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