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 d0ca557..c162140 100644 Binary files a/public/3rd-party-licenses.txt.gz and b/public/3rd-party-licenses.txt.gz differ diff --git a/public/app/about.css.gz b/public/app/about.css.gz index b16d221..c2318f8 100644 Binary files a/public/app/about.css.gz and b/public/app/about.css.gz differ diff --git a/public/app/about.css.map.gz b/public/app/about.css.map.gz index 5ef5ff7..99a2a20 100644 Binary files a/public/app/about.css.map.gz and b/public/app/about.css.map.gz differ diff --git a/public/app/about.js.gz b/public/app/about.js.gz index 3f6223a..8c6bb72 100644 Binary files a/public/app/about.js.gz and b/public/app/about.js.gz differ diff --git a/public/app/app.css.gz b/public/app/app.css.gz index c5e698e..b5c69e8 100644 Binary files a/public/app/app.css.gz and b/public/app/app.css.gz differ diff --git a/public/app/app.css.map.gz b/public/app/app.css.map.gz index 587a79d..77867ca 100644 Binary files a/public/app/app.css.map.gz and b/public/app/app.css.map.gz differ diff --git a/public/app/app.js.gz b/public/app/app.js.gz index 56b4657..9d48f94 100644 Binary files a/public/app/app.js.gz and b/public/app/app.js.gz differ diff --git a/public/app/health.css.gz b/public/app/health.css.gz index 003ffc6..283673d 100644 Binary files a/public/app/health.css.gz and b/public/app/health.css.gz differ diff --git a/public/app/health.css.map.gz b/public/app/health.css.map.gz index 664fcd1..78443a4 100644 Binary files a/public/app/health.css.map.gz and b/public/app/health.css.map.gz differ diff --git a/public/app/health.js.gz b/public/app/health.js.gz index d4fe371..986b4b9 100644 Binary files a/public/app/health.js.gz and b/public/app/health.js.gz differ diff --git a/public/app/install.js.gz b/public/app/install.js.gz index 1b293f9..bf91890 100644 Binary files a/public/app/install.js.gz and b/public/app/install.js.gz differ diff --git a/public/app/settings.css.gz b/public/app/settings.css.gz index 6965760..bd32d6d 100644 Binary files a/public/app/settings.css.gz and b/public/app/settings.css.gz differ diff --git a/public/app/settings.css.map.gz b/public/app/settings.css.map.gz index 917325d..f0e4432 100644 Binary files a/public/app/settings.css.map.gz and b/public/app/settings.css.map.gz differ diff --git a/public/app/settings.js.gz b/public/app/settings.js.gz index f0466db..ded9dbf 100644 Binary files a/public/app/settings.js.gz and b/public/app/settings.js.gz differ diff --git a/public/app/splash.css.gz b/public/app/splash.css.gz index 0d48b91..c8efcc4 100644 Binary files a/public/app/splash.css.gz and b/public/app/splash.css.gz differ diff --git a/public/app/splash.css.map.gz b/public/app/splash.css.map.gz index c22b3b5..d8d40b8 100644 Binary files a/public/app/splash.css.map.gz and b/public/app/splash.css.map.gz differ diff --git a/public/app/splash.js.gz b/public/app/splash.js.gz index 48c5c39..d35575d 100644 Binary files a/public/app/splash.js.gz and b/public/app/splash.js.gz differ diff --git a/tools/linux-x64/sqlite3 b/tools/linux-x64/sqlite3 index e5a68c3..43141e4 100755 Binary files a/tools/linux-x64/sqlite3 and b/tools/linux-x64/sqlite3 differ diff --git a/tools/linux-x64/sqlite3-README.md b/tools/linux-x64/sqlite3-README.md index 72ed9ad..a15da6a 100644 --- a/tools/linux-x64/sqlite3-README.md +++ b/tools/linux-x64/sqlite3-README.md @@ -3,14 +3,15 @@ Applied on Debian 11 x64: ```sh sudo apt install -y build-essential curl -# If using `sh-docker`: - -source <(egrep "^(YEAR|VERSION)=" /code/src/library/node_modules/better-sqlite3/deps/download.sh) +# If using `yarn --cwd src/library sh-docker`: # If you're on an actual debian box: # source <(egrep "^(YEAR|VERSION)=" $HOME/src/photostructure/src/library/node_modules/better-sqlite3/deps/download.sh) +# If using `yarn --cwd src/library sh-docker`: +source <(egrep "^(YEAR|VERSION)=" /code/src/library/node_modules/better-sqlite3/deps/download.sh) + export DEST=/tmp/sqlite-$VERSION mkdir -p $DEST \ @@ -19,9 +20,15 @@ mkdir -p $DEST \ && ./configure --enable-static --disable-readline LDFLAGS="-static -pthread" \ && make clean \ && make -j `nproc` \ - && strip sqlite3 \ - && cp sqlite3 ~/src/photostructure/tools/linux-x64 + && strip sqlite3 + && cp sqlite3 /tmp/sqlite3 +``` + +Then on the host: +# OMG DOCKER CP DOESN'T ACCEPT GLOBS +```sh +docker cp $(docker ps --filter name=photostructure_library --quiet):/tmp/sqlite3 ~/src/photostructure/tools/linux-x64 ``` To validate the binary is static, `ldd` should report "not a dynamic executable:" diff --git a/tools/mac-arm64/sqlite3-README.md b/tools/mac-arm64/sqlite3-README.md index 9cdd5c0..1b20ef2 100644 --- a/tools/mac-arm64/sqlite3-README.md +++ b/tools/mac-arm64/sqlite3-README.md @@ -17,11 +17,12 @@ bash # to avoid zsh brew install curl -YEAR=2022 -VERSION=3400000 +source <(egrep "^(YEAR|VERSION)=" ~/src/photostructure/src/library/node_modules/better-sqlite3/deps/download.sh) -mkdir -p /tmp/sqlite \ - && cd /tmp/sqlite \ +export DEST=/tmp/sqlite-$VERSION + +mkdir -p $DEST \ + && cd $DEST \ && curl https://sqlite.org/$YEAR/sqlite-autoconf-$VERSION.tar.gz | tar -xz --strip 1 \ && ./configure --enable-static-shell --enable-static --disable-readline --disable-shared \ && make clean \ diff --git a/tools/win-x64/sqlite3-README.md b/tools/win-x64/sqlite3-README.md index ff6f4f8..76960fe 100644 --- a/tools/win-x64/sqlite3-README.md +++ b/tools/win-x64/sqlite3-README.md @@ -1,3 +1,3 @@ -Extracted from https://www.sqlite.org/2024/sqlite-tools-win-x64-3450100.zip +Extracted from https://sqlite.org/2024/sqlite-tools-win-x64-3450200.zip -https://www.virustotal.com/gui/file/632027d21b045ff822f594d7481a07fea5a745d71ea191311c8b25158803f0fa +https://www.virustotal.com/gui/file/24d4655fde07743257cc18f7ebb4ca66dee9be7267778fa2db810e5a68edf4f9 \ No newline at end of file diff --git a/tools/win-x64/sqlite3.exe b/tools/win-x64/sqlite3.exe index 9fe7abd..c6bc65d 100755 Binary files a/tools/win-x64/sqlite3.exe and b/tools/win-x64/sqlite3.exe differ diff --git a/yarn.lock b/yarn.lock index 49a9f01..8384a8a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -124,44 +124,44 @@ resolved "https://registry.yarnpkg.com/@photostructure/tz-lookup/-/tz-lookup-9.0.2.tgz#3b03dbedc305c872d9f7b99f78c386f8ba986197" integrity sha512-H8+tTt7ilJNkFyb+QgPnLEGUjQzGwiMb9n7lwRZNBgSKL3VZs9AkjI1E//FcwPjNafwAH932U92+xTqJiF3Bbw== -"@sentry-internal/tracing@7.105.0": - version "7.105.0" - resolved "https://registry.yarnpkg.com/@sentry-internal/tracing/-/tracing-7.105.0.tgz#9cb06f8281454343215cfe4b119c8198f032ec72" - integrity sha512-b+AFYB7Bc9vmyxl2jbmuT4esX5G0oPfpz35A0sxFzmJIhvMg1YMDNio2c81BtKN+VSPORCnKMLhfk3kyKKvWMQ== +"@sentry-internal/tracing@7.107.0": + version "7.107.0" + resolved "https://registry.yarnpkg.com/@sentry-internal/tracing/-/tracing-7.107.0.tgz#a10b4abcbc9e0d8da948e3a95029574387ca7b16" + integrity sha512-le9wM8+OHBbq7m/8P7JUJ1UhSPIty+Z/HmRXc5Z64ODZcOwFV6TmDpYx729IXDdz36XUKmeI+BeM7yQdTTZPfQ== dependencies: - "@sentry/core" "7.105.0" - "@sentry/types" "7.105.0" - "@sentry/utils" "7.105.0" + "@sentry/core" "7.107.0" + "@sentry/types" "7.107.0" + "@sentry/utils" "7.107.0" -"@sentry/core@7.105.0": - version "7.105.0" - resolved "https://registry.yarnpkg.com/@sentry/core/-/core-7.105.0.tgz#89db519dd9aa7326de63a7eaccf861de3769ab1c" - integrity sha512-5xsaTG6jZincTeJUmZomlv20mVRZUEF1U/g89lmrSOybyk2+opEnB1JeBn4ODwnvmSik8r2QLr6/RiYlaxRJCg== +"@sentry/core@7.107.0": + version "7.107.0" + resolved "https://registry.yarnpkg.com/@sentry/core/-/core-7.107.0.tgz#926838ba2c2861d6bd2bced0232e1f9d1ead6c75" + integrity sha512-C7ogye6+KPyBi8NVL0P8Rxx3Ur7Td8ufnjxosVy678lqY+dcYPk/HONROrzUFYW5fMKWL4/KYnwP+x9uHnkDmw== dependencies: - "@sentry/types" "7.105.0" - "@sentry/utils" "7.105.0" + "@sentry/types" "7.107.0" + "@sentry/utils" "7.107.0" -"@sentry/node@7.105.0": - version "7.105.0" - resolved "https://registry.yarnpkg.com/@sentry/node/-/node-7.105.0.tgz#cfe8e5602dff2cc754a95412f44c9ca8156422ff" - integrity sha512-b0QwZ7vT4hcJi6LmNRh3dcaYpLtXnkYXkL0rfhMb8hN8sUx8zuOWFMI7j0cfAloVThUeJVwGyv9dERfzGS2r2w== +"@sentry/node@7.107.0": + version "7.107.0" + resolved "https://registry.yarnpkg.com/@sentry/node/-/node-7.107.0.tgz#d60c2e28953f2ba14d12ada9190f1fc577b2b280" + integrity sha512-UZXkG7uThT2YyPW8AOSKRXp1LbVcBHufa4r1XAwBukA2FKO6HHJPjMUgY6DYVQ6k+BmA56CNfVjYrdLbyjBYYA== dependencies: - "@sentry-internal/tracing" "7.105.0" - "@sentry/core" "7.105.0" - "@sentry/types" "7.105.0" - "@sentry/utils" "7.105.0" + "@sentry-internal/tracing" "7.107.0" + "@sentry/core" "7.107.0" + "@sentry/types" "7.107.0" + "@sentry/utils" "7.107.0" -"@sentry/types@7.105.0": - version "7.105.0" - resolved "https://registry.yarnpkg.com/@sentry/types/-/types-7.105.0.tgz#51dadb7ad650e883459acf18df2ecbb5b4b6e5c2" - integrity sha512-80o0KMVM+X2Ym9hoQxvJetkJJwkpCg7o6tHHFXI+Rp7fawc2iCMTa0IRQMUiSkFvntQLYIdDoNNuKdzz2PbQGA== +"@sentry/types@7.107.0": + version "7.107.0" + resolved "https://registry.yarnpkg.com/@sentry/types/-/types-7.107.0.tgz#5ba4b472be6ccad9aecd58dbc0141a09dafb68c1" + integrity sha512-H7qcPjPSUWHE/Zf5bR1EE24G0pGVuJgrSx8Tvvl5nKEepswMYlbXHRVSDN0gTk/E5Z7cqf+hUBOpkQgZyps77w== -"@sentry/utils@7.105.0": - version "7.105.0" - resolved "https://registry.yarnpkg.com/@sentry/utils/-/utils-7.105.0.tgz#727187d252b97cb9e6c78bcdd0e9a1d14e60f313" - integrity sha512-YVAV0c2KLM8+VZCicQ/E/P2+J9Vs0hGhrXwV7w6ZEAtvxrg4oF270toL1WRhvcaf8JO4J1v4V+LuU6Txs4uEeQ== +"@sentry/utils@7.107.0": + version "7.107.0" + resolved "https://registry.yarnpkg.com/@sentry/utils/-/utils-7.107.0.tgz#b8524539d052a40f9c5f34a8347501f0f81a0751" + integrity sha512-C6PbN5gHh73MRHohnReeQ60N8rrLYa9LciHue3Ru2290eSThg4CzsPnx4SzkGpkSeVlhhptKtKZ+hp/ha3iVuw== dependencies: - "@sentry/types" "7.105.0" + "@sentry/types" "7.107.0" "@sindresorhus/df@^1.0.1": version "1.0.1" @@ -492,11 +492,6 @@ cookie-signature@1.0.7: resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.7.tgz#ab5dd7ab757c54e60f37ef6550f481c426d10454" integrity sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA== -cookie@0.5.0: - version "0.5.0" - resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.5.0.tgz#d1f5d71adec6558c58f389987c366aa47e994f8b" - integrity sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw== - cookie@0.6.0: version "0.6.0" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.6.0.tgz#2798b04b071b0ecbff0dbb62a505a8efa4e19051" @@ -695,17 +690,17 @@ express-session@1.18.0: safe-buffer "5.2.1" uid-safe "~2.1.5" -express@4.18.3: - version "4.18.3" - resolved "https://registry.yarnpkg.com/express/-/express-4.18.3.tgz#6870746f3ff904dee1819b82e4b51509afffb0d4" - integrity sha512-6VyCijWQ+9O7WuVMTRBTl+cjNNIzD5cY5mQ1WM8r/LEkI2u8EYpOotESNwzNlyCn3g+dmjKYI6BmNneSr/FSRw== +express@4.19.1: + version "4.19.1" + resolved "https://registry.yarnpkg.com/express/-/express-4.19.1.tgz#4700635795e911600a45596138cf5b0320e78256" + integrity sha512-K4w1/Bp7y8iSiVObmCrtq8Cs79XjJc/RU2YYkZQ7wpUu5ZyZ7MtPHkqoMz4pf+mgXfNvo2qft8D9OnrH2ABk9w== dependencies: accepts "~1.3.8" array-flatten "1.1.1" body-parser "1.20.2" content-disposition "0.5.4" content-type "~1.0.4" - cookie "0.5.0" + cookie "0.6.0" cookie-signature "1.0.6" debug "2.6.9" depd "2.0.0" @@ -737,10 +732,10 @@ fast-fifo@^1.1.0, fast-fifo@^1.2.0: resolved "https://registry.yarnpkg.com/fast-fifo/-/fast-fifo-1.3.2.tgz#286e31de96eb96d38a97899815740ba2a4f3640c" integrity sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ== -fast-xml-parser@4.3.5: - version "4.3.5" - resolved "https://registry.yarnpkg.com/fast-xml-parser/-/fast-xml-parser-4.3.5.tgz#e2f2a2ae8377e9c3dc321b151e58f420ca7e5ccc" - integrity sha512-sWvP1Pl8H03B8oFJpFR3HE31HUfwtX7Rlf9BNsvdpujD4n7WMhfmu8h9wOV2u+c1k0ZilTADhPqypzx2J690ZQ== +fast-xml-parser@4.3.6: + version "4.3.6" + resolved "https://registry.yarnpkg.com/fast-xml-parser/-/fast-xml-parser-4.3.6.tgz#190f9d99097f0c8f2d3a0e681a10404afca052ff" + integrity sha512-M2SovcRxD4+vC493Uc2GZVcZaj66CCJhWurC4viynVSTvrpErCShNcDz1lAho6n9REQKvL/ll4A4/fw6Y9z8nw== dependencies: strnum "^1.0.5" @@ -1643,10 +1638,10 @@ pump@^3.0.0: end-of-stream "^1.1.0" once "^1.3.1" -punycode@2.3.1: +punycode.js@2.3.1: version "2.3.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.1.tgz#027422e2faec0b25e1549c3e1bd8309b9133b6e5" - integrity sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg== + resolved "https://registry.yarnpkg.com/punycode.js/-/punycode.js-2.3.1.tgz#6b53e56ad75588234e79f4affa90972c7dd8cdb7" + integrity sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA== qs@6.11.0: version "6.11.0"