@devvit/public-api 0.12.0-next-2025-03-31-fec8fadd5.0 → 0.12.0-next-2025-04-10-2ee75c532.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apis/makeAPIClients.d.ts.map +1 -1
- package/apis/makeAPIClients.js +0 -3
- package/apis/reddit/RedditAPIClient.d.ts +37 -1
- package/apis/reddit/RedditAPIClient.d.ts.map +1 -1
- package/apis/reddit/RedditAPIClient.js +150 -113
- package/apis/reddit/common.d.ts +4 -1
- package/apis/reddit/common.d.ts.map +1 -1
- package/apis/reddit/index.d.ts +1104 -0
- package/apis/reddit/index.d.ts.map +1 -0
- package/apis/reddit/index.js +1435 -0
- package/apis/reddit/models/Comment.d.ts +2 -0
- package/apis/reddit/models/Comment.d.ts.map +1 -1
- package/apis/reddit/models/Comment.js +6 -2
- package/apis/reddit/models/ModAction.d.ts +0 -3
- package/apis/reddit/models/ModAction.d.ts.map +1 -1
- package/apis/reddit/models/ModAction.js +2 -1
- package/apis/reddit/models/Post.d.ts +3 -0
- package/apis/reddit/models/Post.d.ts.map +1 -1
- package/apis/reddit/models/Post.js +16 -7
- package/apis/reddit/models/Subreddit.d.ts +1 -19
- package/apis/reddit/models/Subreddit.d.ts.map +1 -1
- package/apis/reddit/models/Subreddit.js +15 -9
- package/apis/reddit/models/User.js +13 -0
- package/apis/reddit/models/Vault.d.ts +0 -3
- package/apis/reddit/models/Vault.d.ts.map +1 -1
- package/apis/reddit/models/Vault.js +7 -2
- package/apis/reddit/models/index.d.ts +1 -1
- package/apis/reddit/models/index.d.ts.map +1 -1
- package/apis/reddit/models/index.js +0 -1
- package/apis/reddit/tests/utils/createTestRedditApiContext.d.ts +7 -0
- package/apis/reddit/tests/utils/createTestRedditApiContext.d.ts.map +1 -0
- package/apis/reddit/tests/utils/{createTestRedditApiClient.js → createTestRedditApiContext.js} +12 -5
- package/apis/settings/SettingsClient.d.ts +3 -1
- package/apis/settings/SettingsClient.d.ts.map +1 -1
- package/apis/settings/SettingsClient.js +34 -0
- package/devvit/Devvit.d.ts.map +1 -1
- package/devvit/Devvit.js +11 -0
- package/devvit/internals/async-metadata.d.ts +2 -0
- package/devvit/internals/async-metadata.d.ts.map +1 -0
- package/devvit/internals/async-metadata.js +65 -0
- package/devvit/internals/blocks/BlocksReconciler.d.ts.map +1 -1
- package/devvit/internals/blocks/BlocksReconciler.js +12 -14
- package/devvit/internals/blocks/handler/BlocksHandler.d.ts.map +1 -1
- package/devvit/internals/blocks/handler/BlocksHandler.js +6 -3
- package/devvit/internals/blocks/handler/ContextBuilder.d.ts.map +1 -1
- package/devvit/internals/blocks/handler/ContextBuilder.js +0 -3
- package/devvit/internals/blocks/handler/useWebView.d.ts.map +1 -1
- package/devvit/internals/blocks/handler/useWebView.js +9 -8
- package/devvit/internals/context.d.ts.map +1 -1
- package/devvit/internals/context.js +3 -1
- package/devvit/internals/csrf.d.ts.map +1 -1
- package/devvit/internals/csrf.js +7 -8
- package/devvit/internals/helpers/devvitInternalMessage.d.ts +12 -0
- package/devvit/internals/helpers/devvitInternalMessage.d.ts.map +1 -0
- package/devvit/internals/helpers/devvitInternalMessage.js +17 -0
- package/devvit/internals/helpers/extendDevvitPrototype.d.ts +6 -1
- package/devvit/internals/helpers/extendDevvitPrototype.d.ts.map +1 -1
- package/devvit/internals/helpers/extendDevvitPrototype.js +9 -1
- package/devvit/internals/menu-items.d.ts.map +1 -1
- package/index.d.ts +2 -1
- package/index.d.ts.map +1 -1
- package/index.js +2 -0
- package/meta.json +231 -154
- package/meta.min.json +281 -127
- package/package.json +9 -9
- package/public-api.d.ts +2706 -2060
- package/public-api.iife.js +1734 -2217
- package/public-api.min.js +6 -6
- package/public-api.min.js.map +4 -4
- package/types/configuration.d.ts +2 -0
- package/types/configuration.d.ts.map +1 -1
- package/types/context.d.ts +2 -4
- package/types/context.d.ts.map +1 -1
- package/version.json +2 -2
- package/apis/reddit/tests/utils/createTestRedditApiClient.d.ts +0 -7
- package/apis/reddit/tests/utils/createTestRedditApiClient.d.ts.map +0 -1
package/public-api.min.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var Rc=Object.create;var id=Object.defineProperty;var Oc=Object.getOwnPropertyDescriptor;var Mc=Object.getOwnPropertyNames;var Bc=Object.getPrototypeOf,Uc=Object.prototype.hasOwnProperty;var rd=r=>{throw TypeError(r)};var ei=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Dc=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Mc(e))!Uc.call(r,s)&&s!==t&&id(r,s,{get:()=>e[s],enumerable:!(i=Oc(e,s))||i.enumerable});return r};var nd=(r,e,t)=>(t=r!=null?Rc(Bc(r)):{},Dc(e||!r||!r.__esModule?id(t,"default",{value:r,enumerable:!0}):t,r));var No=(r,e,t)=>e.has(r)||rd("Cannot "+t);var n=(r,e,t)=>(No(r,e,"read from private field"),t?t.call(r):e.get(r)),l=(r,e,t)=>e.has(r)?rd("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),a=(r,e,t,i)=>(No(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),h=(r,e,t)=>(No(r,e,"access private method"),t);var sd=(r,e,t,i)=>({set _(s){a(r,e,s,t)},get _(){return n(r,e,i)}});var pa=ei((ob,bl)=>{var Xm=Object.prototype.toString;bl.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var t=typeof e;if(t==="boolean")return"boolean";if(t==="string")return"string";if(t==="number")return"number";if(t==="symbol")return"symbol";if(t==="function")return ip(e)?"generatorfunction":"function";if(Qm(e))return"array";if(sp(e))return"buffer";if(np(e))return"arguments";if(ep(e))return"date";if(Ym(e))return"error";if(tp(e))return"regexp";switch(yl(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(rp(e))return"generator";switch(t=Xm.call(e),t){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")};function yl(r){return typeof r.constructor=="function"?r.constructor.name:null}function Qm(r){return Array.isArray?Array.isArray(r):r instanceof Array}function Ym(r){return r instanceof Error||typeof r.message=="string"&&r.constructor&&typeof r.constructor.stackTraceLimit=="number"}function ep(r){return r instanceof Date?!0:typeof r.toDateString=="function"&&typeof r.getDate=="function"&&typeof r.setDate=="function"}function tp(r){return r instanceof RegExp?!0:typeof r.flags=="string"&&typeof r.ignoreCase=="boolean"&&typeof r.multiline=="boolean"&&typeof r.global=="boolean"}function ip(r,e){return yl(r)==="GeneratorFunction"}function rp(r){return typeof r.throw=="function"&&typeof r.return=="function"&&typeof r.next=="function"}function np(r){try{if(typeof r.length=="number"&&typeof r.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function sp(r){return r.constructor&&typeof r.constructor.isBuffer=="function"?r.constructor.isBuffer(r):!1}});var Cl=ei((ab,kl)=>{"use strict";var vl=Symbol.prototype.valueOf,op=pa();function ap(r,e){switch(op(r)){case"array":return r.slice();case"object":return Object.assign({},r);case"date":return new r.constructor(Number(r));case"map":return new Map(r);case"set":return new Set(r);case"buffer":return cp(r);case"symbol":return mp(r);case"arraybuffer":return lp(r);case"float32array":case"float64array":case"int16array":case"int32array":case"int8array":case"uint16array":case"uint32array":case"uint8clampedarray":case"uint8array":return up(r);case"regexp":return dp(r);case"error":return Object.create(r);default:return r}}function dp(r){let e=r.flags!==void 0?r.flags:/\w+$/.exec(r)||void 0,t=new r.constructor(r.source,e);return t.lastIndex=r.lastIndex,t}function lp(r){let e=new r.constructor(r.byteLength);return new Uint8Array(e).set(new Uint8Array(r)),e}function up(r,e){return new r.constructor(r.buffer,r.byteOffset,r.length)}function cp(r){let e=r.length,t=Buffer.allocUnsafe?Buffer.allocUnsafe(e):Buffer.from(e);return r.copy(t),t}function mp(r){return vl?Object(vl.call(r)):{}}kl.exports=ap});var Sl=ei((db,Pl)=>{"use strict";Pl.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var xl=ei((lb,Fl)=>{"use strict";var pp=Sl();function wl(r){return pp(r)===!0&&Object.prototype.toString.call(r)==="[object Object]"}Fl.exports=function(e){var t,i;return!(wl(e)===!1||(t=e.constructor,typeof t!="function")||(i=t.prototype,wl(i)===!1)||i.hasOwnProperty("isPrototypeOf")===!1)}});var Al=ei((ub,Il)=>{"use strict";var gp=Cl(),hp=pa(),fp=xl();function ga(r,e){switch(hp(r)){case"object":return yp(r,e);case"array":return bp(r,e);default:return gp(r)}}function yp(r,e){if(typeof e=="function")return e(r);if(e||fp(r)){let t=new r.constructor;for(let i in r)t[i]=ga(r[i],e);return t}return r}function bp(r,e){let t=new r.constructor(r.length);for(let i=0;i<r.length;i++)t[i]=ga(r[i],e);return t}Il.exports=ga});var bc=ei(vo=>{"use strict";vo.byteLength=qp;vo.toByteArray=Kp;vo.fromByteArray=Qp;var Me=[],Se=[],zp=typeof Uint8Array<"u"?Uint8Array:Array,Ja="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Jt=0,fc=Ja.length;Jt<fc;++Jt)Me[Jt]=Ja[Jt],Se[Ja.charCodeAt(Jt)]=Jt;var Jt,fc;Se[45]=62;Se[95]=63;function yc(r){var e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var i=t===e?0:4-t%4;return[t,i]}function qp(r){var e=yc(r),t=e[0],i=e[1];return(t+i)*3/4-i}function $p(r,e,t){return(e+t)*3/4-t}function Kp(r){var e,t=yc(r),i=t[0],s=t[1],o=new zp($p(r,i,s)),d=0,c=s>0?i-4:i,m;for(m=0;m<c;m+=4)e=Se[r.charCodeAt(m)]<<18|Se[r.charCodeAt(m+1)]<<12|Se[r.charCodeAt(m+2)]<<6|Se[r.charCodeAt(m+3)],o[d++]=e>>16&255,o[d++]=e>>8&255,o[d++]=e&255;return s===2&&(e=Se[r.charCodeAt(m)]<<2|Se[r.charCodeAt(m+1)]>>4,o[d++]=e&255),s===1&&(e=Se[r.charCodeAt(m)]<<10|Se[r.charCodeAt(m+1)]<<4|Se[r.charCodeAt(m+2)]>>2,o[d++]=e>>8&255,o[d++]=e&255),o}function Zp(r){return Me[r>>18&63]+Me[r>>12&63]+Me[r>>6&63]+Me[r&63]}function Xp(r,e,t){for(var i,s=[],o=e;o<t;o+=3)i=(r[o]<<16&16711680)+(r[o+1]<<8&65280)+(r[o+2]&255),s.push(Zp(i));return s.join("")}function Qp(r){for(var e,t=r.length,i=t%3,s=[],o=16383,d=0,c=t-i;d<c;d+=o)s.push(Xp(r,d,d+o>c?c:d+o));return i===1?(e=r[t-1],s.push(Me[e>>2]+Me[e<<4&63]+"==")):i===2&&(e=(r[t-2]<<8)+r[t-1],s.push(Me[e>>10]+Me[e>>4&63]+Me[e<<2&63]+"=")),s.join("")}});function p(r,e){if(r==null)throw Error(e??"Expected nonnullish value.")}function wt(r,e){if(!r)throw Error(e)}var ee;(function(r){r.COMMENT="t1_",r.ACCOUNT="t2_",r.LINK="t3_",r.MESSAGE="t4_",r.SUBREDDIT="t5_",r.AWARD="t6_"})(ee||(ee={}));function Ge(r){return r.startsWith(ee.COMMENT)}function Ds(r){return r.startsWith(ee.ACCOUNT)}function Ft(r){return r.startsWith(ee.LINK)}function od(r){return r.startsWith(ee.MESSAGE)}function ad(r){return r.startsWith(ee.SUBREDDIT)}function dd(r){return r.startsWith(ee.AWARD)}function Nc(r){wt(Ge(r),`Expected comment id to start with ${ee.COMMENT}, got ${r}}`)}function Lc(r){wt(Ds(r),`Expected account id to start with ${ee.ACCOUNT}, got ${r}}`)}function _c(r){wt(Ft(r),`Expected link id to start with ${ee.LINK}, got ${r}}`)}function Hc(r){wt(od(r),`Expected message id to start with ${ee.MESSAGE}, got ${r}}`)}function jc(r){wt(ad(r),`Expected subreddit id to start with ${ee.SUBREDDIT}, got ${r}}`)}function Vc(r){wt(dd(r),`Expected award id to start with ${ee.AWARD}, got ${r}}`)}function ti(r){return Nc(r),r}function te(r){return Lc(r),r}function de(r){return _c(r),r}function Wc(r){return Hc(r),r}function K(r){return jc(r),r}function Gc(r){return Vc(r),r}function fe(r){if(Ge(r))return ti(r);if(Ds(r))return te(r);if(Ft(r))return de(r);if(od(r))return Wc(r);if(ad(r))return K(r);if(dd(r))return Gc(r);throw new Error(`Expected thing id to start with ${Object.values(ee).join(", ")} got ${r}}`)}function Lo(r){return Ge(r)}import*as k from"@devvit/protos";var Ns=class{constructor(e){}};var _o=(t=>(t.Installation="installation",t.App="app",t))(_o||{});function xt(r,e=new Set){for(let t of r){if(t.type==="group"){xt(t.fields,e);continue}let i=t.name;if(e.has(i))throw new Error(`Duplicate field name: ${i}`);e.add(i)}Jc(r)}function Jc(r){for(let e of r)if(e.type==="string"&&e.isSecret&&e.scope!=="app")throw`Invalid setting: only app settings can be secrets. Add "scope: SettingScope.App" to field "${e.name}"`}var Je=Object.freeze({INTERVAL:0,FORM:1,STATE:2,CHANNEL:3,WEB_VIEW:4});var Mg=["3rd-party","activity","add-emoji","add","add-media","add-to-feed","admin","ads","ai","align-center","align-left","align-right","all","ama","appearance","approve","archived","aspect-ratio","aspect-rectangle","attach","audience","audio","author","automod","avatar-style","award","back","backup","ban","best","block","blockchain","bold","boost","bot","bounce","brand-awareness","browse","browser","cake","calendar","camera","campaign","caret-down","caret-left","caret-right","caret-up","chat","chat-group","chat-new","chat-private","checkbox-dismiss","checkbox","checkmark","chrome","clear","client-list","close","closed-captioning","code-block","code-inline","coins-color-old","coins","collapse-left","collapse-right","collectible-expressions","collection","comment","comments","communities","community","confidence","contest","controversial","conversion","copy-clipboard","crop","crosspost","crowd-control","custom-feed","customize","dashboard","day","delete-column","delete","delete-row","devvit","discover","dismiss-all","distinguish","down-arrow","down","download","downvote","downvotes","drag","drugs","duplicate","edit","effect","embed","emoji","end-live-chat","error","expand-left","expand-right","external","feed-video","filter","format","forward","funnel","gif-post","gold","hashtag","heart","help","hide","history","home","hot","ignore-reports","image-post","inbox","info","insert-column-left","insert-column-right","insert-row-above","insert-row-below","internet","invite","italic","join","joined","jump-down","jump-up","karma","keyboard","kick","language","leave","left","link","link-post","list-bulleted","list-numbered","live-chat","live","load","location","lock","logout","loop","macro","mark-read","marketplace","mask","media-gallery","meme","menu","message","mic","mic-mute","mod","mod-mail","mod-mode","mod-mute","mod-overflow","mod-queue","mod-unmute","music","mute","new","night","no-internet","notification","notification-frequent","notification-off","nsfw","nsfw-language","nsfw-violence","official","original","overflow-caret","overflow-horizontal","overflow-vertical","pause","payment","peace","pending-posts","phone","pin","play","poll-post","popular","posts","powerup","predictions","premium","privacy","profile","qa","qr-code","quarantined","quote","r-slash","radar","radio-button","raise-hand","random","ratings-everyone","ratings-mature","ratings-nsfw","ratings-violence","recovery-phrase","refresh","removal-reasons","remove","reply","report","reverse","rich-text","right","rising","rotate","rotate-image","rpan","rules","safari","save","save-view","saved","saved-response","search","self","send","settings","severity","share","share-new","show","side-menu","skipback10","skipforward10","sort-az","sort","sort-price","sort-za","spam","spoiler","sponsored","spreadsheet","star","statistics","status-live","sticker","strikethrough","subtract","superscript","swap-camera","swipe-back","swipe-down","swipe","swipe-up","table","tag","tap","text","text-post","text-size","toggle","tools","top","topic-activism","topic-addictionsupport","topic-advice","topic-animals","topic-anime","topic-art","topic-beauty","topic-business","topic-careers","topic-cars","topic-celebrity","topic-craftsdiy","topic-crypto","topic-culture","topic-diy","topic-entertainment","topic-ethics","topic-family","topic-fashion","topic","topic-fitness","topic-food","topic-funny","topic-gender","topic-health","topic-help","topic-history","topic-hobbies","topic-homegarden","topic-internet","topic-law","topic-learning","topic-lifestyle","topic-marketplace","topic-mature","topic-mensfashion","topic-menshealth","topic-meta","topic-military","topic-movies","topic-music","topic-news","topic-other","topic-outdoors","topic-pets","topic-photography","topic-places","topic-podcasts","topic-politics","topic-programming","topic-reading","topic-religion","topic-science","topic-sexorientation","topic-sports","topic-style","topic-tabletop","topic-technology","topic-television","topic-traumasupport","topic-travel","topic-videogaming","topic-womensfashion","topic-womenshealth","translate","translation-off","trim","u-slash","unban","undo","unheart","unlock","unmod","unpin","unstar","unverified","up-arrow","up","upload","upvote","upvotes","user","user-note","users","vault","verified","video-camera","video-feed","video-post","video-thread","video-transcription","view-card","view-classic","view-compact","view-grid","view-sort","views","volume","wallet","warning","webhook","whale","wiki-ban","wiki","wiki-unban","world","coins-color","powerup-color","powerup-fill-color","share-android","share-ios","video-live-1","video-live-fill-1","video-live","volume-mute","binoculars","caret-updown","planet","telescope"];import{DeletionReason as Ng,EventSource as Lg}from"@devvit/protos";import{AppSettingsDefinition as am,GetFieldsResponse as dm}from"@devvit/protos";import{FormFieldType as ye}from"@devvit/protos";function De(r){return r.map(e=>{switch(e.type){case"string":return zc(e);case"image":return qc(e);case"paragraph":return $c(e);case"number":return Kc(e);case"select":return Zc(e);case"boolean":return Xc(e);case"group":return Qc(e);default:throw new Error("Unknown field type.")}})}function zc(r){return{defaultValue:{fieldType:ye.STRING,stringValue:r.defaultValue},disabled:r.disabled,fieldConfig:{stringConfig:{placeholder:r.placeholder}},fieldId:r.name,fieldType:ye.STRING,helpText:r.helpText,label:r.label,required:r.required,isSecret:r.isSecret}}function qc(r){return{disabled:r.disabled,fieldId:r.name,fieldType:ye.IMAGE,helpText:r.helpText,label:r.label,required:r.required}}function $c(r){return{defaultValue:{fieldType:ye.PARAGRAPH,stringValue:r.defaultValue},disabled:r.disabled,fieldConfig:{paragraphConfig:{lineHeight:r.lineHeight,placeholder:r.placeholder}},fieldId:r.name,fieldType:ye.PARAGRAPH,helpText:r.helpText,label:r.label,required:r.required}}function Kc(r){return{defaultValue:{fieldType:ye.NUMBER,numberValue:r.defaultValue},disabled:r.disabled,fieldConfig:{numberConfig:{}},fieldId:r.name,fieldType:ye.NUMBER,helpText:r.helpText,label:r.label,required:r.required}}function Zc(r){return{defaultValue:{fieldType:ye.SELECTION,selectionValue:{values:r.defaultValue??[]}},disabled:r.disabled,fieldConfig:{selectionConfig:{choices:r.options,multiSelect:r.multiSelect}},fieldId:r.name,fieldType:ye.SELECTION,helpText:r.helpText,label:r.label,required:r.required}}function Xc(r){return{defaultValue:{fieldType:ye.BOOLEAN,boolValue:r.defaultValue},disabled:r.disabled,fieldId:r.name,fieldType:ye.BOOLEAN,helpText:r.helpText,label:r.label}}function Qc(r){return{fieldId:"",fieldType:ye.GROUP,fieldConfig:{groupConfig:{fields:De(r.fields)}},label:r.label,helpText:r.helpText}}function O(r,e){u.prototype[r]=e}import{ValidateFormResponse as om}from"@devvit/protos";import{RealtimeSubscriptionStatus as ud}from"@devvit/protos";var S=Object.freeze({Actor:"devvit-actor",App:"devvit-app",AppUser:"devvit-app-user",AppViewerAuthToken:"devvit-app-viewer-authorization",Caller:"devvit-caller",CallerPortID:"devvit-caller-port-id",Canary:"devvit-canary",Debug:"devvit-debug",GQLHost:"devvit-gql-host",Installation:"devvit-installation",ModPermissions:"devvit-mod-permissions",Post:"devvit-post",PostAuthor:"devvit-post-author",R2Auth:"devvit-sec-authorization",R2Host:"devvit-r2-host",RemoteHostname:"devvit-remote-hostname",SettingsUri:"devvit-sec-settings-uri",StreamID:"devvit-stream-id",Subreddit:"devvit-subreddit",SubredditName:"devvit-subreddit-name",TraceID:"devvit-trace-id",User:"devvit-user",Username:"devvit-user-name",UserAgent:"devvit-user-agent",Version:"devvit-version",Language:"devvit-accept-language",Timezone:"devvit-accept-timezone",Traceparent:"traceparent",AppDependencies:"devvit-app-dependencies"}),ld;(function(r){r.Blocks="blocks",r.EmitSnapshots="emitSnapshots",r.EmitState="emitState",r.Realtime="realtime",r.Runtime="runtime",r.Surface="surface",r.UseAsync="useAsync",r.Payments="payments",r.Bootstrap="bootstrap",r.WebView="webView"})(ld||(ld={}));function cd(r){function e(t){let s=r.currentHookIndex,o=r.getCurrentComponentState(),d=r.getPreviousComponentState(),c=r.metadata[S.App]?.values[0];p(c,"useChannel - app is missing from Context");let m=r.metadata[S.Installation]?.values[0];p(m,"useChannel - installation is missing from Context");async function y(H){let M=o[s].channel;if(o[s].active)if(o[s].connected)await r.realtime.send(M,H);else throw Error(`Failed to send to channel '${M}'; it is active but not yet connected`);else throw Error(`Cannot send a message over inactive channel: ${M}`)}function v(){if(!o[s].active){let H=o[s].channel;o[s].active=!0,r.addRealtimeChannel(H)}}function f(){if(o[s].active){let H=o[s].channel;o[s].active=!1,r.removeRealtimeChannel(H)}}function P(H){return async()=>{let M;switch(H.status){case ud.REALTIME_SUBSCRIBED:o[s].connected=!0,M=t.onSubscribed?.();break;case ud.REALTIME_UNSUBSCRIBED:o[s].connected=!1,M=t.onUnsubscribed?.();break;default:M=t.onMessage(H.event?.data?.msg);break}await M}}let b={channel:`${c}:${m}:${t.name}`,active:!1,connected:!1,preventCallback:!1,type:Je.CHANNEL};s in o?b=o[s]:s in d&&(b=d[s]);let W=r.realtimeEvent;r.isInitialRender?b.active=!1:W&&b.active&&W.event.channel===b.channel&&(b.preventCallback||r.runHook(P(W)),r.rerenderIn(0)),o[s]=b,r.currentHookIndex++;let R=0;return b.active&&b.connected?R=2:b.active&&!b.connected?R=1:!b.active&&b.connected?R=3:!b.active&&!b.connected&&(R=4),{subscribe:v,unsubscribe:f,send:y,status:R}}return e}import{FormFieldType as ii}from"@devvit/protos";function Ho(r){switch(r.fieldType){case ii.STRING:return r.stringValue;case ii.IMAGE:return r.stringValue;case ii.PARAGRAPH:return r.stringValue;case ii.NUMBER:return r.numberValue;case ii.BOOLEAN:return r.boolValue;case ii.SELECTION:return r.selectionValue?.values??[];default:return}}function ze(r){return Object.keys(r).reduce((e,t)=>{let i=Ho(r[t]);return i!==void 0&&(e[t]=i),e},{})}function md(r){function e(t,i){let s=r.currentHookIndex,o=r.getCurrentComponentKey(),d=r.getCurrentComponentState(),c=r.getPreviousComponentState(),m=`form.hook.${o}.${s}`,y={formKey:m,preventSubmit:!1,type:Je.FORM};s in d?y=d[s]:s in c&&(y=c[s]),d[s]=y,r.forms.set(m,t);let v=r.formSubmittedEvent;return v&&!y.preventSubmit&&v.formId===m&&r.runHook(async()=>{let f=i(ze(v.results));f&&f instanceof Promise&&await f,r.rerenderIn(0)}),d[s].preventSubmit=!1,r.currentHookIndex++,m}return e}function pd(r){function e(t,i){let s=r.currentHookIndex,o=r.getCurrentComponentState(),d=r.getPreviousComponentState(),c=100,m=Math.max(c,i),y={lastRun:void 0,running:!1,preventCallback:!1,type:Je.INTERVAL};s in o?y=o[s]:s in d&&(y=d[s]);function v(){i<c&&console.error(`useInterval delay must be at least ${c}ms. Your interval of ${i}ms was automatically extended.`);for(let[P,b]of Object.entries(o))if(P!==s.toString()&&b?.type===Je.INTERVAL&&b?.running)throw new Error("Only one useInterval hook may be running at a time");o[s]={running:!0,lastRun:o[s]?.lastRun??Date.now(),preventCallback:!1,type:Je.INTERVAL},r.rerenderIn(m)}function f(){o[s].running=!1,o[s].lastRun=void 0,o[s].preventCallback=!1}return r.isEffectRender&&y.running&&(y.preventCallback||(y.lastRun===void 0||y.lastRun+m<Date.now())&&r.runHook(async()=>{let P=t();P&&P instanceof Promise&&await P,y.lastRun=Date.now()}),r.rerenderIn(m)),y.preventCallback=!1,o[s]=y,r.currentHookIndex++,{start:v,stop:f}}return e}function gd(r){function e(t){let i=r.currentHookIndex,s=r.getCurrentComponentState(),o=r.getPreviousComponentState();if(i in s)return r.currentHookIndex++,[s[i],d];if(r.isInitialRender||!(i in o)){let c=t instanceof Function?t():t;if(c instanceof Promise)throw(async()=>{s[i]=await c,r.currentHookIndex=0})();s[i]=c}else s[i]=o[i];function d(c){if(r.isRendering)throw new Error("Cannot call setState while rendering.");s[i]=c instanceof Function?c(s[i]):c}return r.currentHookIndex++,[s[i],d]}return e}var Go={now(){return new Date}};function hd(r){return`__autocache__${r}`}function fd(r){return`__lock__${r}`}var em=300,tm=1e3,Ls=5e3,jo=3,yd=.1,bd=1e3,im=3e4;function vd(r){if(r.error)throw new Error(r.error);return r.value}var qe,$e,be,ri,z,kd,Cd,Pd,Vo,Sd,wd,Wo,Fd,_s=class{constructor(e,t,i=Go){l(this,z);l(this,qe);l(this,$e,{});l(this,be);l(this,ri);a(this,qe,e),a(this,ri,t),a(this,be,i)}async cache(e,t){a(this,$e,n(this,ri).__cache=n(this,ri).__cache??{}),h(this,z,Fd).call(this,t);let i=h(this,z,kd).call(this,t.key);if(i!==void 0)return i;let s=await h(this,z,Wo).call(this,t.key),o=await h(this,z,Cd).call(this,t,s,e);return vd(o)}};qe=new WeakMap,$e=new WeakMap,be=new WeakMap,ri=new WeakMap,z=new WeakSet,kd=function(e){let t=n(this,$e)[e];if(t){let i=n(this,be).now().getTime(),s=t?.error&&t?.errorTime&&t.errorCount<jo&&Math.random()<yd&&t.errorTime+bd<i;if(t?.expires&&t.expires<i&&t.checkedAt+bd<i||s){delete n(this,$e)[e];return}else return vd(t)}},Cd=async function(e,t,i){let s=t?.expires,o=s?h(this,z,wd).call(this,s):1;return!t||t?.error&&t.errorCount<jo&&yd>Math.random()||o>Math.random()?h(this,z,Pd).call(this,e,t,i):t},Pd=async function(e,t,i){let s=fd(e.key),o=n(this,be).now().getTime(),d=new Date(o+e.ttl/2);if(await n(this,qe).set(s,"1",{expiration:d,nx:!0}))return h(this,z,Sd).call(this,e.key,t,i,e.ttl);if(t)return t;{let m=n(this,be).now();return h(this,z,Vo).call(this,m,e.key,e.ttl)}},Vo=async function(e,t,i){let s=Math.min(i,tm),o=await h(this,z,Wo).call(this,t);if(o)return o;if(n(this,be).now().getTime()-e.getTime()>=s)throw new Error(`Cache request timed out trying to get data at key: ${t}`);return await new Promise(d=>setTimeout(d,em)),h(this,z,Vo).call(this,e,t,i)},Sd=async function(e,t,i,s){let o=n(this,be).now().getTime()+s;t=t??{value:null,expires:o,errorCount:0,error:null,errorTime:null,checkedAt:0};try{t.value=await i(),t.error=null,t.errorCount=0,t.errorTime=null}catch(d){t.value=null,t.error=d.message??"Unknown error",t.errorTime=n(this,be).now().getTime(),t.errorCount++}return n(this,$e)[e]=t,await n(this,qe).set(hd(e),JSON.stringify(t),{expiration:new Date(o+im)}),t.error&&t.errorCount<jo&&await n(this,qe).del(fd(e)),t},wd=function(e){let t=n(this,be).now().getTime(),i=e-t;return i<0?1:i<1e3?.1:i<2e3?.01:i<3e3?.001:0},Wo=async function(e){let t=await n(this,qe).get(hd(e));if(t){let i=JSON.parse(t);return i.checkedAt=n(this,be).now().getTime(),n(this,$e)[e]=i,i}},Fd=function(e){e.ttl<Ls&&(console.warn(`Cache TTL cannot be less than ${Ls} milliseconds! Updating ttl value of ${e.ttl} to ${Ls}.`),e.ttl=Ls)};function xd(r,e,t=Go){let i=new _s(r,e,t);return i.cache.bind(i)}function Id(r){new URL(r.slice(0,r.indexOf(",")))}var ni,si,ai,Ad,Ed,oi=class{constructor(){l(this,ai);l(this,ni,{});l(this,si,{});a(this,ni,u.assets),a(this,si,u.webViewAssets)}getURL(e,t){return typeof e=="string"?h(this,ai,Ad).call(this,e,t??{webView:!1}):h(this,ai,Ed).call(this,e,t??{webView:!1})}};ni=new WeakMap,si=new WeakMap,ai=new WeakSet,Ad=function(e,t){let i=t.webView?n(this,si)[e]:n(this,ni)[e];if(i)return i;try{return Id(e),e}catch{return""}},Ed=function(e,t){let i={},s=[],o=t.webView?n(this,si):n(this,ni);if(o)for(let d of e)if(o[d])i[d]=o[d];else try{Id(d),i[d]=d}catch{s.push(d)}else s=e;if(s.length>0)throw new Error(`The following assets were missing from the assets list: ${s.join(", ")}`);return i};var Ke,di=class{constructor(e){l(this,Ke);a(this,Ke,e)}async get(e){let{messages:t}=await u.kvStorePlugin.Get({keys:[e]},n(this,Ke));try{if(t[e])return JSON.parse(t[e])}catch{return}}async put(e,t){let i={};i[e]=JSON.stringify(t),await u.kvStorePlugin.Put({messages:i},n(this,Ke))}async delete(e){await u.kvStorePlugin.Del({keys:[e]},n(this,Ke))}async list(){let{keys:e}=await u.kvStorePlugin.List({filter:"*"},n(this,Ke));return e}};Ke=new WeakMap;var Rr,li=class{constructor(e){l(this,Rr);a(this,Rr,e)}async upload(e){let t=await u.mediaPlugin.Upload(e,n(this,Rr));if(!t.mediaId)throw new Error("unable to get mediaId via uploads");return Promise.resolve({mediaId:t.mediaId,mediaUrl:t.mediaUrl})}};Rr=new WeakMap;var Or,ui=class{constructor(e){l(this,Or);a(this,Or,e)}async add(e){await u.modLogPlugin.Add(e,n(this,Or))}};Or=new WeakMap;var Mr,ci=class{constructor(e){l(this,Mr);a(this,Mr,e)}async send(e,t){await u.realtimePlugin.Send({channel:e,data:{msg:t}},n(this,Mr))}};Mr=new WeakMap;import"@devvit/protos";var g,Br,Ur,Dr,mi=class{constructor(e){l(this,g);l(this,Br);l(this,Ur);l(this,Dr);a(this,g,e),a(this,Br,new js(e))}get modMail(){return n(this,Br)}getSubredditById(e){return le.getById(fe(e),n(this,g))}getSubredditInfoById(e){return Od(e,n(this,g))}getSubredditByName(e){return le.getByName(e,n(this,g))}getSubredditInfoByName(e){return Md(e,n(this,g))}addSubredditRemovalReason(e,t){return le.addRemovalReason(e,t.title,t.message,n(this,g))}getSubredditRemovalReasons(e){return le.getRemovalReasons(e,n(this,g))}async getCurrentSubredditName(){let e=n(this,g)?.[S.SubredditName]?.values[0];if(e)return e;let t=n(this,g)?.[S.Subreddit]?.values[0],i=await Jo(K(t),n(this,g));if(!i)throw new Error("Couldn't get current subreddit's name");return i}async getCurrentSubreddit(){let e=await le.getFromMetadata(n(this,g));if(!e)throw new Error("Couldn't get current subreddit");return e}getPostById(e){return G.getById(fe(e),n(this,g))}submitPost(e){return G.submit(e,n(this,g))}crosspost(e){return G.crosspost(e,n(this,g))}getUserById(e){return C.getById(fe(e),n(this,g))}getUserByUsername(e){return C.getByUsername(e,n(this,g))}async getCurrentUsername(){return n(this,Dr)??a(this,Dr,Td(n(this,g))),n(this,Dr)}async getCurrentUser(){return n(this,Ur)??a(this,Ur,this.getCurrentUsername().then(e=>e?C.getByUsername(e,n(this,g)):void 0)),n(this,Ur)}getAppUser(){return C.getFromMetadata(S.AppUser,n(this,g))}getSnoovatarUrl(e){return C.getSnoovatarUrl(e,n(this,g))}getCommentById(e){return Q.getById(fe(e),n(this,g))}getComments(e){return Q.getComments(e,n(this,g))}getCommentsByUser(e){return Q.getCommentsByUser(e,n(this,g))}submitComment(e){return Q.submit({...e,id:fe(e.id)},n(this,g))}getControversialPosts(e){return G.getControversialPosts(e,n(this,g))}getTopPosts(e){return G.getTopPosts(e,n(this,g))}getHotPosts(e){return G.getHotPosts(e,n(this,g))}getNewPosts(e){return G.getNewPosts(e,n(this,g))}getRisingPosts(e){return G.getRisingPosts(e,n(this,g))}getPostsByUser(e){return G.getPostsByUser(e,n(this,g))}getCommentsAndPostsByUser(e){return C.getOverview(e,n(this,g))}getModerationLog(e){return Hs(e,n(this,g))}getApprovedUsers(e){return C.getSubredditUsersByType({type:"contributors",...e},n(this,g))}approveUser(e,t){return C.createRelationship({username:e,subredditName:t,type:"contributor"},n(this,g))}removeUser(e,t){return C.removeRelationship({username:e,subredditName:t,type:"contributor"},n(this,g))}getWikiContributors(e){return C.getSubredditUsersByType({type:"wikicontributors",...e},n(this,g))}addWikiContributor(e,t){return C.createRelationship({username:e,subredditName:t,type:"wikicontributor"},n(this,g))}removeWikiContributor(e,t){return C.removeRelationship({username:e,subredditName:t,type:"wikicontributor"},n(this,g))}getBannedUsers(e){return C.getSubredditUsersByType({type:"banned",...e},n(this,g))}banUser(e){return C.createRelationship({username:e.username,subredditName:e.subredditName,type:"banned",banReason:e.reason,banMessage:e.message,note:e.note,duration:e.duration,banContext:e.context},n(this,g))}unbanUser(e,t){return C.removeRelationship({username:e,subredditName:t,type:"banned"},n(this,g))}getBannedWikiContributors(e){return C.getSubredditUsersByType({type:"wikibanned",...e},n(this,g))}banWikiContributor(e){return C.createRelationship({...e,type:"wikibanned"},n(this,g))}unbanWikiContributor(e,t){return C.removeRelationship({username:e,subredditName:t,type:"wikibanned"},n(this,g))}getModerators(e){return C.getSubredditUsersByType({type:"moderators",...e},n(this,g))}inviteModerator(e){return C.createRelationship({type:"moderator_invite",subredditName:e.subredditName,username:e.username,permissions:e.permissions??[]},n(this,g))}revokeModeratorInvite(e,t){return C.removeRelationship({username:e,subredditName:t,type:"moderator_invite"},n(this,g))}removeModerator(e,t){return C.removeRelationship({type:"moderator",subredditName:t,username:e},n(this,g))}setModeratorPermissions(e,t,i){return C.setModeratorPermissions(e,t,i,n(this,g))}getMutedUsers(e){return C.getSubredditUsersByType({type:"muted",...e},n(this,g))}muteUser(e){return C.createRelationship({...e,type:"muted"},n(this,g))}unmuteUser(e,t){return C.removeRelationship({username:e,subredditName:t,type:"muted"},n(this,g))}getModNotes(e){return ve.get(e,n(this,g))}deleteModNote(e){return ve.delete(e,n(this,g))}addModNote(e){let t={...e,redditId:e.redditId?fe(e.redditId):void 0};return ve.add(t,n(this,g))}addRemovalNote(e){return ve.addRemovalNote(e,n(this,g))}async sendPrivateMessage(e){return It.send(e,n(this,g))}async sendPrivateMessageAsSubreddit(e){return It.sendAsSubreddit(e,n(this,g))}async approve(e){if(Ge(e))return Q.approve(e,n(this,g));if(Ft(e))return G.approve(e,n(this,g));throw new Error("id must start with either t1_ or t3_")}async remove(e,t){if(Ge(e))return Q.remove(e,t,n(this,g));if(Ft(e))return G.remove(e,t,n(this,g));throw new Error("id must start with either t1_ or t3_")}async getPostFlairTemplates(e){return ne.getPostFlairTemplates(e,n(this,g))}async getUserFlairTemplates(e){return ne.getUserFlairTemplates(e,n(this,g))}async createPostFlairTemplate(e){return ne.createPostFlairTemplate(e,n(this,g))}async createUserFlairTemplate(e){return ne.createUserFlairTemplate(e,n(this,g))}async editFlairTemplate(e){return ne.editFlairTemplate(e,n(this,g))}async deleteFlairTemplate(e,t){return ne.deleteFlairTemplate(e,t,n(this,g))}async setUserFlair(e){return ce.setUserFlair(e,n(this,g))}async setUserFlairBatch(e,t){return ce.setUserFlairBatch(e,t,n(this,g))}async removeUserFlair(e,t){return ce.removeUserFlair(e,t,n(this,g))}async setPostFlair(e){return ce.setPostFlair(e,n(this,g))}async removePostFlair(e,t){return ce.removePostFlair(e,de(t),n(this,g))}async getWidgets(e){return ie.getWidgets(e,n(this,g))}async deleteWidget(e,t){return ie.delete(e,t,n(this,g))}async addWidget(e){return ie.add(e,n(this,g))}async reorderWidgets(e,t){return ie.reorder(e,t,n(this,g))}async getWikiPage(e,t){return ue.getPage(e,t,n(this,g))}async getWikiPages(e){return ue.getPages(e,n(this,g))}async createWikiPage(e){return ue.createPage(e,n(this,g))}async updateWikiPage(e){return ue.updatePage(e,n(this,g))}getWikiPageRevisions(e){return ue.getPageRevisions(e,n(this,g))}async revertWikiPage(e,t,i){return ue.revertPage(e,t,i,n(this,g))}async getWikiPageSettings(e,t){return ue.getPageSettings(e,t,n(this,g))}async updateWikiPageSettings(e){return ue.updatePageSettings(e,n(this,g))}async addEditorToWikiPage(e,t,i){return ue.addEditor(e,t,i,n(this,g))}async removeEditorFromWikiPage(e,t,i){return ue.removeEditor(e,t,i,n(this,g))}getMessages(e){return It.getMessages(e,n(this,g))}markAllMessagesAsRead(){return It.markAllAsRead(n(this,g))}report(e,t){return u.redditAPIPlugins.LinksAndComments.Report({reason:t.reason,thingId:e.id,srName:e.subredditName,usernames:e.authorName},n(this,g))}getModQueue(e){return le.aboutLocation({...e,location:"modqueue"},n(this,g))}getReports(e){return le.aboutLocation({...e,location:"reports"},n(this,g))}getSpam(e){return le.aboutLocation({...e,location:"spam"},n(this,g))}getUnmoderated(e){return le.aboutLocation({...e,location:"unmoderated"},n(this,g))}getEdited(e){return le.aboutLocation({...e,location:"edited"},n(this,g))}getVaultByAddress(e){return Dd(e,n(this,g))}getVaultByUserId(e){return Nd(fe(e),n(this,g))}getSubredditLeaderboard(e){return Bd(e,n(this,g))}getSubredditStyles(e){return Ud(e,n(this,g))}async subscribeToCurrentSubreddit(){let e=await this.getCurrentSubreddit();await u.redditAPIPlugins.Subreddits.Subscribe({action:"sub",actionSource:"",srName:e.name,sr:"",skipInitialDefaults:!0},n(this,g))}async unsubscribeFromCurrentSubreddit(){let e=await this.getCurrentSubreddit();await u.redditAPIPlugins.Subreddits.Subscribe({action:"unsub",actionSource:"",srName:e.name,sr:"",skipInitialDefaults:!1},n(this,g))}};g=new WeakMap,Br=new WeakMap,Ur=new WeakMap,Dr=new WeakMap;import{BitfieldOverflowBehavior as zo,RedisKeyScope as qo}from"@devvit/protos";function Nr(r){return r&&typeof r=="object"&&"message"in r&&r.message!==void 0&&typeof r.message=="string"?r.message.includes("redis: nil"):!1}var I,A,E,$o=class{constructor(e,t,i){l(this,I);l(this,A);l(this,E);a(this,I,e),a(this,A,t),a(this,E,i)}async get(e){return await n(this,I).Get({key:e,transactionId:n(this,A)},n(this,E)),this}async multi(){await n(this,I).Multi(n(this,A),n(this,E))}async set(e,t,i){let s;return i?.expiration&&(s=Math.floor((i.expiration.getTime()-Date.now())/1e3),s<1&&(s=1)),await n(this,I).Set({key:e,value:t,nx:i?.nx===!0,xx:i?.xx===!0,expiration:s||0,transactionId:n(this,A)},n(this,E)),this}async del(...e){return await n(this,I).Del({keys:e,transactionId:n(this,A)},n(this,E)),this}async type(e){return await n(this,I).Type({key:e,transactionId:n(this,A)},n(this,E)),this}async exec(){let e=await n(this,I).Exec(n(this,A),n(this,E)),t=[];for(let i of e.response)i.members?t.push(i.members):i.nil!==void 0?t.push(null):i.num!==void 0?t.push(i.num):i.values!==void 0?t.push(i.values.values):i.str!==void 0?t.push(i.str):i.dbl!==void 0&&t.push(i.dbl);return t}async discard(){await n(this,I).Discard(n(this,A),n(this,E))}async watch(...e){return await n(this,I).Watch({keys:e,transactionId:n(this,A)},n(this,E)),this}async unwatch(){return await n(this,I).Unwatch(n(this,A),n(this,E)),this}async getRange(e,t,i){return await n(this,I).GetRange({key:e,start:t,end:i,transactionId:n(this,A)},n(this,E)),this}async setRange(e,t,i){return await n(this,I).SetRange({key:e,offset:t,value:i,transactionId:n(this,A)},n(this,E)),this}async strlen(e){return this.strLen(e)}async strLen(e){return await n(this,I).Strlen({key:e,transactionId:n(this,A)},n(this,E)),this}async mget(e){return this.mGet(e)}async mGet(e){return await n(this,I).MGet({keys:e,transactionId:n(this,A)},n(this,E)),this}async mset(e){return this.mSet(e)}async mSet(e){let t=Object.entries(e).map(([i,s])=>({key:i,value:s}));return await n(this,I).MSet({kv:t,transactionId:n(this,A)},n(this,E)),this}async incrBy(e,t){return await n(this,I).IncrBy({key:e,value:t,transactionId:n(this,A)},n(this,E)),this}async expire(e,t){return await n(this,I).Expire({key:e,seconds:t,transactionId:n(this,A)},n(this,E)),this}async expireTime(e){return await n(this,I).ExpireTime({key:e,transactionId:n(this,A)},n(this,E)),this}async zAdd(e,...t){return await n(this,I).ZAdd({key:e,members:t,transactionId:n(this,A)},n(this,E)),this}async zScore(e,t){return await n(this,I).ZScore({key:{key:e,transactionId:n(this,A)},member:t},n(this,E)),this}async zRank(e,t){return await n(this,I).ZRank({key:{key:e,transactionId:n(this,A)},member:t},n(this,E)),this}async zIncrBy(e,t,i){return await n(this,I).ZIncrBy({key:e,member:t,value:i,transactionId:n(this,A)},n(this,E)),this}async zScan(e,t,i,s){let o={key:e,cursor:t,pattern:i,count:s,transactionId:n(this,A)};return await n(this,I).ZScan(o,n(this,E)),this}async zCard(e){return await n(this,I).ZCard({key:e,transactionId:n(this,A)},n(this,E)),this}async zRange(e,t,i,s){let o={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};if(s?.reverse&&(o.rev=s.reverse),s?.by==="lex"?o.byLex=!0:s?.by==="score"&&(o.byScore=!0),s?.limit)if(o.byLex||o.byScore)o.offset=s.limit.offset,o.count=s.limit.count;else throw new Error("zRange parsing error: 'limit' only allowed when 'options.by' is 'lex' or 'score'");return await n(this,I).ZRange({key:{key:e,transactionId:n(this,A)},start:t+"",stop:i+"",...o},n(this,E)),this}async zRem(e,t){return await n(this,I).ZRem({key:{key:e,transactionId:n(this,A)},members:t},n(this,E)),this}async zRemRangeByLex(e,t,i){return await n(this,I).ZRemRangeByLex({key:{key:e,transactionId:n(this,A)},min:t,max:i},n(this,E)),this}async zRemRangeByRank(e,t,i){return await n(this,I).ZRemRangeByRank({key:{key:e,transactionId:n(this,A)},start:t,stop:i},n(this,E)),this}async zRemRangeByScore(e,t,i){return await n(this,I).ZRemRangeByScore({key:{key:e,transactionId:n(this,A)},min:t,max:i},n(this,E)),this}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){return await n(this,I).HGetAll({key:e,transactionId:n(this,A)},n(this,E)),this}async hget(e,t){return this.hGet(e,t)}async hGet(e,t){return await n(this,I).HGet({key:e,field:t,transactionId:n(this,A)},n(this,E)),this}async hMGet(e,t){return await n(this,I).HMGet({key:e,fields:t,transactionId:n(this,A)},n(this,E)),this}async hset(e,t){return this.hSet(e,t)}async hSet(e,t){let i=Object.entries(t).map(([s,o])=>({field:s,value:o}));return await n(this,I).HSet({key:e,fv:i,transactionId:n(this,A)},n(this,E)),this}async hincrby(e,t,i){return this.hIncrBy(e,t,i)}async hIncrBy(e,t,i){return await n(this,I).HIncrBy({key:e,field:t,value:i,transactionId:n(this,A)},n(this,E)),this}async hdel(e,t){return this.hDel(e,t)}async hDel(e,t){return await n(this,I).HDel({key:e,fields:t,transactionId:n(this,A)},n(this,E)),this}async hscan(e,t,i,s){return this.hScan(e,t,i,s)}async hScan(e,t,i,s){let o={key:e,cursor:t,pattern:i,count:s,transactionId:n(this,A)};return await n(this,I).HScan(o,n(this,E)),this}async hkeys(e){return this.hKeys(e)}async hKeys(e){return await n(this,I).HKeys({key:e,transactionId:n(this,A)},n(this,E)),this}async hlen(e){return this.hLen(e)}async hLen(e){return await n(this,I).HLen({key:e,transactionId:n(this,A)},n(this,E)),this}};I=new WeakMap,A=new WeakMap,E=new WeakMap;var w,pi,Ko=class Ko{constructor(e,t=void 0,i=qo.INSTALLATION){l(this,w);l(this,pi);a(this,w,e),a(this,pi,t),this.scope=i,this.global=i===qo.INSTALLATION?new Ko(n(this,w),n(this,pi),qo.GLOBAL):this}get storage(){return n(this,pi)||u.redisPlugin}async watch(...e){let t=await this.storage.Watch({keys:e},n(this,w));return new $o(this.storage,t,n(this,w))}async get(e){try{let t=await this.storage.Get({key:e,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return t!==null?t.value??void 0:t}catch(t){if(Nr(t))return;throw t}}async getBuffer(e){try{let t=await this.storage.GetBytes({key:e,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return t!==null?Buffer.from(t.value):t}catch(t){if(Nr(t))return;throw t}}async set(e,t,i){let s;return i?.expiration&&(s=Math.floor((i.expiration.getTime()-Date.now())/1e3),s<1&&(s=1)),(await this.storage.Set({key:e,value:t,nx:i?.nx===!0&&!i.xx,xx:i?.xx===!0&&!i.nx,expiration:s||0,scope:this.scope},n(this,w))).value}async exists(...e){return(await this.storage.Exists({keys:e,scope:this.scope},n(this,w))).existingKeys}async del(...e){await this.storage.Del({keys:e,scope:this.scope},n(this,w))}async incrBy(e,t){return(await this.storage.IncrBy({key:e,value:t,scope:this.scope},n(this,w))).value}async getRange(e,t,i){let s=await this.storage.GetRange({key:e,start:t,end:i,scope:this.scope},n(this,w));return s!==null?s.value:s}async setRange(e,t,i){return(await this.storage.SetRange({key:e,offset:t,value:i,scope:this.scope},n(this,w))).value}async strlen(e){return this.strLen(e)}async strLen(e){return(await this.storage.Strlen({key:e,scope:this.scope},n(this,w))).value}async expire(e,t){await this.storage.Expire({key:e,seconds:t,scope:this.scope},n(this,w))}async expireTime(e){return(await this.storage.ExpireTime({key:e,scope:this.scope},n(this,w))).value}async zAdd(e,...t){return(await this.storage.ZAdd({key:e,members:t,scope:this.scope},n(this,w))).value}async zRange(e,t,i,s){let o={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};if(s?.reverse&&(o.rev=s.reverse),s?.by==="lex"?o.byLex=!0:s?.by==="score"?o.byScore=!0:(o.offset=0,o.count=0),s?.limit)if(o.byLex||o.byScore)o.offset=s.limit.offset,o.count=s.limit.count;else throw new Error("zRange parsing error: 'limit' only allowed when 'options.by' is 'lex' or 'score'");return(await this.storage.ZRange({key:{key:e},start:t+"",stop:i+"",...o,scope:this.scope},n(this,w))).members}async zRem(e,t){return(await this.storage.ZRem({key:{key:e},members:t,scope:this.scope},n(this,w))).value}async zRemRangeByLex(e,t,i){return(await this.storage.ZRemRangeByLex({key:{key:e},min:t,max:i,scope:this.scope},n(this,w))).value}async zRemRangeByRank(e,t,i){return(await this.storage.ZRemRangeByRank({key:{key:e},start:t,stop:i,scope:this.scope},n(this,w))).value}async zRemRangeByScore(e,t,i){return(await this.storage.ZRemRangeByScore({key:{key:e},min:t,max:i,scope:this.scope},n(this,w))).value}async zScore(e,t){try{let i=await this.storage.ZScore({key:{key:e},member:t,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return i!==null?i.value:i}catch(i){if(Nr(i))return;throw i}}async zRank(e,t){try{let i=await this.storage.ZRank({key:{key:e},member:t,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return i!==null?i.value:i}catch(i){if(Nr(i))return;throw i}}async zIncrBy(e,t,i){let s=await this.storage.ZIncrBy({key:e,member:t,value:i,scope:this.scope},n(this,w));return s!==null?s.value:s}async mget(e){return this.mGet(e)}async mGet(e){let t=await this.storage.MGet({keys:e,scope:this.scope},n(this,w));return t!==null?t.values.map(i=>i||null):t}async mset(e){return this.mSet(e)}async mSet(e){let t=Object.entries(e).map(([i,s])=>({key:i,value:s}));await this.storage.MSet({kv:t,scope:this.scope},n(this,w))}async zCard(e){let t=await this.storage.ZCard({key:e,scope:this.scope},n(this,w));return t!==null?t.value:t}async zScan(e,t,i,s){let o={key:e,cursor:t,pattern:i,count:s,scope:this.scope};return await this.storage.ZScan(o,n(this,w))}async type(e){let t=await this.storage.Type({key:e,scope:this.scope},n(this,w));return t!==null?t.value:t}async rename(e,t){return(await this.storage.Rename({key:e,newKey:t,scope:this.scope},n(this,w))).result}async hget(e,t){return this.hGet(e,t)}async hGet(e,t){try{let i=await this.storage.HGet({key:e,field:t,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return i!==null?i.value??void 0:i}catch(i){if(Nr(i))return;throw i}}async hMGet(e,t){let i=await this.storage.HMGet({key:e,fields:t,scope:this.scope},n(this,w));return i!==null?i.values.map(s=>s||null):i}async hset(e,t){return this.hSet(e,t)}async hSet(e,t){let i=Object.entries(t).map(([o,d])=>({field:o,value:d}));return(await this.storage.HSet({key:e,fv:i,scope:this.scope},n(this,w))).value}async hSetNX(e,t,i){return(await this.storage.HSetNX({key:e,field:t,value:i,scope:this.scope},n(this,w))).success}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){let t=await this.storage.HGetAll({key:e,scope:this.scope},n(this,w));return t!==null?t.fieldValues:t}async hdel(e,t){return this.hDel(e,t)}async hDel(e,t){return(await this.storage.HDel({key:e,fields:t,scope:this.scope},n(this,w))).value}async hscan(e,t,i,s){return this.hScan(e,t,i,s)}async hScan(e,t,i,s){let o={key:e,cursor:t,pattern:i,count:s,scope:this.scope};return await this.storage.HScan(o,n(this,w))}async hkeys(e){return this.hKeys(e)}async hKeys(e){let t=await this.storage.HKeys({key:e,scope:this.scope},n(this,w));return t!==null?t.keys:t}async hincrby(e,t,i){return this.hIncrBy(e,t,i)}async hIncrBy(e,t,i){return(await this.storage.HIncrBy({key:e,field:t,value:i,scope:this.scope},n(this,w))).value}async hlen(e){return this.hLen(e)}async hLen(e){return(await this.storage.HLen({key:e,scope:this.scope})).value}async bitfield(e,...t){let i=[];for(let o=0;o<t.length;){let d=t[o],c={};switch(d){case"get":{if(o+2>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'get' command");c.get={encoding:t[o+1],offset:t[o+2].toString()},o+=3;break}case"set":{if(o+3>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'set' command");c.set={encoding:t[o+1],offset:t[o+2].toString(),value:t[o+3].toString()},o+=4;break}case"incrBy":{if(o+3>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'incrBy' command");c.incrBy={encoding:t[o+1],offset:t[o+2].toString(),increment:t[o+3].toString()},o+=4;break}case"overflow":{if(o+1>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'overflow' command");let m=t[o+1].toString();c.overflow={behavior:rm(m)},o+=2;break}default:throw Error(`bitfield command parse failed; ${d} unrecognized (must be 'get', 'set', 'incrBy', or 'overflow')`)}i.push(c)}return(await this.storage.Bitfield({key:e,commands:i})).results}};w=new WeakMap,pi=new WeakMap;var gi=Ko;function rm(r){let e=r.toLowerCase();switch(e){case"wrap":return zo.BITFIELD_OVERFLOW_BEHAVIOR_WRAP;case"sat":return zo.BITFIELD_OVERFLOW_BEHAVIOR_SAT;case"fail":return zo.BITFIELD_OVERFLOW_BEHAVIOR_FAIL;default:throw Error(`unknown bitfield overflow behavior: ${e}`)}}var At,hi=class{constructor(e){l(this,At);a(this,At,e)}async runJob(e){return(await u.schedulerPlugin.Schedule({action:{type:e.name,data:e.data},cron:"cron"in e?e.cron:void 0,when:"runAt"in e?e.runAt:void 0},n(this,At))).id}async cancelJob(e){await u.schedulerPlugin.Cancel({id:e},n(this,At))}async listJobs(){return(await u.schedulerPlugin.List({after:new Date(0),before:new Date(Date.now()+31536e7)},n(this,At))).actions.map(t=>(p(t.request?.action,"Scheduled job is malformed"),"when"in t.request&&t.request.when!=null?{id:t.id,name:t.request.action.type,runAt:t.request.when,data:t.request.action.data}:{id:t.id,name:t.request.action.type,cron:t.request.cron??"",data:t.request.action}))}};At=new WeakMap;var Lr,fi=class{constructor(e){l(this,Lr);a(this,Lr,e)}async get(e){return(await this.getAll())[e]}async getAll(){let t=await u.settingsPlugin.GetSettings({},n(this,Lr));if(!t.installationSettings)throw new Error("Could not get installation settings");if(!t.appSettings)throw new Error("Could not get app settings");return{...Ld(t.installationSettings.settings,u.installationSettings),...Ld(t.appSettings.settings,u.appSettings)}}};Lr=new WeakMap;function Ld(r,e){let t=Object.keys(r).reduce((i,s)=>(i[s]=Ho(r[s]),i),{});return e&&_d(t,e),t}function _d(r,e){for(let t of e)t.type==="group"?_d(r,t.fields):!(t.name in r)&&"defaultValue"in t&&(r[t.name]=t.defaultValue)}import{EffectType as Vs,ToastAppearance as Hd}from"@devvit/protos";var Ze,yi,_r,Gs,Ws=class{constructor(e){l(this,Ze,[]);l(this,yi);l(this,_r);l(this,Gs,(e,t)=>{let i=t!==void 0?e:"",s=t!==void 0?t:e;n(this,Ze).push({type:Vs.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:i,app:{message:s}}}})});a(this,yi,e),a(this,_r,{postMessage:n(this,Gs)})}get webView(){return n(this,_r)}showForm(e,t){let i=u.formDefinitions.get(e);if(!i&&n(this,yi)){let d=n(this,yi).forms.get(e);d&&(i={form:d,onSubmit:()=>{}})}if(!i)throw new Error("Form does not exist. Make sure you have added it using Devvit.createForm at the root of your app.");let s=i.form instanceof Function?i.form(t??{}):i.form,o={fields:[],id:e,title:s.title,acceptLabel:s.acceptLabel,cancelLabel:s.cancelLabel,shortDescription:s.description};xt(s.fields),o.fields=De(s.fields),n(this,Ze).push({type:Vs.EFFECT_SHOW_FORM,showForm:{form:o}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Hd.SUCCESS:Hd.NEUTRAL}:t={text:e},n(this,Ze).push({type:Vs.EFFECT_SHOW_TOAST,showToast:{toast:t}})}navigateTo(e){let t;typeof e=="string"?t=new URL(e).toString():t=new URL(e.permalink,"https://www.reddit.com").toString(),n(this,Ze).push({type:Vs.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}get __effects(){return n(this,Ze)}};Ze=new WeakMap,yi=new WeakMap,_r=new WeakMap,Gs=new WeakMap;function ke({metadata:r,ui:e,hooks:t,reconciler:i}){let s=new ui(r),o=new di(r),d=new gi(r),c=xd(d,i?i.state:{}),m=new mi(r),y=new hi(r),v=new fi(r),f=e?new Ws(i):void 0,P=new li(r),b=new oi,W=new ci(r),R=t&&i?gd(i):void 0,H=t&&i?pd(i):void 0,M=t&&i?md(i):void 0,Yt=t&&i?cd(i):void 0;return{modLog:s,kvStore:o,redis:d,reddit:m,scheduler:y,settings:v,media:P,assets:b,realtime:W,get useForm(){return M??(()=>{throw new Error("useForm() is unavailable")})},get cache(){return c??(()=>{throw new Error("cache() is unavailable")})},get useState(){return R??(()=>{throw new Error("useState() is unavailable")})},get useInterval(){return H??(()=>{throw new Error("useInterval() is unavailable")})},get useChannel(){return Yt??(()=>{throw new Error("useChannel() is unavailable")})},get ui(){if(!f)throw new Error("ui client is not available");return f}}}var jd={name:"@devvit/public-api",version:"0.12.0-dev",license:"BSD-3-Clause",repository:{type:"git",url:"https://developers.reddit.com/"},type:"module",exports:{".":"./dist/index.js","./package.json":"./package.json","./*":"./dist/*"},main:"./dist/index.js",files:["dist/**"],scripts:{build:"yarn build:icon-types && yarn build:semantic-colors && tsc && cp -af devvit.tsconfig.json dist/ && yarn build:types && yarn build:min && yarn build:unmin","build:icon-types":"make-icons src/types/icons.ts","build:min":"esbuild --bundle --sourcemap=linked --target=es2020 --format=esm --metafile=dist/meta.min.json --outfile=dist/public-api.min.js --external:@devvit/protos --minify src/index.ts","build:semantic-colors":"node scripts/make-semantic-colors.js","build:types":"api-extractor run && sed -ne '/declare global {/,$ p' src/devvit/Devvit.ts >> dist/public-api.d.ts","build:unmin":"esbuild --bundle --sourcemap=inline --target=es2020 --format=iife --metafile=dist/meta.json --outfile=dist/public-api.iife.js --global-name=devvitPublicAPI src/index.ts",clean:"rm -rf .turbo api-extractor coverage dist src/devvit/internals/semanticColors.ts src/types/icons.ts || :",clobber:"yarn clean && rm -rf node_modules",dev:"tsc -w","dev:build":"chokidar ./src ../shared-types/dist --command 'yarn build' --ignore './src/types/icons.ts' --ignore './src/devvit/internals/semanticColors.ts'",lint:"redlint .","lint:fix":"yarn lint --fix",prepublishOnly:"publish-package-json",test:"yarn test:unit && yarn test:types && yarn test:size","test:size":"filesize","test:types":"tsc --noEmit","test:unit":"vitest run","test:unit-with-coverage":"vitest run --coverage"},types:"./dist/index.d.ts",dependencies:{"@devvit/metrics":"0.12.0-dev","@devvit/protos":"0.12.0-dev","@devvit/shared-types":"0.12.0-dev","base64-js":"1.5.1","clone-deep":"4.0.1",moderndash:"4.0.0"},devDependencies:{"@ampproject/filesize":"4.3.0","@devvit/repo-tools":"0.12.0-dev","@devvit/tsconfig":"0.12.0-dev","@microsoft/api-extractor":"7.41.0","@reddit/faceplate-ui":"18.0.1","@types/clone-deep":"4.0.1","@vitest/coverage-c8":"0.32.0","chokidar-cli":"3.0.0",esbuild:"0.23.0",eslint:"9.11.1",typescript:"5.3.2",vitest:"1.6.0"},publishConfig:{directory:"dist"},filesize:{"dist/public-api.min.js":{gzip:"61 KB",none:"215 KB"}},source:"./src/index.ts"};function se(r,e,t){let i=r[S.Subreddit]?.values[0];p(i,"subreddit is missing from Context");let s=r[S.SubredditName]?.values[0],o=r[S.AppUser]?.values[0],d=r[S.App]?.values[0],c=r[S.Version]?.values[0],m=r[S.User]?.values[0],y=sm(r);return{get appAccountId(){return p(o,"appAccountId is missing from Context"),o},subredditId:i,subredditName:s,userId:m,postId:e,commentId:t,appName:d,appVersion:c,debug:y,toJSON(){return{appAccountId:o,appName:d,appVersion:c,subredditId:i,subredditName:s,userId:m,postId:e,commentId:t,debug:y}}}}function sm(r){let e={blocks:void 0,emitSnapshots:void 0,emitState:void 0,realtime:void 0,runtime:void 0,surface:void 0,useAsync:void 0,payments:void 0,bootstrap:void 0,webView:void 0},t={};for(let s in e)t[s.toLowerCase()]=s;let i={};for(let s of(r[S.Debug]?.values??[]).join().split(",")){let[o,d]=s.split("=");o&&(o=o.trim(),d=d?.trim(),o.toLowerCase()in t&&(o=t[o.toLowerCase()]),i[o]??(i[o]=d||"true"))}return r[S.Debug]&&console.info(`[api] @devvit/public-api v${jd.version} ${Object.entries(i).map(([s,o])=>`${s}=${o}`).join(" ")}`),{...i,metadata:r}}function Vd(r){return r.flatMap(e=>e.type==="group"?Vd(e.fields):e)}async function Js(r,e,t){if(!e)throw new Error("Settings were not defined.");let i={success:!0,errors:{}},s=ze(r.fieldValues),o=Vd(e);return await Promise.all(o.map(async d=>{let c=d.name;if(c&&d.onValidate){let m=s[c],y=d.onValidate,v=Object.assign(ke({metadata:t}),se(t)),f=await y({value:m,isEditing:r.editing},v);f&&(i.success=!1,i.errors[c]=f)}})),om.fromJSON(i)}async function lm(){if(!u.appSettings)throw new Error("App settings were not defined.");return dm.fromJSON({fields:{fields:De(u.appSettings)}})}async function um(r,e){return Js(r,u.appSettings,e)}function Wd(r){r.provides(am),O("GetAppSettingsFields",lm),O("ValidateAppForm",um)}import{CustomPostDefinition as ym,RenderPostResponse as bm}from"@devvit/protos";import{BlockRenderEventType as la,EffectType as nl}from"@devvit/protos";function bi(r){return r.__effects}function Gd(){let r=new Set;return e=>{let t=e,i=1;for(;r.has(t);)t=`${e}.${i++}`;return r.add(t),t}}import{BlockActionType as da,BlockAvatarBackground as el,BlockAvatarFacing as tl,BlockAvatarSize as Xe,BlockBorderWidth as Ks,BlockButtonAppearance as Qe,BlockButtonSize as ea,BlockGap as Zs,BlockHorizontalAlignment as ta,BlockIconSize as Xs,BlockImageResizeMode as Hr,BlockPadding as jr,BlockRadius as Vr,BlockSpacerShape as ia,BlockSpacerSize as Qs,BlockStackDirection as ra,BlockTextOutline as na,BlockTextOverflow as sa,BlockTextSize as ki,BlockTextStyle as oa,BlockTextWeight as il,BlockType as Ee,BlockVerticalAlignment as aa}from"@devvit/protos";var Zo={"alienblue-100":"#DCE2FB","alienblue-200":"#B8C5FC","alienblue-25":"#F7F8FD","alienblue-300":"#90A9FD","alienblue-400":"#648EFC","alienblue-50":"#EEF0FB","alienblue-500":"#1870F4","alienblue-600":"#115BCA","alienblue-700":"#0A449B","alienblue-75":"#E6E9FB","alienblue-800":"#0A2F6C","alienblue-900":"#0A1A3F","alienblue-950":"#07102B","berrypurple-100":"#F3DAFB","berrypurple-200":"#EAB3FD","berrypurple-25":"#FBF6FD","berrypurple-300":"#DE8BFF","berrypurple-400":"#CF5FFF","berrypurple-50":"#F8EDFC","berrypurple-500":"#BC0EFF","berrypurple-600":"#9B00D4","berrypurple-700":"#7600A3","berrypurple-75":"#F6E4FB","berrypurple-800":"#520472","berrypurple-900":"#300643","berrypurple-950":"#20042A",black:"#000000","black-opacity-0":"#00000000","black-opacity-10":"#00000019","black-opacity-15":"#00000026","black-opacity-20":"#00000033","black-opacity-25":"#0000003F","black-opacity-33":"#00000054","black-opacity-5":"#0000000C","black-opacity-50":"#0000007F","black-opacity-60":"#00000099","black-opacity-67":"#000000AA","black-opacity-80":"#000000CC","black-opacity-90":"#000000E5","brown-100":"#F1DFCF","brown-200":"#E9BE95","brown-25":"#FBF7F4","brown-300":"#DC9D5D","brown-400":"#BA854E","brown-50":"#F7EFE9","brown-500":"#9A6D3F","brown-600":"#7B5631","brown-700":"#5D4023","brown-75":"#F4E7DC","brown-800":"#3F2C19","brown-900":"#221A11","brown-950":"#15100A","coolgray-100":"#DBE4E9","coolgray-150":"#C9D7DE","coolgray-200":"#B7CAD4","coolgray-25":"#F6F8F9","coolgray-250":"#A4BDCA","coolgray-300":"#97AFBC","coolgray-350":"#8BA2AD","coolgray-400":"#7F949F","coolgray-450":"#748791","coolgray-50":"#EEF1F3","coolgray-500":"#667780","coolgray-525":"#576F76","coolgray-550":"#5C6C74","coolgray-600":"#536168","coolgray-650":"#48545B","coolgray-700":"#3D494E","coolgray-75":"#E5EBEE","coolgray-750":"#333D42","coolgray-800":"#2A3236","coolgray-850":"#21272A","coolgray-900":"#181C1F","coolgray-950":"#0E1113","global-black":{light:"#000000",dark:"#000000"},"global-brand-orangered":{light:"#FF4500",dark:"#FF4500"},"global-white":{light:"#FFFFFF",dark:"#FFFFFF"},"kiwigreen-100":"#A8F5A0","kiwigreen-200":"#58E15B","kiwigreen-25":"#EBFDE7","kiwigreen-300":"#00C61C","kiwigreen-400":"#01A816","kiwigreen-50":"#DDF8D7","kiwigreen-500":"#008A10","kiwigreen-600":"#016E0B","kiwigreen-700":"#005306","kiwigreen-75":"#CAF5C2","kiwigreen-800":"#033902","kiwigreen-900":"#0D2005","kiwigreen-950":"#081404","lightblue-100":"#CAE7FB","lightblue-200":"#87D0FD","lightblue-25":"#F3F9FD","lightblue-300":"#02B9FB","lightblue-400":"#029DD5","lightblue-50":"#E6F3FC","lightblue-500":"#007FAE","lightblue-600":"#01668D","lightblue-700":"#014D6B","lightblue-75":"#D9EDFB","lightblue-800":"#03354B","lightblue-900":"#051E2B","lightblue-950":"#04131A","lime-100":"#B7F28E","lime-200":"#90DA58","lime-25":"#EEFDDC","lime-300":"#6DBF01","lime-400":"#5BA200","lime-50":"#E0F8C8","lime-500":"#4A8500","lime-600":"#3A6A00","lime-700":"#2A5000","lime-75":"#CEF5AD","lime-800":"#1E3702","lime-900":"#151E05","lime-950":"#0D1304","mintgreen-100":"#9BF5D9","mintgreen-200":"#00E2B7","mintgreen-25":"#E7FDF5","mintgreen-300":"#00C29D","mintgreen-400":"#01A484","mintgreen-50":"#D7F8EC","mintgreen-500":"#01876D","mintgreen-600":"#006C56","mintgreen-700":"#015140","mintgreen-75":"#C0F5E3","mintgreen-800":"#00382B","mintgreen-900":"#032019","mintgreen-950":"#03140F","orangered-100":"#FCDBCF","orangered-200":"#FDB498","orangered-25":"#FDF6F4","orangered-300":"#FF895D","orangered-400":"#FF4500","orangered-50":"#FCEEE8","orangered-500":"#D93900","orangered-600":"#AE2C00","orangered-700":"#842100","orangered-75":"#FBE5DC","orangered-800":"#591B02","orangered-900":"#2F1405","orangered-950":"#1C0D04","periwinkle-100":"#E6DFFB","periwinkle-200":"#CDBEFD","periwinkle-25":"#F9F7FD","periwinkle-300":"#B29FFF","periwinkle-400":"#9580FF","periwinkle-50":"#F2EFFC","periwinkle-500":"#6A5CFF","periwinkle-600":"#523DFF","periwinkle-700":"#4001EA","periwinkle-75":"#ECE7FB","periwinkle-800":"#250AA6","periwinkle-900":"#160E5B","periwinkle-950":"#0C083F","poopbrown-100":"#FEEEDD","poopbrown-200":"#F6DDC3","poopbrown-300":"#EECCAA","poopbrown-400":"#CAA075","poopbrown-50":"#FEF7EE","poopbrown-500":"#9A6D3F","poopbrown-600":"#6E4924","poopbrown-700":"#54371A","poopbrown-800":"#3B2510","poopbrown-900":"#29190A","poopbrown-950":"#110B04","puregray-100":"#F2F2F2","puregray-150":"#EBEBEB","puregray-200":"#E4E4E4","puregray-250":"#DDDDDD","puregray-300":"#D6D6D6","puregray-350":"#C3C3C3","puregray-400":"#ACACAC","puregray-450":"#919191","puregray-50":"#F8F8F8","puregray-500":"#767676","puregray-550":"#5C5C5C","puregray-600":"#434343","puregray-650":"#393939","puregray-700":"#303030","puregray-750":"#272727","puregray-800":"#1E1E1E","puregray-850":"#181818","puregray-900":"#131313","puregray-950":"#080808","red-100":"#FBDBD4","red-200":"#FDB3A4","red-25":"#FDF6F5","red-300":"#FF8773","red-400":"#FF4F40","red-50":"#FCEEEA","red-500":"#EB001F","red-600":"#BC0117","red-700":"#90000F","red-75":"#FBE4DF","red-800":"#650405","red-900":"#340F05","red-950":"#1F0B04","sakurapink-100":"#FBD9EB","sakurapink-200":"#FDAEDA","sakurapink-25":"#FDF6F9","sakurapink-300":"#FF7ECA","sakurapink-400":"#FF38BB","sakurapink-50":"#FCEDF4","sakurapink-500":"#DE019F","sakurapink-600":"#B2007F","sakurapink-700":"#880060","sakurapink-75":"#FBE3EF","sakurapink-800":"#5F0443","sakurapink-900":"#380626","sakurapink-950":"#250419",transparent:"transparent",white:"#ffffff","white-opacity-0":"#FFFFFF00","white-opacity-10":"#FFFFFF19","white-opacity-15":"#FFFFFF26","white-opacity-20":"#FFFFFF33","white-opacity-25":"#FFFFFF3F","white-opacity-5":"#FFFFFF0C","white-opacity-50":"#FFFFFF7F","yellow-100":"#FFE284","yellow-200":"#FFBF0B","yellow-25":"#FFF9E0","yellow-300":"#D8A100","yellow-400":"#B78800","yellow-50":"#FFF3C0","yellow-500":"#977000","yellow-600":"#785800","yellow-700":"#5B4200","yellow-75":"#FFEAA2","yellow-800":"#3F2D00","yellow-900":"#231A03","yellow-950":"#161003","yelloworange-100":"#FCDCC8","yelloworange-200":"#FDB586","yelloworange-25":"#FDF7F3","yelloworange-300":"#FF8A35","yelloworange-400":"#E46C00","yelloworange-50":"#FCEEE6","yelloworange-500":"#BD5800","yelloworange-600":"#974500","yelloworange-700":"#733300","yelloworange-75":"#FBE5D7","yelloworange-800":"#4E2402","yelloworange-900":"#2A1705","yelloworange-950":"#1A0E04","action-downvote":{light:"#6A5CFF",dark:"#6A5CFF"},"action-upvote":{light:"#D93900",dark:"#D93900"},"ai-background-weaker":{light:"#E7FDF5",dark:"#00382B"},"ai-plain":{light:"#006C56",dark:"#01A484"},"ai-plain-hover":{light:"#015140",dark:"#00C29D"},"alert-caution":{light:"#977000",dark:"#977000"},"avatar-gradient":{light:"",dark:""},"brand-background":{light:"#D93900",dark:"#D93900"},"brand-background-hover":{light:"#AE2C00",dark:"#AE2C00"},"brand-gradient-active":{light:"",dark:""},"brand-gradient-active-highlight":{light:"",dark:""},"brand-gradient-default":{light:"",dark:""},"brand-gradient-default-highlight":{light:"",dark:""},"brand-gradient-hover":{light:"",dark:""},"brand-gradient-hover-highlight":{light:"",dark:""},"brand-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"category-live":{light:"#D93900",dark:"#D93900"},"category-nsfw":{light:"#DE019F",dark:"#DE019F"},"category-spoiler":{light:"#131313",dark:"#F2F2F2"},"caution-background":{light:"#FFBF0B",dark:"#D8A100"},"caution-background-hover":{light:"#D8A100",dark:"#FFBF0B"},"caution-onBackground":{light:"#000000",dark:"#000000"},"caution-plain":{light:"#785800",dark:"#FFBF0B"},"caution-plain-hover":{light:"#5B4200",dark:"#FFE284"},"danger-background":{light:"#EB001F",dark:"#BC0117"},"danger-background-disabled":{light:"#FDB3A4",dark:"#340F05"},"danger-background-hover":{light:"#BC0117",dark:"#EB001F"},"danger-background-weaker":{light:"#FBDBD4",dark:"#650405"},"danger-content":{light:"#BC0117",dark:"#FF4F40"},"danger-content-default":{light:"#ffffff",dark:"#ffffff"},"danger-content-hover":{light:"#90000F",dark:"#FF8773"},"danger-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"danger-plain":{light:"#BC0117",dark:"#FF8773"},"danger-plain-hover":{light:"#90000F",dark:"#FDB3A4"},"downvote-background":{light:"#6A5CFF",dark:"#6A5CFF"},"downvote-background-disabled":{light:"#6a5cff4d",dark:"#6a5cff4d"},"downvote-background-hover":{light:"#523DFF",dark:"#523DFF"},"downvote-content":{light:"#523DFF",dark:"#9580FF"},"downvote-content-weak":{light:"#6A5CFF",dark:"#6A5CFF"},"downvote-disabled":{light:"#523DFF4c",dark:"#9580FF4c"},"downvote-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"downvote-onStrongScrim":{light:"#B29FFF",dark:"#B29FFF"},"downvote-onStrongScrim-disabled":{light:"#b29fff4d",dark:"#b29fff4d"},"downvote-onStrongScrim-weaker":{light:"#9580FF",dark:"#9580FF"},"downvote-plain":{light:"#523DFF",dark:"#9580FF"},"downvote-plain-disabled":{light:"#523dff4d",dark:"#9580ff4d"},"downvote-plain-weaker":{light:"#6A5CFF",dark:"#6A5CFF"},"elevation-large1":{light:"#0000003F",dark:"#0000007F"},"elevation-large2":{light:"#00000026",dark:"#00000033"},"elevation-medium1":{light:"#0000003F",dark:"#0000007F"},"elevation-medium2":{light:"#00000019",dark:"#00000033"},"elevation-small":{light:"#00000026",dark:"#00000054"},"elevation-xsmall":{light:"#0000003F",dark:"#000000AA"},favorite:{light:"#977000",dark:"#B78800"},"global-admin":{light:"#D93900",dark:"#D93900"},"global-alienblue":{light:"#1870F4",dark:"#1870F4"},"global-darkblue":{light:"#2A3236",dark:"#2A3236"},"global-focus":{light:"#029DD5",dark:"#007FAE"},"global-gold":{light:"#B78800",dark:"#D8A100"},"global-moderator":{light:"#008A10",dark:"#008A10"},"global-nsfw":{light:"#DE019F",dark:"#DE019F"},"global-offline":{light:"#667780",dark:"#667780"},"global-online":{light:"#00C61C",dark:"#00C61C"},"global-orangered":{light:"#FF4500",dark:"#FF4500"},"global-stars":{light:"#977000",dark:"#D8A100"},"gradient-media":{light:"",dark:""},"gradient-media-strong":{light:"",dark:""},"identity-admin":{light:"#D93900",dark:"#D93900"},"identity-coins":{light:"#B78800",dark:"#B78800"},"identity-moderator":{light:"#008A10",dark:"#008A10"},"identity-self":{light:"#01876D",dark:"#01876D"},"interactive-background-disabled":{light:"#0000000C",dark:"#FFFFFF0C"},"interactive-content-disabled":{light:"#0000003F",dark:"#FFFFFF3F"},"interactive-focused":{light:"#007FAE",dark:"#007FAE"},"interactive-pressed":{light:"#00000026",dark:"#FFFFFF26"},"inverted-interactive-background-disabled":{light:"#FFFFFF0C",dark:"#0000000C"},"inverted-interactive-content-disabled":{light:"#FFFFFF3F",dark:"#0000003F"},"inverted-interactive-pressed":{light:"#FFFFFF26",dark:"#00000026"},"inverted-neutral-background":{light:"#0E1113",dark:"#FFFFFF"},"inverted-neutral-background-hover":{light:"#181C1F",dark:"#F6F8F9"},"inverted-neutral-border":{light:"#FFFFFF33",dark:"#00000033"},"inverted-neutral-content":{light:"#B7CAD4",dark:"#333D42"},"inverted-neutral-content-strong":{light:"#EEF1F3",dark:"#181C1F"},"inverted-secondary-background":{light:"#2A3236",dark:"#E5EBEE"},"inverted-secondary-background-hover":{light:"#333D42",dark:"#DBE4E9"},"inverted-secondary-background-selected":{light:"#3D494E",dark:"#C9D7DE"},"inverted-secondary-onBackground":{light:"#FFFFFF",dark:"#000000"},"inverted-secondary-plain":{light:"#DBE4E9",dark:"#181C1F"},"inverted-secondary-plain-hover":{light:"#FFFFFF",dark:"#000000"},"media-background":{light:"#00000099",dark:"#00000099"},"media-background-hover":{light:"#000000cc",dark:"#000000cc"},"media-background-selected":{light:"#000000cc",dark:"#000000cc"},"media-border-selected":{light:"#FFFFFF",dark:"#FFFFFF"},"media-border-weak":{light:"#FFFFFF19",dark:"#FFFFFF19"},"media-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"media-onBackground-disabled":{light:"#FFFFFF3F",dark:"#FFFFFF3F"},"media-onBackground-weak":{light:"#E5EBEE",dark:"#E5EBEE"},"media-onbackground":{light:"#ffffff",dark:"#ffffff"},"media-onbackground-disabled":{light:"#ffffff3f",dark:"#ffffff3f"},"media-onbackground-weak":{light:"#B7CAD4",dark:"#B7CAD4"},"neutral-background":{light:"#FFFFFF",dark:"#0E1113"},"neutral-background-container":{light:"#F6F8F9",dark:"#181C1F"},"neutral-background-container-hover":{light:"#EEF1F3",dark:"#21272A"},"neutral-background-container-strong":{light:"#EEF1F3",dark:"#21272A"},"neutral-background-container-strong-hover":{light:"#E5EBEE",dark:"#2A3236"},"neutral-background-gilded":{light:"#FFF9E0",dark:"#181C1F"},"neutral-background-gilded-hover":{light:"#FFF3C0",dark:"#21272A"},"neutral-background-hover":{light:"#F6F8F9",dark:"#181C1F"},"neutral-background-medium":{light:"#F8F8F8",dark:"#131313"},"neutral-background-pinned":{light:"#FFFFFF",dark:"#0E1113"},"neutral-background-selected":{light:"#E5EBEE",dark:"#2A3236"},"neutral-background-strong":{light:"#FFFFFF",dark:"#181C1F"},"neutral-background-strong-hover":{light:"#F6F8F9",dark:"#21272A"},"neutral-background-weak":{light:"#F6F8F9",dark:"#000000"},"neutral-background-weak-hover":{light:"#EEF1F3",dark:"#0E1113"},"neutral-border":{light:"#00000033",dark:"#FFFFFF33"},"neutral-border-medium":{light:"#0000007F",dark:"#FFFFFF7F"},"neutral-border-strong":{light:"#181C1F",dark:"#F6F8F9"},"neutral-border-weak":{light:"#00000019",dark:"#FFFFFF19"},"neutral-content":{light:"#333D42",dark:"#B7CAD4"},"neutral-content-disabled":{light:"#D6D6D6",dark:"#303030"},"neutral-content-strong":{light:"#181C1F",dark:"#EEF1F3"},"neutral-content-weak":{light:"#5C6C74",dark:"#8BA2AD"},offline:{light:"#767676",dark:"#767676"},online:{light:"#01A816",dark:"#01A816"},"opacity-08":{light:"#13131314",dark:"#13131314"},"opacity-50":{light:"#0000007f",dark:"#F2F2F27f"},"opacity-highlight":{light:"",dark:""},pizzaRed:{light:"#ef5350",dark:"#c62828"},primary:{light:"#115BCA",dark:"#648EFC"},"primary-background":{light:"#0A449B",dark:"#115BCA"},"primary-background-hover":{light:"#0A2F6C",dark:"#1870F4"},"primary-background-selected":{light:"#0A1A3F",dark:"#648EFC"},"primary-border":{light:"#0A449B",dark:"#648EFC"},"primary-border-hover":{light:"#0A2F6C",dark:"#90A9FD"},"primary-hover":{light:"#0A449B",dark:"#90A9FD"},"primary-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"primary-onBackground-selected":{light:"#FFFFFF",dark:"#000000"},"primary-plain":{light:"#0A449B",dark:"#648EFC"},"primary-plain-hover":{light:"#0A2F6C",dark:"#90A9FD"},"primary-plain-visited":{light:"#7600A3",dark:"#CF5FFF"},"primary-visited":{light:"#9B00D4",dark:"#CF5FFF"},scrim:{light:"#00000099",dark:"#00000099"},"scrim-background":{light:"#00000099",dark:"#00000099"},"scrim-background-strong":{light:"#000000CC",dark:"#000000CC"},"scrim-gradient":{light:"",dark:""},"scrim-strong":{light:"#000000cc",dark:"#000000cc"},secondary:{light:"#21272A",dark:"#DBE4E9"},"secondary-background":{light:"#E5EBEE",dark:"#2A3236"},"secondary-background-hover":{light:"#DBE4E9",dark:"#333D42"},"secondary-background-selected":{light:"#C9D7DE",dark:"#3D494E"},"secondary-hover":{light:"#000000",dark:"#ffffff"},"secondary-onBackground":{light:"#000000",dark:"#FFFFFF"},"secondary-plain":{light:"#181C1F",dark:"#DBE4E9"},"secondary-plain-hover":{light:"#000000",dark:"#FFFFFF"},"secondary-plain-weak":{light:"#5C6C74",dark:"#8BA2AD"},"secondary-weak":{light:"#576F76",dark:"#748791"},"success-background":{light:"#008A10",dark:"#016E0B"},"success-background-hover":{light:"#016E0B",dark:"#008A10"},"success-content":{light:"#016E0B",dark:"#01A816"},"success-hover":{light:"#005306",dark:"#00C61C"},"success-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"success-plain":{light:"#016E0B",dark:"#00C61C"},"success-plain-hover":{light:"#005306",dark:"#58E15B"},"tone-1":{light:"#131313",dark:"#F2F2F2"},"tone-2":{light:"#434343",dark:"#ACACAC"},"tone-3":{light:"#ACACAC",dark:"#434343"},"tone-4":{light:"#E4E4E4",dark:"#303030"},"tone-5":{light:"#F2F2F2",dark:"#1E1E1E"},"tone-6":{light:"#F8F8F8",dark:"#131313"},"tone-7":{light:"#ffffff",dark:"#080808"},"transparent-background-hover":{light:"#74879119",dark:"#66778019"},"ui-canvas":{light:"#F2F2F2",dark:"#080808"},"ui-modalbackground":{light:"#FFFFFF",dark:"#181C1F"},"upvote-background":{light:"#D93900",dark:"#D93900"},"upvote-background-disabled":{light:"#d939004d",dark:"#d939004d"},"upvote-background-hover":{light:"#AE2C00",dark:"#AE2C00"},"upvote-content":{light:"#AE2C00",dark:"#FF4500"},"upvote-content-weak":{light:"#FF4500",dark:"#FF4500"},"upvote-disabled":{light:"#AE2C004c",dark:"#FF45004c"},"upvote-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"upvote-onStrongScrim":{light:"#FF895D",dark:"#FF895D"},"upvote-onStrongScrim-disabled":{light:"#ff895d4d",dark:"#ff895d4d"},"upvote-onStrongScrim-weaker":{light:"#FF4500",dark:"#FF4500"},"upvote-plain":{light:"#AE2C00",dark:"#FF895D"},"upvote-plain-disabled":{light:"#ae2c004d",dark:"#ff895d4d"},"upvote-plain-weaker":{light:"#FF4500",dark:"#FF4500"},"warning-background":{light:"#B78800",dark:"#B78800"},"warning-background-hover":{light:"#977000",dark:"#D8A100"},"warning-content":{light:"#785800",dark:"#B78800"},"warning-content-hover":{light:"#5B4200",dark:"#D8A100"},"warning-onBackground":{light:"#000000",dark:"#000000"}};var Jd={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",transparent:"#FFFFFF00",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},zd=r=>!!r.match(/^(#[0-9a-fA-F]{3,8}).*/),qd=r=>r in Zo,Xo=r=>r in Jd,$d=r=>!!r.match(/^rgba?\(.*/),Kd=r=>!!r.match(/^hsla?\(.*/),Zd=(r,e="light")=>{if(Xo(r))return zs(r);let i=Zo[r];return typeof i=="string"?i:i[e]},zs=r=>Jd[r]??r,Xd=r=>{let[e,t,i,s]=r.replace(/^rgba?\(|\s+|\)$/g,"").split(",");if(!e||!t||!i)return r;let d=[...[e,t,i].map(m=>parseFloat(m))];if(s){let m=parseFloat(s),y=Math.round(m*255);d.push(y)}return`#${d.map(m=>m.toString(16).padStart(2,"0")).join("")}`};import{BlockStackDirection as qs}from"@devvit/protos";var Qo={stackParentLayout:{hasHeight:!0,hasWidth:!0,direction:qs.UNRECOGNIZED,alignment:void 0}};function Yd(r,e,t){if(!e)return{hasHeight:!1,hasWidth:!1};let{growDirection:i,stretchDirection:s}=cm(r?.grow,e.direction,e.alignment),o=t?.height?.value?.value||t?.height?.min?.value||Qd(2,i,s,e.hasHeight),d=t?.width?.value?.value||t?.width?.min?.value||Qd(1,i,s,e.hasWidth);return{hasHeight:!!o,hasWidth:!!d}}function Qd(r,e,t,i){return e===r&&i||t===r&&i}function cm(r,e,t){let i=e===qs.STACK_VERTICAL||e===qs.UNRECOGNIZED,s=e===qs.STACK_HORIZONTAL,o=0;s&&r?o=1:i&&r&&(o=2);let d=t===void 0||t.horizontal===void 0,c=t===void 0||t.vertical===void 0,m=s?!!c:i?!!d:!1,y=0;return s&&m?y=2:i&&m&&(y=1),{growDirection:o,stretchDirection:y}}import{BlockSizeUnit as Et,BlockStackDirection as $s}from"@devvit/protos";function vi(r){if(r==null)return;if(typeof r=="number")return{value:r,unit:Et.SIZE_UNIT_PERCENT};let e=r.match(/^(\d+(?:\.\d+)?)(px|%)?$/);if(e==null)return;let t=Et.SIZE_UNIT_PERCENT;return e.at(2)==="px"&&(t=Et.SIZE_UNIT_PIXELS),{value:Number.parseFloat(e[1]),unit:t}}function mm(r,e){return(r.width?.value?.unit===Et.SIZE_UNIT_PERCENT||r.width?.min?.unit===Et.SIZE_UNIT_PERCENT)&&(e.direction===$s.STACK_HORIZONTAL||e.direction===$s.STACK_DEPTH)&&(e.hasWidth||(r.width=void 0)),(r.height?.value?.unit===Et.SIZE_UNIT_PERCENT||r.height?.min?.unit===Et.SIZE_UNIT_PERCENT)&&(e.direction===$s.STACK_VERTICAL||e.direction===$s.STACK_DEPTH)&&(e.hasHeight||(r.height=void 0)),r}function Yo(r,e){if(r){let t=r.width!=null||r.minWidth!=null||r.maxWidth!=null,i=r.height!=null||r.minHeight!=null||r.maxHeight!=null;if(t||i||r.grow!=null){let s={width:t?{value:vi(r.width),min:vi(r.minWidth),max:vi(r.maxWidth)}:void 0,height:i?{value:vi(r.height),min:vi(r.minHeight),max:vi(r.maxHeight)}:void 0,grow:r.grow};return e.stackParentLayout&&(s=mm(s,e.stackParentLayout)),s}}}var rl="data-",pm=new Set(["onPress","onMessage"]),gm=new Map([["onPress",da.ACTION_CLICK],["onMessage",da.ACTION_WEBVIEW]]),Wr,Ci=class{constructor(e=()=>{}){l(this,Wr);a(this,Wr,e)}createBlocksElementOrThrow({type:e,props:t,children:i}){let s=this.createBlocksElement({type:e,props:t,children:i},Qo);if(!s)throw new Error(`Could not create block of type ${e}`);return s}createBlocksElement({type:e,props:t,children:i},s){switch(e){case"blocks":return this.makeRoot(t,...i);case"hstack":return this.makeHStack(t,s,...i);case"vstack":return this.makeVStack(t,s,...i);case"zstack":return this.makeZStack(t,s,...i);case"text":return this.makeText(t,s,...i);case"button":return this.makeButton(t,s,...i);case"image":return this.makeImage(t,s);case"spacer":return this.makeSpacer(t,s);case"icon":return this.makeIcon(t,s);case"avatar":return this.makeAvatar(t,s);case"webview":return this.makeWebView(t,s);case"__fragment":throw new Error("root fragment is not supported - use 'blocks' instead")}}makeRootHeight(e){switch(e){case"regular":return 320;case"tall":return 512}}makeBlockPadding(e){switch(e){case"none":return jr.PADDING_NONE;case"xsmall":return jr.PADDING_XSMALL;case"small":return jr.PADDING_SMALL;case"medium":return jr.PADDING_MEDIUM;case"large":return jr.PADDING_LARGE}}makeBlockRadius(e){switch(e){case"none":return Vr.RADIUS_NONE;case"small":return Vr.RADIUS_SMALL;case"medium":return Vr.RADIUS_MEDIUM;case"large":return Vr.RADIUS_LARGE;case"full":return Vr.RADIUS_FULL}}makeBlockGap(e){switch(e){case"none":return Zs.GAP_NONE;case"small":return Zs.GAP_SMALL;case"medium":return Zs.GAP_MEDIUM;case"large":return Zs.GAP_LARGE}}makeBlockAlignment(e){if(e===void 0)return;let t,i;if(e.includes("top")?t=aa.ALIGN_TOP:e.includes("middle")?t=aa.ALIGN_MIDDLE:e.includes("bottom")&&(t=aa.ALIGN_BOTTOM),e.includes("start")?i=ta.ALIGN_START:e.includes("center")?i=ta.ALIGN_CENTER:e.includes("end")&&(i=ta.ALIGN_END),t!==void 0||i!==void 0)return{vertical:t,horizontal:i}}makeBlockBorder(e,t,i,s){if(!e&&!t)return;let o;switch(e){case"none":o=Ks.BORDER_WIDTH_NONE;break;case"thin":o=Ks.BORDER_WIDTH_THIN;break;case"thick":o=Ks.BORDER_WIDTH_THICK;break;default:o=Ks.BORDER_WIDTH_THIN;break}let d=t??"neutral-border-weak",c=this.getThemedColors(d,i,s);return{width:o,color:c?.light,colors:c}}makeBlockTextSize(e){switch(e){case"xsmall":return ki.TEXT_SIZE_XSMALL;case"small":return ki.TEXT_SIZE_SMALL;case"medium":return ki.TEXT_SIZE_MEDIUM;case"large":return ki.TEXT_SIZE_LARGE;case"xlarge":return ki.TEXT_SIZE_XLARGE;case"xxlarge":return ki.TEXT_SIZE_XXLARGE}}makeBlockTextStyle(e){switch(e){case"body":return oa.TEXT_STYLE_BODY;case"metadata":return oa.TEXT_STYLE_METADATA;case"heading":return oa.TEXT_STYLE_HEADING}}makeBlockTextOutline(e){switch(e){case"none":return na.TEXT_OUTLINE_NONE;case"thin":return na.TEXT_OUTLINE_THIN;case"thick":return na.TEXT_OUTLINE_THICK}}makeBlockTextWeight(e){switch(e){case"regular":return il.TEXT_WEIGHT_REGULAR;case"bold":return il.TEXT_WEIGHT_BOLD}}makeBlockTextOverflow(e){switch(e){case"clip":return sa.TEXT_OVERFLOW_CLIP;case"ellipsis":return sa.TEXT_OVERFLOW_ELLIPSE}return sa.TEXT_OVERFLOW_ELLIPSE}makeBlockButtonAppearance(e){switch(e){case"secondary":return Qe.BUTTON_APPEARANCE_SECONDARY;case"primary":return Qe.BUTTON_APPEARANCE_PRIMARY;case"plain":return Qe.BUTTON_APPEARANCE_PLAIN;case"bordered":return Qe.BUTTON_APPEARANCE_BORDERED;case"media":return Qe.BUTTON_APPEARANCE_MEDIA;case"destructive":return Qe.BUTTON_APPEARANCE_DESTRUCTIVE;case"caution":return Qe.BUTTON_APPEARANCE_CAUTION;case"success":return Qe.BUTTON_APPEARANCE_SUCCESS}}makeBlockButtonSize(e){switch(e){case"small":return ea.BUTTON_SIZE_SMALL;case"medium":return ea.BUTTON_SIZE_MEDIUM;case"large":return ea.BUTTON_SIZE_LARGE}}makeBlockImageResizeMode(e){switch(e){case"none":return Hr.IMAGE_RESIZE_NONE;case"fit":return Hr.IMAGE_RESIZE_FIT;case"fill":return Hr.IMAGE_RESIZE_FILL;case"cover":return Hr.IMAGE_RESIZE_COVER;case"scale-down":return Hr.IMAGE_RESIZE_SCALE_DOWN}}makeBlockSpacerSize(e){switch(e){case"xsmall":return Qs.SPACER_XSMALL;case"small":return Qs.SPACER_SMALL;case"medium":return Qs.SPACER_MEDIUM;case"large":return Qs.SPACER_LARGE}}makeBlockSpacerShape(e){switch(e){case"invisible":return ia.SPACER_INVISIBLE;case"thin":return ia.SPACER_THIN;case"square":return ia.SPACER_SQUARE}}makeBlockIconSize(e){switch(e){case"xsmall":return Xs.ICON_SIZE_XSMALL;case"small":return Xs.ICON_SIZE_SMALL;case"medium":return Xs.ICON_SIZE_MEDIUM;case"large":return Xs.ICON_SIZE_LARGE}}makeBlockAvatarSize(e){switch(e){case"xxsmall":return Xe.AVATAR_SIZE_XXSMALL;case"xsmall":return Xe.AVATAR_SIZE_XSMALL;case"small":return Xe.AVATAR_SIZE_SMALL;case"medium":return Xe.AVATAR_SIZE_MEDIUM;case"large":return Xe.AVATAR_SIZE_LARGE;case"xlarge":return Xe.AVATAR_SIZE_XXLARGE;case"xxlarge":return Xe.AVATAR_SIZE_XXLARGE;case"xxxlarge":return Xe.AVATAR_SIZE_XXXLARGE}}makeBlockAvatarFacing(e){switch(e){case"left":return tl.AVATAR_FACING_LEFT;case"right":return tl.AVATAR_FACING_RIGHT}}makeBlockAvatarBackground(e){switch(e){case"dark":return el.AVATAR_BG_DARK;case"light":return el.AVATAR_BG_LIGHT}}getDataSet(e){return Object.keys(e).filter(t=>t.startsWith(rl)).reduce((t,i)=>(t[i.substring(rl.length)]=e[i],t),{})}makeActions(e,t){let i=[],s=this.getDataSet(t);return pm.forEach(o=>{if(o in t){let d=t[o];i.push({type:gm.get(o)??da.UNRECOGNIZED,id:d.toString(),data:s})}}),i}blockColorToHex(e,t="light"){if(e)return e=e.toLowerCase(),zd(e)?e:qd(e)?Zd(e,t):Xo(e)?zs(e):$d(e)?Xd(e):Kd(e)?e:(console.warn(`Could not parse color: ${e}.`),zs("red"))}childrenToBlocks(e,t){return e.flatMap(i=>(typeof i!="string"?this.createBlocksElement(i,t):void 0)??[])}getThemedColors(e,t,i){let s=this.blockColorToHex(t,"light"),o=this.blockColorToHex(i,"dark"),d=[];if(e&&(!s||!o)){let c=Array.from(e?.matchAll(/[\w#-]+(?:\([\w\t ,.#-]+\))?/g)??[]);d.push(...c.map(m=>m[0]))}return s||(s=this.blockColorToHex(d?.at(0),"light")),o||(o=this.blockColorToHex(d?.at(1)??d?.at(0),"dark")),s||o?{light:s,dark:o}:void 0}parsePixels(e){return typeof e=="string"?Number(e.slice(0,-2)):e}resolveAssetUrl(e,t){return n(this,Wr).call(this)?.getURL(e,t)??e}childrenToString(e){return e.map(t=>t.toString()).join("")}makeRoot(e,...t){return this.wrapRoot(e,this.childrenToBlocks(t,Qo))}wrapRoot(e,t){return this.makeBlock(Ee.BLOCK_ROOT,{},{},{rootConfig:{children:t,height:this.makeRootHeight(u.customPostType?.height??e?.height??"regular")}})}makeStackBlock(e,t,i,s){let o=this.getThemedColors(t?.backgroundColor,t?.lightBackgroundColor,t?.darkBackgroundColor),d=this.makeBlockAlignment(t?.alignment),c=Yo(t,i),m=Yd(t,i.stackParentLayout,c);return this.makeBlock(Ee.BLOCK_STACK,t,i,{stackConfig:{alignment:d,backgroundColor:o?.light,backgroundColors:o,border:this.makeBlockBorder(t?.border,t?.borderColor,t?.lightBorderColor,t?.darkBorderColor),children:this.childrenToBlocks(s,{stackParentLayout:{...m,direction:e,alignment:d}}),cornerRadius:this.makeBlockRadius(t?.cornerRadius),direction:e,gap:this.makeBlockGap(t?.gap),padding:this.makeBlockPadding(t?.padding),reverse:t?.reverse}})}makeHStack(e,t,...i){return this.makeStackBlock(ra.STACK_HORIZONTAL,e,t,i)}makeVStack(e,t,...i){return this.makeStackBlock(ra.STACK_VERTICAL,e,t,i)}makeZStack(e,t,...i){return this.makeStackBlock(ra.STACK_DEPTH,e,t,i)}makeText(e,t,...i){let s=this.getThemedColors(e?.color,e?.lightColor,e?.darkColor);return this.makeBlock(Ee.BLOCK_TEXT,e,t,{textConfig:{alignment:this.makeBlockAlignment(e?.alignment),color:s?.light,colors:s,outline:this.makeBlockTextOutline(e?.outline),size:this.makeBlockTextSize(e?.size),style:this.makeBlockTextStyle(e?.style),text:this.childrenToString(i),weight:this.makeBlockTextWeight(e?.weight),selectable:e?.selectable,wrap:e?.wrap,overflow:this.makeBlockTextOverflow(e?.overflow)}})}makeButton(e,t,...i){let s=this.getThemedColors(e?.textColor,e?.lightTextColor,e?.darkTextColor);return this.makeBlock(Ee.BLOCK_BUTTON,e,t,{buttonConfig:{buttonAppearance:this.makeBlockButtonAppearance(e?.appearance),icon:e?.icon,buttonSize:this.makeBlockButtonSize(e?.size),text:this.childrenToString(i),textColor:s?.light,textColors:s,disabled:e?.disabled}})}makeImage(e,t){return e&&this.makeBlock(Ee.BLOCK_IMAGE,e,t,{imageConfig:{description:e?.description,resizeMode:this.makeBlockImageResizeMode(e.resizeMode),url:this.resolveAssetUrl(e.url),width:this.parsePixels(e.imageWidth),height:this.parsePixels(e.imageHeight)}})}makeSpacer(e,t){return this.makeBlock(Ee.BLOCK_SPACER,e,t,{spacerConfig:{size:this.makeBlockSpacerSize(e?.size),shape:this.makeBlockSpacerShape(e?.shape)}})}makeIcon(e,t){let i=this.getThemedColors(e?.color,e?.lightColor,e?.darkColor);return e&&this.makeBlock(Ee.BLOCK_ICON,e,t,{iconConfig:{icon:e.name,color:i?.light,colors:i,size:this.makeBlockIconSize(e.size)}})}makeAvatar(e,t){return e&&this.makeBlock(Ee.BLOCK_AVATAR,e,t,{avatarConfig:{thingId:e.thingId,size:this.makeBlockAvatarSize(e.size),facing:this.makeBlockAvatarFacing(e.facing),background:this.makeBlockAvatarBackground(e.background)}})}makeWebView(e,t){return e&&this.makeBlock(Ee.BLOCK_WEBVIEW,e,t,{webviewConfig:{url:this.resolveAssetUrl(e.url,{webView:!0})}})}makeBlock(e,t,i,s){return{type:e,sizes:Yo(t,i),config:s,actions:(t&&this.makeActions(e,t))??[],id:t?.id,key:t?.key}}ensureRootBlock(e){let t;if(e.type===Ee.BLOCK_ROOT?(e.config?.rootConfig&&u.customPostType?.height&&(e.config.rootConfig.height=this.makeRootHeight(u.customPostType?.height)),t=e):t=this.wrapRoot(void 0,[e]),!t)throw new Error("Could not create root block");return t}};Wr=new WeakMap;function sl(r){if(typeof r=="string")throw new Error("Root element cannot be a string")}var ol=r=>{let e="",t=r.props?Object.keys(r.props).map(i=>i==="onPress"?"":`${i}="${r.props[i]}"`).join(" "):"";e+=`<${r.type}${t?" "+t:""}>`;for(let i of r.children)typeof i=="string"?e+=i:e+=ol(i);return e+=`</${r.type}>`,e};function hm(r){return" ".repeat(r)}function fm(r){let e="",t=0,i=r.split(/>\s*</);for(let s=0;s<i.length;s++){let o=i[s];s===0&&(o=o.trim()),s===i.length-1&&(o=o.trim());let d=o.charAt(0)==="/";d&&t--,e+=hm(t),s!==0&&(e+="<"),e+=o,s!==i.length-1&&(e+=`>
|
|
2
|
-
`),!d&&o.indexOf("</")===-1&&o.charAt(o.length-1)!=="/"&&t++}return e}var Ce,al,Gr,ua,Jr,Ne=class{constructor(e,t,i,s,o){l(this,Ce);this.renderState={};this.currentComponentKey=[];this.currentHookIndex=0;this.actions=new Map;this.forms=new Map;this.realtimeChannels=[];this.realtimeUpdated=!1;this.pendingHooks=[];this.isRendering=!1;this.transformer=new Ci(()=>this.assets);this.effects=[];l(this,Jr,!1);this.component=e,this.event=t,this.state={__renderState:{},...i},this.metadata=s,this.state.__realtimeChannels&&(this.realtimeChannels=this.state.__realtimeChannels);let d=ke({reconciler:this,hooks:!0,ui:!0,metadata:s});this.cache=d.cache,this.modLog=d.modLog,this.reddit=d.reddit,this.kvStore=d.kvStore,this.redis=d.redis,this.settings=d.settings,this.scheduler=d.scheduler,this.media=d.media,this.assets=d.assets,this.realtime=d.realtime,this.dimensions=o,this.ui=d.ui,this.hooks={useState:d.useState,useInterval:d.useInterval,useForm:d.useForm,useChannel:d.useChannel}}emitEffect(e,t){this.effects.push(t)}async render(){await this.reconcile(),this.isRendering=!0;let e=await this.buildBlocksUI();return this.isRendering=!1,e}makeUniqueActionID(e){let t=e,i=1;for(;this.actions.has(t);)t=`${e}.${i++}`;return t}async reconcile(){let e=h(this,Ce,Gr).call(this),t={type:this.component,props:e,children:[]},i=await this.processBlock(t);if(sl(i),this.transformer.createBlocksElementOrThrow(i),this.isUserActionRender&&this.blockRenderEventId){let s=this.actions.get(this.blockRenderEventId);s&&await s(this.event.data)}for(let s of this.pendingHooks)await s();this.buildNextState(),h(this,Ce,al).call(this)}async buildBlocksUI(){let e=h(this,Ce,Gr).call(this),t={type:this.component,props:e,children:[]},i=await this.renderElement(e,t);return this.transformer.ensureRootBlock(i)}async renderElement(e,t){let i=await this.processBlock(t);return sl(i),(u.debug.emitSnapshots||e.debug.emitSnapshots)&&console.debug(fm(ol(i))),(u.debug.emitState||e.debug.emitState)&&console.debug(JSON.stringify(this.state,void 0,2)),this.transformer.createBlocksElementOrThrow(i)}async processProps(e){let t=e.props??{},i=["onPress","onMessage"];for(let s of i)if(s in t){let o=t[s],d=o?.name,c=this.makeUniqueActionID(`${e.type}.${d??s}`);this.actions.set(c,o),t[s]=c}}async processBlock(e,t=Gd(),i=[]){let s=e;if(typeof s.type=="string"){let c=[];for(let f=0;f<s.children.length;f++){let P=s.children[f];P!=null&&c.push(await this.processBlock(P,t,[...i,`${s.type}.${f}`]))}let m=c.flat(),y=h(this,Ce,ua).call(this,m);return await this.processProps(s),{type:s.type,props:s.props,children:y}}if(typeof s.type=="function"){let c=t(`${i.length?i.join("."):"root"}.${s.type.name.length?s.type.name:"anonymous"}`);this.currentComponentKey.push(c),this.renderState[c]||(this.renderState[c]={});let m=s.children.flatMap(f=>f),y={...h(this,Ce,Gr).call(this),...s.props,children:m},v;for(;v===void 0;)try{v=await s.type(y,h(this,Ce,Gr).call(this))}catch(f){if(f instanceof Promise)v=await f;else throw f}if(!this.isInitialRender){let f=this.getPreviousComponentState();if(Object.keys(f).length!==this.currentHookIndex)throw new Error("Invalid hook call. Hooks can only be called at the top-level of a function component. Make sure that you are not calling hooks inside loops, conditions, or nested functions.")}if(this.currentComponentKey.pop(),this.currentHookIndex=0,typeof v=="object")return this.processBlock(v,t,[...i,s.type.name])}if(typeof s=="string")return s;if(typeof s=="number")return`${s}`;let o=[],d="";return Array.isArray(s)?o=s:typeof s.type>"u"&&s.children&&(o=s.children,d="fragmentChild."),{type:"__fragment",props:void 0,children:await Promise.all(o.flatMap(async(c,m)=>await this.processBlock(c,t,[...i,`${d}${m}`])))}}getCurrentComponentKey(){if(!this.currentComponentKey.at(-1))throw new Error("Current component key is missing");return this.currentComponentKey}getCurrentComponentState(){let e=this.currentComponentKey.at(-1);if(!e)throw new Error("Current component key is missing");return this.renderState[e]}getPreviousComponentState(){let e=this.currentComponentKey.at(-1);if(!e)throw new Error("Current component key is missing");return this.state.__renderState[e]||(this.state.__renderState[e]={}),this.state.__renderState[e]}get isInitialRender(){return this.event?this.event.type===la.RENDER_INITIAL:!1}get isUserActionRender(){return this.event?this.event.type===la.RENDER_USER_ACTION:!1}get isEffectRender(){return this.event?this.event.type===la.RENDER_EFFECT_EVENT:!1}get formSubmittedEvent(){return this.event?this.event.formSubmitted:!1}get blockRenderEventId(){return this.event?this.event.id:!1}get realtimeEvent(){if(!this.event)return!1;let e=this.event.realtimeEvent;return e?.event?.channel?e:!1}runHook(e){this.pendingHooks.push(e)}rerenderIn(e){n(this,Jr)||(a(this,Jr,!0),this.effects.push({type:nl.EFFECT_RERENDER_UI,rerenderUi:{delaySeconds:e/1e3}}))}addRealtimeChannel(e){this.realtimeChannels.push(e),this.realtimeUpdated=!0}removeRealtimeChannel(e){this.realtimeChannels=this.realtimeChannels.filter(t=>t!==e),this.realtimeUpdated=!0}get realtimeEffect(){return this.realtimeUpdated&&this.realtimeChannels.length>0?[{type:nl.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:this.realtimeChannels}}]:[]}getEffects(){return[...bi(this.ui),...this.effects,...this.realtimeEffect]}buildNextState(){for(let e of Object.keys(this.renderState))this.renderState[e]=Object.values(this.renderState[e]);this.state={__postData:this.state.__postData,__renderState:this.renderState,__cache:this.state.__cache,...this.realtimeChannels.length>0?{__realtimeChannels:this.realtimeChannels}:{}}}};Ce=new WeakSet,al=function(){this.actions.clear(),this.currentComponentKey=[],this.currentHookIndex=0,this.pendingHooks=[],this.realtimeChannels=[],this.realtimeUpdated=!1},Gr=function(){let e={...se(this.metadata,this.state.__postData?.thingId),modLog:this.modLog,reddit:this.reddit,cache:this.cache,kvStore:this.kvStore,redis:this.redis,settings:this.settings,scheduler:this.scheduler,media:this.media,assets:this.assets,realtime:this.realtime,ui:this.ui,dimensions:this.dimensions,uiEnvironment:{timezone:this.metadata[S.Timezone]?.values[0],locale:this.metadata[S.Language]?.values[0],dimensions:this.dimensions},...this.hooks};return e.debug.effects=this,e},ua=function(e){let t=[];for(let i of e)typeof i=="string"?t.push(i):i.type==="__fragment"?t.push(...h(this,Ce,ua).call(this,i.children)):t.push(i);return t},Jr=new WeakMap;async function vm(r,e){let t=u.customPostType;if(!t)throw new Error("Custom post type not registered");let i=new Ne((o,d)=>t.render(d),r.blocks,r.state,e,r.dimensions),s=await i.render();return bm.fromJSON({state:i.state,blocks:{ui:s},effects:i.getEffects()})}function dl(r){r.provides(ym),O("RenderPost",vm)}import{GetFieldsResponse as km,InstallationSettingsDefinition as Cm}from"@devvit/protos";async function Pm(){if(!u.installationSettings)throw new Error("Installation settings were not defined.");return km.fromJSON({fields:{fields:De(u.installationSettings)}})}async function Sm(r,e){return Js(r,u.installationSettings,e)}function ll(r){r.provides(Cm),O("GetSettingsFields",Pm),O("ValidateForm",Sm)}import{ContextActionDefinition as wm,ContextActionList as Fm,ContextActionResponse as xm}from"@devvit/protos";function ca(r){let e=r.debug.metadata[S.User].values[0];if(!e)throw new Error("User missing from context");return e}function ma(r){let e=r.debug.metadata[S.Subreddit].values[0];if(!e)throw new Error("Subreddit missing from context");return e}async function ul(r,e){let t=ca(r),i=ma(r);if(!t||!i)throw new Error("User or subreddit missing from context");let s=e.comment?.id&&`t1_${e.comment.id}`,o=e.post?.id&&`t3_${e.post.id}`,d=e.subreddit?.id&&`t5_${e.subreddit.id}`,c=s||o||d;if(!c)throw new Error("targetId is missing from ContextActionRequest");if(s){let f=await r.reddit.getCommentById(s);if(!f)throw new Error(`Comment ${s} not found`);if(f.subredditId!==i)throw new Error("Comment does not belong to the subreddit")}if(o){let f=await r.reddit.getPostById(o);if(!f)throw new Error(`Post ${o} not found`);if(f.subredditId!==i)throw new Error("Post does not belong to the subreddit")}if(d&&d!==i)throw new Error(`Subreddit ${d} ${i} not found`);let m=zr(e.actionId);if(!m)throw new Error("Action not found");let y=!!m.forUserType?.includes("moderator");if(y&&!cl(r))throw new Error("User is not a moderator");let v={needsModCheck:y};await r.redis.set(`${t}${i}${c}${e.actionId}`,JSON.stringify(v)),await r.redis.expire(`${t}${i}${c}${e.actionId}`,600),console.debug("CSRF token added: "+JSON.stringify(v))}async function cl(r){let e=ca(r),t=ma(r),i=await r.reddit.getSubredditInfoById(t);return!!(await r.reddit.getModerators({subredditName:i.name}).all()).find(o=>o.id===e)}async function ml(r,e){let t=ca(r),i=ma(r),{actionId:s,thingId:o}=e.state?.__contextAction??{},d=await r.redis.get(`${t}${i}${o}${s}`);if(!d)throw new Error("CSRF token not found");if(JSON.parse(d).needsModCheck&&!await cl(r))throw new Error("User is not a moderator: "+t+"; "+i);console.debug("CSRF token validated: "+d)}var pl=r=>`menuItem.${r}`;function zr(r){return u.menuItems.find((e,t)=>pl(t)===r)}async function Im(r,e){let t=u.menuItems;if(!t.length)throw new Error("No menu items registered.");let i=t.map((s,o)=>({actionId:pl(o),name:s.label,description:s.description,contexts:{subreddit:s.location.includes("subreddit"),post:s.location.includes("post"),comment:s.location.includes("comment")},users:{loggedOut:s.forUserType?.includes("loggedOut"),moderator:s.forUserType?.includes("moderator")},postFilters:s.postFilter==="currentApp"?{currentApp:!0}:void 0}));return Fm.fromJSON({actions:i})}async function Am(r,e){let t=zr(r.actionId);if(!t)throw new Error(`MenuItem ${r.actionId} not found`);let i=r.comment?.id&&`t1_${r.comment.id}`,s=r.post?.id&&`t3_${r.post.id}`,o=r.subreddit?.id&&`t5_${r.subreddit.id}`,d=i||s||o;p(d,"targetId is missing from ContextActionRequest");let c={targetId:d,location:r.comment?"comment":r.post?"post":"subreddit"},m=Object.assign(ke({ui:!0,metadata:e}),se(e,s,i),{uiEnvironment:{timezone:e[S.Timezone]?.values[0],locale:e[S.Language]?.values[0]}});return await ul(m,r),await t.onPress(c,m),xm.fromJSON({effects:bi(m.ui)})}function gl(r){r.provides(wm),O("GetActions",Im),O("OnAction",Am)}function Le(r){return r?r===!0?!0:r.enabled:!1}import{SchedulerHandlerDefinition as Em}from"@devvit/protos";async function Tm(r,e){let t=r.type,i=u.scheduledJobHandlers.get(t);if(!i)throw new Error(`Job ${t} not found`);let s={name:t,data:r.data},o=Object.assign(ke({metadata:e}),se(e));await i(s,o)}function hl(r){r.provides(Em),O("HandleScheduledAction",Tm)}import{OnAppInstallDefinition as Rm,OnAppUpgradeDefinition as Om,OnAutomoderatorFilterCommentDefinition as Mm,OnAutomoderatorFilterPostDefinition as Bm,OnCommentCreateDefinition as Um,OnCommentDeleteDefinition as Dm,OnCommentReportDefinition as Nm,OnCommentSubmitDefinition as Lm,OnCommentUpdateDefinition as _m,OnModActionDefinition as Hm,OnModMailDefinition as jm,OnPostCreateDefinition as Vm,OnPostDeleteDefinition as Wm,OnPostFlairUpdateDefinition as Gm,OnPostNsfwUpdateDefinition as Jm,OnPostReportDefinition as zm,OnPostSpoilerUpdateDefinition as qm,OnPostSubmitDefinition as $m,OnPostUpdateDefinition as Km}from"@devvit/protos";var Ye;(function(r){function e(d,c){return d.length<=c?d:`${d.slice(0,c-1)}\u2026`}r.ellipsize=e;function t(d){return d[0]==null?d:`${d[0].toLocaleUpperCase()}${d.slice(1)}`}r.capitalize=t;function i(d){return d==null||/^\s*$/.test(d)}r.isBlank=i;function s(d,c="stack"){return d instanceof Error?`${d[c]||d.stack||d.message||d.name}`:String(d)}r.caughtToString=s;function o(d,c="stack"){return d instanceof Error?`${d[c]||d.stack||d.message||d.name}`:String(d)}r.caughtToStringUntyped=o})(Ye||(Ye={}));function $(r,e){return p(e),async(t,i)=>{let s={...t,type:r},o=Object.assign(ke({metadata:i}),se(i)),d=await Promise.allSettled(e.map(m=>m(s,o))),c=Zm(d);if(c)throw c.err;return{}}}function fl(r){for(let e of u.triggerOnEventHandlers.keys())switch(e){case"PostSubmit":r.provides($m),O("OnPostSubmit",$("PostSubmit",u.triggerOnEventHandlers.get(e)));break;case"PostCreate":r.provides(Vm),O("OnPostCreate",$("PostCreate",u.triggerOnEventHandlers.get(e)));break;case"PostUpdate":r.provides(Km),O("OnPostUpdate",$("PostUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostReport":r.provides(zm),O("OnPostReport",$("PostReport",u.triggerOnEventHandlers.get(e)));break;case"PostDelete":r.provides(Wm),O("OnPostDelete",$("PostDelete",u.triggerOnEventHandlers.get(e)));break;case"PostFlairUpdate":r.provides(Gm),O("OnPostFlairUpdate",$("PostFlairUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentSubmit":r.provides(Lm),O("OnCommentSubmit",$("CommentSubmit",u.triggerOnEventHandlers.get(e)));break;case"CommentCreate":r.provides(Um),O("OnCommentCreate",$("CommentCreate",u.triggerOnEventHandlers.get(e)));break;case"CommentUpdate":r.provides(_m),O("OnCommentUpdate",$("CommentUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentReport":r.provides(Nm),O("OnCommentReport",$("CommentReport",u.triggerOnEventHandlers.get(e)));break;case"CommentDelete":r.provides(Dm),O("OnCommentDelete",$("CommentDelete",u.triggerOnEventHandlers.get(e)));break;case"AppInstall":r.provides(Rm),O("OnAppInstall",$("AppInstall",u.triggerOnEventHandlers.get(e)));break;case"AppUpgrade":r.provides(Om),O("OnAppUpgrade",$("AppUpgrade",u.triggerOnEventHandlers.get(e)));break;case"ModAction":r.provides(Hm),O("OnModAction",$("ModAction",u.triggerOnEventHandlers.get(e)));break;case"ModMail":r.provides(jm),O("OnModMail",$("ModMail",u.triggerOnEventHandlers.get(e)));break;case"PostNsfwUpdate":r.provides(Jm),O("OnPostNsfwUpdate",$("PostNsfwUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostSpoilerUpdate":r.provides(qm),O("OnPostSpoilerUpdate",$("PostSpoilerUpdate",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterPost":r.provides(Bm),O("OnAutomoderatorFilterPost",$("AutomoderatorFilterPost",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterComment":r.provides(Mm),O("OnAutomoderatorFilterComment",$("AutomoderatorFilterComment",u.triggerOnEventHandlers.get(e)));break;default:throw new Error(`Unknown trigger event: ${e}`)}}function Zm(r){let e=r.reduce((t,i)=>i.status==="rejected"?[...t,i.reason]:t,[]);if(e.length!==0)return e.length===1?{err:e[0]}:{err:new Error(e.map(t=>Ye.caughtToString(t)).join(`
|
|
3
|
-
`))}}import{EffectType as kp,HandleUIEventResponse as ha,UIEventHandlerDefinition as Cp}from"@devvit/protos";var Ml=nd(Al(),1);function El(r){return r?.constructor===Object}function Tt(r,e){return Object.is(r,e)?!0:typeof r!=typeof e?!1:Array.isArray(r)&&Array.isArray(e)?Tl(r,e):r instanceof Date&&e instanceof Date?r.getTime()===e.getTime():r instanceof RegExp&&e instanceof RegExp?r.toString()===e.toString():El(r)&&El(e)?vp(r,e):r instanceof ArrayBuffer&&e instanceof ArrayBuffer?Rl(new DataView(r),new DataView(e)):r instanceof DataView&&e instanceof DataView?Rl(r,e):Ol(r)&&Ol(e)?r.byteLength!==e.byteLength?!1:Tl(r,e):!1}function vp(r,e){let t=Object.keys(r),i=Object.keys(e);if(!Tt(t,i))return!1;for(let s of t)if(!Tt(r[s],e[s]))return!1;return!0}function Tl(r,e){return r.length!==e.length?!1:r.every((t,i)=>Tt(t,e[i]))}function Rl(r,e){if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r.getUint8(t)!==e.getUint8(t))return!1;return!0}function Ol(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}async function Pp(r,e){let t=r.state??{},i=(0,Ml.default)(t),s=ke({ui:!0,metadata:e});if(r.event?.formSubmitted&&r.event.formSubmitted.formId){let m=r.event.formSubmitted.formId;if(m.includes("form.hook.")&&u.customPostType){let b=new Ne((W,R)=>u.customPostType?.render(R)??null,r.event,r.state,e,void 0);return await b.reconcile(),ha.fromJSON({state:b.state,effects:b.getEffects()})}let y=u.formDefinitions.get(m);if(!y)throw new Error(`Form with key ${m} not found`);let v,f;if(i.__contextAction){let{actionId:b,thingId:W}=i.__contextAction,R=zr(b);R?.location==="post"?v=W:R?.location==="comment"&&(f=W)}let P=Object.assign(s,se(e,v,f),{uiEnvironment:{timezone:e[S.Timezone]?.values[0],locale:e[S.Language]?.values[0]}});await ml(P,r),await y.onSubmit({values:ze(r.event.formSubmitted.results)},P)}else if(r.event?.realtimeEvent){if(u.customPostType){let m=new Ne((y,v)=>u.customPostType?.render(v)??null,r.event,r.state,e,void 0);return await m.reconcile(),ha.fromJSON({state:m.state,effects:m.getEffects()})}}else if(r.event?.toastAction)throw new Error("Toast actions not yet implemented");let o=!Tt(t,i),d=bi(s.ui),c=o?[...d,{type:kp.EFFECT_RERENDER_UI,rerenderUi:{delaySeconds:0}}]:d;return ha.fromJSON({state:i,effects:c})}function Bl(r){r.provides(Cp),O("HandleUIEvent",Pp)}import{CustomPostDefinition as po,UIResponse as au}from"@devvit/protos";import{UIEventScope as Tp}from"@devvit/protos";var fa="ServerCallRequired";function Ys(r){return r?.message===fa}var ka={now(){return new Date}};function Ul(r){return`__autocache__${r}`}function Dl(r){return`__lock__${r}`}var Sp=300,wp=1e3,eo=5e3,ya=3,Nl=.1,Ll=1e3,Fp=3e4;function _l(r){if(r.error)throw new Error(r.error);return r.value}var et,tt,Pe,Pi,q,Hl,jl,Vl,ba,Wl,Gl,va,Jl,to=class{constructor(e,t,i=ka){l(this,q);l(this,et);l(this,tt,{});l(this,Pe);l(this,Pi);a(this,et,e),a(this,Pi,t),a(this,Pe,i)}async cache(e,t){var d;(d=n(this,Pi)).__cache??(d.__cache={}),a(this,tt,n(this,Pi).__cache),h(this,q,Jl).call(this,t);let i=h(this,q,Hl).call(this,t.key);if(i!==void 0)return i;let s=await h(this,q,va).call(this,t.key),o=await h(this,q,jl).call(this,t,s,e);return _l(o)}};et=new WeakMap,tt=new WeakMap,Pe=new WeakMap,Pi=new WeakMap,q=new WeakSet,Hl=function(e){let t=n(this,tt)[e];if(t){let i=n(this,Pe).now().getTime(),s=t?.error&&t?.errorTime&&t.errorCount<ya&&Math.random()<Nl&&t.errorTime+Ll<i;if(t?.expires&&t.expires<i&&t.checkedAt+Ll<i||s){delete n(this,tt)[e];return}else return _l(t)}},jl=async function(e,t,i){let s=t?.expires,o=s?h(this,q,Gl).call(this,s):1;return!t||t?.error&&t.errorCount<ya&&Nl>Math.random()||o>Math.random()?h(this,q,Vl).call(this,e,t,i):t},Vl=async function(e,t,i){let s=Dl(e.key),o=n(this,Pe).now().getTime(),d=new Date(o+e.ttl/2);if(await n(this,et).set(s,"1",{expiration:d,nx:!0}))return h(this,q,Wl).call(this,e.key,t,i,e.ttl);if(t)return t;{let m=n(this,Pe).now();return h(this,q,ba).call(this,m,e.key,e.ttl)}},ba=async function(e,t,i){let s=Math.min(i,wp),o=await h(this,q,va).call(this,t);if(o)return o;if(n(this,Pe).now().getTime()-e.getTime()>=s)throw new Error(`Cache request timed out trying to get data at key: ${t}`);return await new Promise(d=>setTimeout(d,Sp)),h(this,q,ba).call(this,e,t,i)},Wl=async function(e,t,i,s){let o=n(this,Pe).now().getTime()+s;t=t??{value:null,expires:o,errorCount:0,error:null,errorTime:null,checkedAt:0};try{t.value=await i(),t.error=null,t.errorCount=0,t.errorTime=null}catch(d){t.value=null,t.error=d.message??"Unknown error",t.errorTime=n(this,Pe).now().getTime(),t.errorCount++}return n(this,tt)[e]=t,await n(this,et).set(Ul(e),JSON.stringify(t),{expiration:new Date(o+Fp)}),t.error&&t.errorCount<ya&&await n(this,et).del(Dl(e)),t},Gl=function(e){let t=n(this,Pe).now().getTime(),i=e-t;return i<0?1:i<1e3?.1:i<2e3?.01:i<3e3?.001:0},va=async function(e){let t=await n(this,et).get(Ul(e));if(t){let i=JSON.parse(t);return i.checkedAt=n(this,Pe).now().getTime(),n(this,tt)[e]=i,i}},Jl=function(e){e.ttl<eo&&(console.warn(`Cache TTL cannot be less than ${eo} milliseconds! Updating ttl value of ${e.ttl} to ${eo}.`),e.ttl=eo)};function zl(r,e,t=ka){let i=new to(r,e,t);return i.cache.bind(i)}import{EffectType as io,ToastAppearance as Kl}from"@devvit/protos";function ql(r){let e=r.match(/form\.hook\.(.+)\.0/);if(e?.[1])return e[1]}var Ca=class{constructor(e,t,i){this.state=null;this.hookId=e.hookId,this.form=t,this.onSubmit=i,this.onUIEvent=async s=>{s.formSubmitted&&await i(ze(s.formSubmitted.results))}}};function Pa(r,e){let t=me({namespace:"useForm",initializer:i=>new Ca(i,r,e)});return xp({id:t.hookId})}function xp(r){return`form.hook.${r.id}.0`}function $l(r,e){let t=ql(e);return r.getHook({id:t})}var _e,no,qr,so,ro=class{constructor(e){l(this,_e);l(this,no,0);l(this,qr);l(this,so,(e,t)=>{let i=t!==void 0?e:"",s=t!==void 0?t:e;n(this,_e).emitEffect(`postMessage${sd(this,no)._++}`,{type:io.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:i,app:{message:s,jsonString:JSON.stringify(s)}}}})});a(this,_e,e),a(this,qr,{postMessage:n(this,so)})}get webView(){return n(this,qr)}showForm(e,t){let i=$l(n(this,_e),e);if(!i)throw new Error("Form does not exist. Make sure you have added it using useForm.");let s=i.form instanceof Function?i.form(t??{}):i.form,o={fields:[],id:e,title:s.title,acceptLabel:s.acceptLabel,cancelLabel:s.cancelLabel,shortDescription:s.description};xt(s.fields),o.fields=De(s.fields),n(this,_e).emitEffect(e,{type:io.EFFECT_SHOW_FORM,showForm:{form:o}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Kl.SUCCESS:Kl.NEUTRAL}:t={text:e},n(this,_e).emitEffect(e.toString(),{type:io.EFFECT_SHOW_TOAST,showToast:{toast:t}})}navigateTo(e){let t;typeof e=="string"?t=new URL(e).toString():t=new URL(e.permalink,"https://www.reddit.com").toString(),n(this,_e).emitEffect(t,{type:io.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}};_e=new WeakMap,no=new WeakMap,qr=new WeakMap,so=new WeakMap;import{EffectType as Ip,RealtimeSubscriptionStatus as Zl}from"@devvit/protos";var it,Te,rt,Rt,$r,wa,oo=class oo{constructor(e,t){l(this,$r);l(this,it);l(this,Te);l(this,rt);l(this,Rt);a(this,it,t.context),a(this,Te,!!t.context._devvitContext?.debug.realtime),a(this,Rt,e),a(this,rt,t.invalidate);let i=t.context.meta[S.App]?.values[0];if(!i)throw Error("useChannel missing app ID metadata");let s=t.context.meta[S.Installation]?.values[0];if(!s)throw Error("useChannel missing install ID from metadata");let o=`${i}:${s}:${e.name}`;if(Object.values(n(this,it)._hooks).filter(c=>c instanceof oo).some(c=>c.state.channel===o))throw Error(`useChannel channel names must be unique; "${o}" duplicated`);this.state={channel:o,connected:!1,subscribed:!1}}async onUIEvent(e){let t=e.realtimeEvent;if(!(!t||!this.state.subscribed))switch(t.status){case Zl.REALTIME_SUBSCRIBED:n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" connected`),this.state.connected=!0,n(this,rt).call(this),await n(this,Rt).onSubscribed?.();break;case Zl.REALTIME_UNSUBSCRIBED:n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" disconnected`),this.state.connected=!1,n(this,rt).call(this),await n(this,Rt).onUnsubscribed?.();break;default:n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" received message: ${JSON.stringify(e,void 0,2)}`),n(this,Rt).onMessage(t.event?.data?.msg);break}}async send(e){if(n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" send message: ${JSON.stringify(e,void 0,2)}`),!this.state.subscribed||!this.state.connected)throw console.debug(`[realtime] "${this.state.channel}" send failed; channel not connected`),Error(`useChannel send failed; "${this.state.channel}" channel not connected`);await n(this,it).devvitContext.realtime.send(this.state.channel,e)}get status(){return this.state.subscribed&&this.state.connected?2:this.state.subscribed&&!this.state.connected?1:!this.state.subscribed&&this.state.connected?3:4}subscribe(){this.state.subscribed||(n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" subscribed`),this.state.subscribed=!0,n(this,rt).call(this),h(this,$r,wa).call(this))}unsubscribe(){this.state.subscribed&&(n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" unsubscribed`),this.state.subscribed=!1,n(this,rt).call(this),h(this,$r,wa).call(this))}};it=new WeakMap,Te=new WeakMap,rt=new WeakMap,Rt=new WeakMap,$r=new WeakSet,wa=function(){let e=Object.values(n(this,it)._hooks).filter(t=>t instanceof oo&&t.state.subscribed).map(t=>t.state.channel);n(this,it).emitEffect(this.state.channel,{type:Ip.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:e}})};var Sa=oo;function Fa(r){if(!r.name||/[^a-zA-Z0-9_]/.test(r.name))throw Error(`useChannel error: The name "${r.name}" you provided for the hook is invalid. Valid names can only contain letters, numbers, and underscores (_).`);let e=`useChannel:${r.name}`;return me({id:e,namespace:e,initializer:t=>new Sa(r,t)})}import{EffectType as xa}from"@devvit/protos";function Xl(r){return typeof r=="object"&&r!==null&&"__deleted"in r}var Ot,nt,Si=class Si{constructor(e,t){l(this,Ot);this._segments=[];l(this,nt,{});this._prevHooks={};this._prevHookId="";this._effects={};this._changed={};this._touched={};this._requeueEvents=[];this._rootProps={};this._generated={};this._undeliveredHandlers={};this.request=e,this.meta=t,a(this,Ot,e.state??{__cache:{}}),this._rootProps=e.props??{}}get devvitContext(){if(!this._devvitContext)throw new Error("Devvit context not available");return this._devvitContext}set devvitContext(e){this._devvitContext=e}get _changedState(){let e={__cache:n(this,Ot).__cache??{}};for(let i in this._changed)e[i]=this._state[i];let t=new Set(Object.keys(this._state));return Object.keys(n(this,nt)).forEach(i=>{i!=="__cache"&&t.delete(i)}),t.forEach(i=>{if(i==="__cache")return;let s={__deleted:!0};this._state[i]=e[i]=s}),e}get _hooks(){return n(this,nt)}set _hooks(e){this._prevHooks=n(this,nt),a(this,nt,e)}get _state(){return n(this,Ot)}set _state(e){a(this,Ot,e)}push(e){this._segments.push({...e,next:0})}pop(){this._segments.pop()}addUndeliveredEventHandler(e,t){this._undeliveredHandlers[e]=t}addGlobalUndeliveredEventHandler(e,t){Si.addGlobalUndeliveredEventHandler(e,t)}getHook(e){return n(this,nt)[e.id]}static addGlobalUndeliveredEventHandler(e,t){Si._staticUndeliveredHandlers[e]=t}async handleUndeliveredEvent(e){let t={...Si._staticUndeliveredHandlers,...this._undeliveredHandlers};for(let[i,s]of Object.entries(t))await s(e,this)}emitEffect(e,t){this._effects[e]=t}addToRequeueEvents(...e){this._devvitContext?.debug.blocks&&console.debug("[blocks] requeueing events",e);let t=e.reduce((i,s)=>(s.retry?i.retry.push(s):i.normal.push(s),i),{retry:[],normal:[]});this._requeueEvents=[...t.retry,...this._requeueEvents,...t.normal]}get effects(){return Object.values(this._effects)}nextHookId(e){e.key===void 0&&(e.key=this._segments[this._segments.length-1].next+++""),this.push(e);try{let t=[];for(let s=this._segments.length-1;s>=0;s--){let o=this._segments[s];if(o.id){t.unshift(o.id);break}let d=[];o.namespace&&d.push(o.namespace),o.key!==void 0&&o.key!==!1&&d.push(o.key),t.unshift(d.join("-"))}let i=t.join(".");if(this._generated[i]&&!e.shared)throw new Error(`Hook id ${i} already used, cannot register another hook with the same id`);return this._generated[i]=!0,this._prevHookId=i,i}finally{this.pop()}}};Ot=new WeakMap,nt=new WeakMap,Si._staticUndeliveredHandlers={};var wi=Si;var st={};wi.addGlobalUndeliveredEventHandler("intervals",async(r,e)=>{r.timer&&r.hook&&(delete st[r.hook],e.emitEffect("timers",{type:xa.EFFECT_SET_INTERVALS,interval:{intervals:st}}))});var ot,Fi,Kr,xi,Ia=class{constructor(e,t,i){l(this,ot);l(this,Fi);l(this,Kr);l(this,xi);this.state={duration:{seconds:0,nanos:0},running:!1};a(this,Fi,i.invalidate),a(this,ot,i.hookId),a(this,Kr,e),a(this,xi,i.context);let s=Math.floor(t/1e3),o=t%1e3*1e6;this.state.duration={seconds:s,nanos:o}}onStateLoaded(){this.state.running?st[n(this,ot)]={duration:this.state.duration}:delete st[n(this,ot)]}async onUIEvent(e){await n(this,Kr).call(this)}start(){st[n(this,ot)]={duration:this.state.duration},this.state.running=!0,n(this,Fi).call(this),n(this,xi).emitEffect("timers",{type:xa.EFFECT_SET_INTERVALS,interval:{intervals:st}})}stop(){delete st[n(this,ot)],this.state.running=!1,n(this,Fi).call(this),n(this,xi).emitEffect("timers",{type:xa.EFFECT_SET_INTERVALS,interval:{intervals:st}})}};ot=new WeakMap,Fi=new WeakMap,Kr=new WeakMap,xi=new WeakMap;function Aa(r,e){let t=me({namespace:"useInterval",initializer:i=>new Ia(r,e,i)});return{start:()=>t.start(),stop:()=>t.stop()}}import{UIEventScope as Ep}from"@devvit/protos";var Mt=class extends Error{};import{UIEventScope as Ql}from"@devvit/protos";function Ta(r){if(r instanceof Error){if(r.message===fa)throw r;return console.error(r),{message:r.message,details:r.stack??""}}else return console.error(r),{message:"Unknown error",details:Ye.caughtToString(r)}}var Fe,Re,Ii,Zr,Ai,Ea=class{constructor(e,t,i){l(this,Fe);l(this,Re);l(this,Ii);l(this,Zr);l(this,Ai);a(this,Fe,!!i.context.devvitContext.debug.useAsync),n(this,Fe)&&console.debug("[useAsync] v1",t),this.state={data:null,load_state:"initial",error:null,depends:null},a(this,Re,i.hookId),this.initializer=e,a(this,Ii,i.invalidate),a(this,Zr,i.context),this.localDepends=t.depends??null,a(this,Ai,t)}onStateLoaded(){if(n(this,Fe)&&console.debug("[useAsync] async onLoad ",n(this,Re),this.state),n(this,Fe)&&console.debug("[useAsync] async onLoad have ",this.localDepends,"and",this.state.depends),!Tt(this.localDepends,this.state.depends)||this.state.load_state==="initial"){n(this,Fe)&&console.debug("[useAsync] attempting to resolve for hookId",n(this,Re)),this.state.load_state="loading",this.state.depends=this.localDepends,n(this,Ii).call(this);let e={scope:Ql.ALL,hook:n(this,Re),async:!0,asyncRequest:{requestId:n(this,Re)+"-"+JSON.stringify(this.state.depends)}};n(this,Fe)&&console.debug("[useAsync] onLoad requeue"),n(this,Zr).addToRequeueEvents(e)}}async onUIEvent(e,t){if(e.asyncRequest){let i={requestId:e.asyncRequest.requestId};try{i.data={value:await this.initializer()}}catch(o){i.error=Ta(o)}let s={scope:Ql.ALL,asyncResponse:i,hook:n(this,Re)};n(this,Fe)&&console.debug("[useAsync] onReq requeue"),t.addToRequeueEvents(s)}else if(e.asyncResponse){let i=n(this,Re)+"-"+JSON.stringify(this.state.depends);e.asyncResponse.requestId===i?(this.state={...this.state,data:e.asyncResponse.data?.value??null,error:e.asyncResponse.error??null,load_state:e.asyncResponse.error?"error":"loaded"},n(this,Ai).finally&&await n(this,Ai).finally(this.state.data,this.state.error?new Error(this.state.error?.message??"Unknown error"):null),n(this,Ii).call(this)):n(this,Fe)&&console.debug("[useAsync] onResp skip, stale event",e.asyncResponse.requestId," !== ",i)}else throw new Error("Unknown event type")}};Fe=new WeakMap,Re=new WeakMap,Ii=new WeakMap,Zr=new WeakMap,Ai=new WeakMap;function Ap(r,e={}){let t=me({namespace:"useAsync",initializer:i=>new Ea(r,e,i)});return{data:t.state.data,error:t.state.error,loading:t.state.load_state==="loading"}}var He,Ei,Bt,at,Ra=class{constructor(e,t){this.state={value:null,load_state:"initial",error:null};l(this,He);l(this,Ei);l(this,Bt);l(this,at);a(this,Bt,e),a(this,at,t.hookId),a(this,He,t.invalidate),a(this,Ei,t.context)}async onUIEvent(){if(this.state.load_state==="loading"&&this._promise){try{this.state.value=await this._promise,this.state.load_state="loaded"}catch(e){this.state.load_state="error",this.state.error=Ta(e)}n(this,He).call(this)}else console.warn(`Invalid state for hook (${n(this,at)}):`,this.state.load_state,this._promise)}setter(e){this.state.value=e instanceof Function?e(this.state.value):e,this.state.load_state="loaded",n(this,He).call(this)}onStateLoaded(){if(this._promise=n(this,Ei)._prevHooks[n(this,at)]?._promise,this.state.load_state==="loading")throw new Mt;if(this.state.load_state==="error")throw new Error(this.state.error?.message??"Unknown error");if(this.state.load_state==="initial"){let e;try{e=n(this,Bt)instanceof Function?n(this,Bt).call(this):n(this,Bt)}catch(t){console.log("error in loading async",t),this.state.load_state="error",n(this,He).call(this);return}if(e instanceof Promise){this._promise=e,this.state.load_state="loading";let t={scope:Ep.ALL,asyncRequest:{requestId:n(this,at)},hook:n(this,at)};throw n(this,Ei).addToRequeueEvents(t),n(this,He).call(this),new Mt}else this.state.value=e,this.state.load_state="loaded";n(this,He).call(this)}}};He=new WeakMap,Ei=new WeakMap,Bt=new WeakMap,at=new WeakMap;function Oa(r){let e=me({namespace:"useState",initializer:t=>new Ra(r,t)});return[e.state.value,e.setter.bind(e)]}var ao=class{buildContext(e,t,i){let s=new ui(i),o=new di(i),d=new gi(i),c=new mi(i),m=new hi(i),y=new fi(i),v=new ro(e),f=new li(i),P=new oi,b=new ci(i),W=zl(d,e._state),R={modLog:s,kvStore:o,redis:d,reddit:c,scheduler:m,settings:y,media:f,assets:P,realtime:b,ui:v,useState:Oa,useChannel:Fa,useInterval:Aa,useForm:Pa,cache:W,dimensions:t.env?.dimensions,uiEnvironment:{timezone:i[S.Timezone]?.values[0],locale:i[S.Language]?.values[0],dimensions:t.env?.dimensions,colorScheme:t.env?.colorScheme}},H=se(i,t.props?.postId);return H.debug.effects=e,{...H,...R}}};var pe=null;function Yl(r){return JSON.parse(JSON.stringify(r))}function Rp(r){if(!(r!==""&&!/[-.]/.test(r)))throw new Error(`Hook with namespace '${r}' is invalid. Hook namespaces cannot be empty string or contain dashes/dots because they are used as delimiters internally. Please update the hook namespace and try again.`)}function me({initializer:r,...e}){if(!pe)throw new Error("Hooks can only be declared at the top of a component. You cannot declare hooks outside of components or inside of event handlers. It's almost always a mistake to declare hooks inside of loops or conditionals.");Rp(e.namespace);let t=pe.nextHookId(e),i=pe,s={hookId:t,invalidate:()=>{i._changed[t]=!0,i._state[t]=i?._hooks[t]?.state},context:pe},o=pe._state[t]===void 0||Xl(pe._state[t]);pe._hooks[t]=pe._hooks[t]??r(s);let d=pe._hooks[t];return o||(d.state=pe._state[t]),d.onStateLoaded?.(),o&&d.state!==void 0&&d.state!==null&&s.invalidate(),d}var Op=null,lo=128,Ti,mo,Xr,F,oe,uo,eu,Ma,tu,Ba,Ua,co,Da,iu,Ut=class{constructor(e){l(this,F);l(this,Ti);l(this,mo,new ao);l(this,Xr,new Ci(()=>this._latestRenderContext?.devvitContext?.assets));this._latestRenderContext=null;n(this,F,oe)&&console.debug("[blocks] BlocksHandler v1"),a(this,Ti,e),Op=this}async handle(e,t){let i=new wi(e,t),s=n(this,mo).buildContext(i,e,t);i.devvitContext=s;let o,d=e.events.length-lo,c=e.events;if(d>0){c=[];{let R=0;for(let H of e.events)R<d&&H.realtimeEvent?R++:c.push(H)}for(;c.length>lo;)c.shift();console.warn(`dropped ${d} events`)}let y=!c.length||c.some(R=>!R.async),v=c.some(R=>R.blocking),f,P,b=[...c];c.length===0&&c.push({scope:Tp.ALL}),n(this,F,oe)&&console.debug("[blocks] starting processing events");let W=0;for(;c.length>0;){if(W++>lo)throw new Error(`Exceeded maximum iterations of ${lo}`);n(this,F,oe)&&console.debug("[blocks] processing events loop iteration",c.length);let R=[];if(!c[0].async)R.push(c.shift());else for(;c[0]?.async;)R.push(c.shift());if(!R.length)throw Error("batch must have at least one event");try{if(R[0].async){let M=Yl(i._state);await h(this,F,eu).call(this,i,...R),i._state=M}else await h(this,F,tu).call(this,i,...R)}catch(M){if(!Ys(M))throw M;if(n(this,F,oe)&&console.debug("[blocks] caught in handler",M),i._latestRenderContent=void 0,P){i._state=P._state,i._changed=f,i._effects=P._effects;let Yt=b.map(ed=>{let td={...ed};return td.retry=!0,td});i.addToRequeueEvents(...Yt);break}else throw Ys(M)||console.error("[blocks] unhandled error in handler",M),M}n(this,F,oe)&&console.debug("[blocks] remaining events",i._requeueEvents);let H=[];for(let M of i._requeueEvents){if(!y&&!M.async){n(this,F,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch A",M),H.push(M);continue}if(y&&M.async&&!v){n(this,F,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch B",M),H.push(M);continue}n(this,F,oe)&&console.debug("[blocks] reprocessing event in BlocksHandler",M),c.push(M)}i._requeueEvents=H,c.length>0&&(f={...i._changed},P={_state:Yl(i._state),_effects:{...i._effects}},b=[...c])}if(y){i._latestRenderContent||(i._latestRenderContent=h(this,F,Ba).call(this,n(this,Ti),i.request.props??{},i));let R=i._latestRenderContent;R&&(o=n(this,Xr).createBlocksElementOrThrow(R),o=n(this,Xr).ensureRootBlock(o))}return{state:i._changedState,effects:i.effects,blocks:o,events:i._requeueEvents}}};Ti=new WeakMap,mo=new WeakMap,Xr=new WeakMap,F=new WeakSet,oe=function(){return!!this._latestRenderContext?.devvitContext.debug.blocks},uo=function(e,...t){e._hooks={},h(this,F,Ba).call(this,n(this,Ti),e.request.props??{},e)},eu=async function(e,...t){h(this,F,uo).call(this,e,...t),await Promise.all(t.map(async i=>{if(!i.async)throw new Error("You can't mix main and other queues in one batch. This is likely a platform bug. Please file an issue in the Discord for someone to help! https://discord.com/channels/1050224141732687912/1115441897079574620");await h(this,F,Ma).call(this,e,i)}))},Ma=async function(e,t){let i=e._hooks[t.hook];if(i?.onUIEvent)try{await i.onUIEvent(t,e)}catch(s){throw Ys(s)?n(this,F,oe)&&console.error("Server call required",s):console.error("Error in event handler",s),s}else await e.handleUndeliveredEvent(t)},tu=async function(e,...t){for(let i of t)n(this,F,oe)&&console.log("[blocks] handling main queue event",i),n(this,F,oe)&&console.log("[blocks] before",e._state),h(this,F,uo).call(this,e,i),await h(this,F,Ma).call(this,e,i),n(this,F,oe)&&console.log("[blocks] after",e._state);h(this,F,uo).call(this,e)},Ba=function(e,t,i){n(this,F,oe)&&console.debug("[blocks] renderRoot"),i._generated={},pe=i,this._latestRenderContext=i;try{let s=h(this,F,Ua).call(this,e,t,i);if(s.length!==1)throw new Error(`There can only be one root element, received: ${s.length}. Please wrap these elements in a <vstack></vstack> or <hstack></hstack> to continue. Fragments cannot be used as a root element.`);let o=s[0];if(o==="[object Promise]")throw new Error('Root elements cannot be async. To use data from an async endpoint, please use "const [data] = useState(async () => {/** your async code */})".');if(typeof o=="string")throw new Error("The root element must return a valid block, not a string. Try wrapping the element in a <text>your content</text> tag to continue.");return i._latestRenderContent=o,o}catch(s){if(s instanceof Mt)return;throw s}finally{pe=null}},Ua=function(e,t,i){i.push({namespace:e.name||"anonymous",...t});try{let s=e(t,i.devvitContext);if(s instanceof Promise)throw new Error(`Components (found: ${e.name??"unknown component"}) cannot be async. To use data from an async endpoint, please use "const [data] = useState(async () => {/** your async code */})".`);return h(this,F,Da).call(this,s,i)}finally{i.pop()}},co=function(e,t){return e=e.flat(1/0),e.flatMap((i,s)=>(i&&typeof i=="object"&&"props"in i&&(i.props?.key||(i.props=i.props??{},i.props.key=`${s}`)),h(this,F,Da).call(this,i,t)))},Da=function(e,t){if(Array.isArray(e))return h(this,F,co).call(this,e,t);if(Mp(e))if(e.type===void 0)try{return t.push({namespace:"fragment",...e.props}),h(this,F,co).call(this,e.children,t)}finally{t.pop()}else if(typeof e.type=="function"){let i={...e.props,children:e.children.flat(1/0)};return h(this,F,Ua).call(this,e.type,i,t)}else try{t.push({namespace:e.type,...e.props});let i=h(this,F,co).call(this,e.children,t),s=h(this,F,iu).call(this,e.props??{});return[{type:e.type,children:i,props:s}]}finally{t.pop()}else return[(e??"").toString()]},iu=function(e){let t={};for(let i in e)if(!(typeof e[i]>"u"))if(typeof e[i]=="function"){let s=me({namespace:i,key:!1,initializer:({hookId:o})=>({hookId:o,state:null,onUIEvent:d=>{if(d.userAction)return e[i](d.userAction.data);if(d.webView?.postMessage)return e[i](d.webView.postMessage.message)}})});t[i]=s.hookId,"captureHookRef"in e[i]&&e[i].captureHookRef()}else{let s=JSON.parse(JSON.stringify(e[i]));s!=null&&(t[i]=s)}return t};function Mp(r){return typeof r=="object"&&r!=null&&"type"in r}var ru=r=>{let e=Number(r.trim().split(".").pop());return isNaN(e)?void 0:e},nu=r=>{let[e,t,i]=r.trim().split(";");if(!e||!t||!i){console.warn(`Received a malformed devvit-user-agent! Received: '${r}'`);return}if(e!=="Reddit"){console.warn(`Received unknown company name in user agent! Received: '${r}'`);return}if(t==="iOS"){let s=ru(i);if(s===void 0){console.warn(`Could not parse version number from user agent! Received: '${r}'`);return}return{company:"Reddit",platform:"iOS",rawVersion:i,versionNumber:s}}if(t==="Android"){let s=ru(i);if(s===void 0){console.warn(`Could not parse version number from user agent! Received: '${r}'`);return}return{company:"Reddit",platform:"Android",rawVersion:i,versionNumber:s}}if(t==="Shreddit")return{company:"Reddit",platform:"Shreddit",rawVersion:i};if(t==="Play")return{company:"Reddit",platform:"Play",rawVersion:i};console.warn("Received unknown platform:",t)},su=r=>r?r.platform==="Android"?r.versionNumber<1875012:r.platform==="iOS"?r.versionNumber<614973:!1:(console.warn(`Could not parse devvit-user-agent! Received: '${JSON.stringify(r)}'`),!1),Bp=r=>{switch(r){case"Android":return"https://play.google.com/store/apps/details?id=com.reddit.frontpage";case"iOS":return"https://apps.apple.com/us/app/reddit/id1064216828";case"Play":case"Shreddit":break;default:console.error(`No upgrade link for platform: ${r}`)}},Up=({platform:r},e)=>u.createElement("blocks",null,u.createElement("vstack",{alignment:"middle center",height:100,width:100},u.createElement("vstack",{maxWidth:"300px",gap:"large",alignment:"middle center"},u.createElement("vstack",{gap:"medium",alignment:"middle center"},u.createElement("image",{imageHeight:100,imageWidth:100,url:"https://i.redd.it/p1vmc5ulmpib1.png"}),u.createElement("text",{size:"large",weight:"bold",wrap:!0,alignment:"center"},"Uh oh, the app you're trying to use requires the latest version of Reddit. Please upgrade your app to continue.")),u.createElement("hstack",{alignment:"middle center"},u.createElement("button",{onPress:()=>{let t=Bp(r);t?e.ui.navigateTo(t):console.warn("No upgrade link found for platform:",r)}},"Upgrade"))))),ou=r=>()=>u.createElement(Up,{platform:r});var Dp=()=>u.createElement("vstack",{alignment:"center middle",width:"100%",height:"100%"},u.createElement("text",null,"This feature is not available yet")),Np=[[po,po.methods.renderPostContent,(r,e)=>u.customPostType?.render(e)??null],[po,po.methods.renderPostComposer,(r,e)=>u.createElement(Dp,null)]];function Lp(r){return async(e,t)=>{let i=nu(t["devvit-user-agent"]?.values?.[0]??"");if(i&&su(i)){let o=new Ut(ou(i.platform));return au.fromJSON(await o.handle(e,t))}let s=new Ut(r);return au.fromJSON(await s.handle(e,t))}}function du(r){for(let[e,t,i]of Np)r.provides(e),O(t.name,Lp(i))}var Ri,Qr,Oi,Dt,Nt,Mi,Bi,Lt,dt,Yr,en,_t,j,U=class U extends Ns{static configure(e){a(this,Oi,{...n(this,Oi),...e}),Le(e.http)&&this.use(k.HTTPDefinition),(e.redis===void 0||Le(e.kvStore)||Le(e.redis))&&(this.use(k.KVStoreDefinition),this.use(k.RedisAPIDefinition)),Le(e.media)&&this.use(k.MediaServiceDefinition),Le(e.modLog)&&this.use(k.ModlogDefinition),Le(e.redditAPI)&&(this.use(k.FlairDefinition),this.use(k.GraphQLDefinition),this.use(k.LinksAndCommentsDefinition),this.use(k.ListingsDefinition),this.use(k.ModerationDefinition),this.use(k.ModNoteDefinition),this.use(k.NewModmailDefinition),this.use(k.PrivateMessagesDefinition),this.use(k.SubredditsDefinition),this.use(k.UsersDefinition),this.use(k.WidgetsDefinition),this.use(k.WikiDefinition)),Le(e.realtime)&&this.use(k.RealtimeDefinition)}static addMenuItem(e){n(this,Bi).push(e)}static addCustomPostType(e){a(this,Dt,e)}static createForm(e,t){let i=`form.${n(this,Nt).size}`;return n(this,Nt).set(i,{form:e,onSubmit:t}),i}static addSchedulerJob(e){if(n(this,j)[k.SchedulerDefinition.fullName]||this.use(k.SchedulerDefinition),n(this,Lt).has(e.name))throw new Error(`Job ${e.name} is already defined`);n(this,Lt).set(e.name,e.onRun)}static addSettings(e){xt(e);let t=e.filter(s=>s.type==="group"||!s.scope||s.scope==="installation"),i=e.filter(s=>s.type!=="group"&&s.scope==="app");t.length>0&&a(this,Mi,t),i.length>0&&a(this,Ri,i),n(this,j)[k.SettingsDefinition.fullName]||this.use(k.SettingsDefinition)}static addTrigger(e){if("events"in e){for(let t of e.events)this.addTrigger({event:t,onEvent:(i,s)=>e.onEvent(i,s)});return this}return n(this,dt).has(e.event)?n(this,dt).get(e.event)?.push(e.onEvent):n(this,dt).set(e.event,[e.onEvent]),U}static provide(e){n(this,en).push(e)}static use(e,t){n(this,_t)[e.fullName]={def:e,options:t??{},handler:void 0};let i={};for(let s of Object.values(e.methods))i[s.name]=(o,d)=>n(this,_t)[e.fullName].handler?.[s.name]?.(s.requestType?.fromPartial(o??{}),d);return n(this,j)[e.fullName]=i,i}static get redditAPIPlugins(){if(!Le(n(this,Oi).redditAPI))throw new Error("Reddit API is not enabled. You can enable it by passing `redditAPI: true` to `Devvit.configure`.");return{Flair:n(this,j)[k.FlairDefinition.fullName],GraphQL:n(this,j)[k.GraphQLDefinition.fullName],LinksAndComments:n(this,j)[k.LinksAndCommentsDefinition.fullName],Listings:n(this,j)[k.ListingsDefinition.fullName],Moderation:n(this,j)[k.ModerationDefinition.fullName],ModNote:n(this,j)[k.ModNoteDefinition.fullName],NewModmail:n(this,j)[k.NewModmailDefinition.fullName],PrivateMessages:n(this,j)[k.PrivateMessagesDefinition.fullName],Subreddits:n(this,j)[k.SubredditsDefinition.fullName],Users:n(this,j)[k.UsersDefinition.fullName],Widgets:n(this,j)[k.WidgetsDefinition.fullName],Wiki:n(this,j)[k.WikiDefinition.fullName]}}static get modLogPlugin(){let e=n(this,j)[k.ModlogDefinition.fullName];if(!e)throw new Error("ModLog is not enabled. You can enable it by passing `modLog: true` to `Devvit.configure`");return e}static get schedulerPlugin(){let e=n(this,j)[k.SchedulerDefinition.fullName];if(!e)throw new Error("Scheduler is not enabled. You can enable it by calling `Devvit.addSchedulerJob` at the top level of your app.");return e}static get kvStorePlugin(){let e=n(this,j)[k.KVStoreDefinition.fullName];if(!e)throw new Error("Key Value Store is not enabled. You can enable it by passing `kvStore: true` to `Devvit.configure`");return e}static get redisPlugin(){let e=n(this,j)[k.RedisAPIDefinition.fullName];if(!e)throw new Error("Redis is not enabled. You can enable it by passing `redis: true` to `Devvit.configure`");return e}static get mediaPlugin(){let e=n(this,j)[k.MediaServiceDefinition.fullName];if(!e)throw new Error("MediaService is not enabled. You can enable it by passing `media: true` to `Devvit.configure`");return e}static get settingsPlugin(){let e=n(this,j)[k.SettingsDefinition.fullName];if(!e)throw new Error("Settings must first be configured with `Devvit.addSettings()` before they can be accessed");return e}static get realtimePlugin(){let e=n(this,j)[k.RealtimeDefinition.fullName];if(!e)throw new Error("Realtime is not enabled. You can enable it by passing `realtime: true` to `Devvit.configure`");return e}static get menuItems(){return n(this,Bi)}static get customPostType(){return n(this,Dt)}static get formDefinitions(){return n(this,Nt)}static get scheduledJobHandlers(){return n(this,Lt)}static get installationSettings(){return n(this,Mi)}static get appSettings(){return n(this,Ri)}static get triggerOnEventHandlers(){return n(this,dt)}static get assets(){return n(this,Qr)}static get webViewAssets(){return n(this,Yr)}constructor(e){super(e),a(U,Qr,e.assets??{}),a(U,Yr,e.webviewAssets??{});for(let t in n(U,_t)){let i=n(U,_t)[t];i.handler=e.use(i.def,i.options)}n(U,Bi).length>0&&gl(e),n(U,Lt).size>0&&hl(e),n(U,Dt)&&(dl(e),du(e)),(n(U,Dt)||n(U,Nt).size>0)&&Bl(e),n(U,Mi)&&ll(e),n(U,Ri)&&Wd(e),n(U,dt).size>0&&fl(e);for(let t of n(U,en))e.provides(t)}};Ri=new WeakMap,Qr=new WeakMap,Oi=new WeakMap,Dt=new WeakMap,Nt=new WeakMap,Mi=new WeakMap,Bi=new WeakMap,Lt=new WeakMap,dt=new WeakMap,Yr=new WeakMap,en=new WeakMap,_t=new WeakMap,j=new WeakMap,U.debug={},l(U,Ri),l(U,Qr,{}),l(U,Oi,{}),l(U,Dt),l(U,Nt,new Map),l(U,Mi),l(U,Bi,[]),l(U,Lt,new Map),l(U,dt,new Map),l(U,Yr,{}),l(U,en,[]),l(U,_t,{}),l(U,j,{});var u=U;(e=>{function r(t,i,...s){return{type:t,props:i,children:s}}e.createElement=r})(u||(u={}));var Ht={APP:0,USER:1};function Z(r){let e=Object.getOwnPropertyDescriptors(r.constructor.prototype);for(let[t,i]of Object.entries(e))i.get&&Object.defineProperty(r,t,{...i,enumerable:!0})}var Na;(function(r){r[r.bold=1]="bold",r[r.italic=2]="italic",r[r.underline=4]="underline",r[r.strikethrough=8]="strikethrough",r[r.subscript=16]="subscript",r[r.superscript=32]="superscript",r[r.monospace=64]="monospace"})(Na||(Na={}));var lu="text",uu="raw",cu="br",mu="link",pu="c/",gu="p/",hu="r/",fu="u/",yu="@",bu="spoilertext",vu="par",ku="h",Cu="hr",Pu="blockquote",Su="code",wu="li",Fu="list",xu="L",Iu="R",Au="C",Eu="table",Tu="embed",Ru="img",Ou="gif",Mu="video";function Bu(r){return{e:Ou,id:r.mediaId,...r.caption&&{c:r.caption},...r.blur&&{o:r.blur}}}function Uu(r,e){let t={},i=[];return Object.assign(t,tn(t,i),rn(t,i),nn(t,i),an(t,i),dn(t,i),ln(t,i)),e(t),{e:Pu,c:i,...r.author&&{a:r.author}}}function Du(r,e){let t={},i=[];return Object.assign(t,_a(t,i)),e(t),{e:Su,c:i,...r.language&&{l:r.language}}}function Nu(r){return{e:pu,t:r.permalink}}function Lu(r,e){let t={},i=[];return Object.assign(t,_a(t,i),on(t,i)),e(t),{e:ku,l:r.level,c:i}}function _u(r){return{e:Tu,u:r.sourceUrl,c:r.contentUrl,x:r.width,y:r.height}}function Hu(){return{e:Cu}}function ju(r){return{e:Ru,id:r.mediaId,...r.caption&&{c:r.caption},...r.blur&&{o:r.blur}}}function Vu(){return{e:cu}}function Wu(r){return{e:mu,t:r.text,u:r.url,...r.formatting&&{f:r.formatting},...r.tooltip&&{a:r.tooltip}}}function Gu(r,e){let t={},i=[];return Object.assign(t,oc(t,i)),e(t),{e:Fu,o:r.ordered,c:i}}function Ju(r){let e={},t=[];return Object.assign(e,tn(e,t),rn(e,t),nn(e,t),go(e,t),an(e,t),dn(e,t),ln(e,t)),r(e),{e:wu,c:t}}function zu(r){let e={},t=[];return Object.assign(e,ho(e,t),on(e,t),La(e,t),Ha(e,t),sn(e,t)),r(e),{e:vu,c:t}}function qu(r){return{e:gu,t:r.permalink}}function $u(r){return{e:uu,t:r}}function Ku(r){let e={},t=[];return Object.assign(e,ho(e,t),on(e,t),La(e,t)),r(e),{e:bu,c:t}}function Zu(r){return{e:hu,t:r.subredditName,l:r.showPrefix}}function Xu(r){let e={},t=[],i=[];return Object.assign(e,ac(e,t,i)),r(e),{e:Eu,h:t,c:i}}function Qu(r){let[e,t]=sc();return r(e),{c:t}}function Yu(r,e){let[t,i]=sc();e(t);let s;switch(r.columnAlignment){case"left":s=xu;break;case"right":s=Iu;break;case"center":s=Au;break}return{...s&&{a:s},...i&&{c:i}}}function ec(r){let e={},t=[];return Object.assign(e,dc(e,t)),r(e),t}function tc(r){return{e:lu,t:r.text,...r.formatting&&{f:r.formatting}}}function ic(r){return{e:fu,t:r.username,l:r.showPrefix}}function rc(r){return{e:yu,t:r.username,l:r.showPrefix}}function nc(r){return{e:Mu,id:r.mediaId,...r.caption&&{c:r.caption},...r.blur&&{o:r.blur},...r.thumbnail&&{p:r.thumbnail},...r.convertToGif&&{gifify:r.convertToGif}}}function sc(){let r={},e=[];return Object.assign(r,ho(r,e),on(r,e),Ha(r,e),sn(r,e)),[r,e]}function tn(r,e){return{blockQuote(t,i){return e.push(Uu(t,i)),r}}}function rn(r,e){return{codeBlock(t,i){return e.push(Du(t,i)),r}}}function lc(r,e){return{embed(t){return e.push(_u(t)),r}}}function nn(r,e){return{heading(t,i){return e.push(Lu(t,i)),r}}}function go(r,e){return{horizontalRule(){return e.push(Hu()),r}}}function sn(r,e){return{image(t){return e.push(ju(t)),r},animatedImage(t){return e.push(Bu(t)),r}}}function La(r,e){return{linebreak(){return e.push(Vu()),r}}}function on(r,e){return{link(t){return e.push(Wu(t)),r},commentLink(t){return e.push(Nu(t)),r},postLink(t){return e.push(qu(t)),r},subredditLink(t){return e.push(Zu(t)),r},userLink(t){return e.push(ic(t)),r},userMention(t){return e.push(rc(t)),r}}}function an(r,e){return{list(t,i){return e.push(Gu(t,i)),r}}}function oc(r,e){return{item(t){return e.push(Ju(t)),r}}}function dn(r,e){return{paragraph(t){return e.push(zu(t)),r}}}function _a(r,e){return{rawText(t){return e.push($u(t)),r}}}function Ha(r,e){return{spoiler(t){return e.push(Ku(t)),r}}}function ac(r,e,t){return{headerCell(i,s){return e.push(Yu(i,s)),r},row(i){return t.push(ec(i)),r}}}function ln(r,e){return{table(t){return e.push(Xu(t)),r}}}function dc(r,e){return{cell(t){return e.push(Qu(t)),r}}}function ho(r,e){return{text(t){return e.push(tc(t)),r}}}function uc(r,e){return{video(t){return e.push(nc(t)),r}}}var _p=function(r,e,t,i,s){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},Hp=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},fo,jt=class{constructor(){fo.set(this,void 0);let e=[];Object.assign(this,dn(this,e),nn(this,e),go(this,e),tn(this,e),rn(this,e),lc(this,e),an(this,e),ln(this,e),sn(this,e),uc(this,e)),_p(this,fo,{document:e},"f")}build(){return JSON.stringify(Hp(this,fo,"f"))}paragraph(e){return this}heading(e,t){return this}horizontalRule(){return this}blockQuote(e,t){return this}codeBlock(e,t){return this}embed(e){return this}list(e,t){return this}table(e){return this}image(e){return this}animatedImage(e){return this}video(e){return this}};fo=new WeakMap;function Ui(r){let e;return r instanceof jt?e=r.build():typeof r=="object"?e=JSON.stringify(r):e=r,e}var cc=100,mc=1/0,Vt,Wt,lt,Di,Ni,yo,V=class{constructor(e){l(this,Ni);l(this,Vt);l(this,Wt);l(this,lt);l(this,Di,!1);this.pageSize=cc;this.limit=mc;this.children=[];Z(this),this._fetch=e.fetch,this.pageSize=e.pageSize??cc,this.limit=e.limit??mc,a(this,Wt,e.after),a(this,Vt,e.before),a(this,lt,e.more),e.children&&(this.children=e.children)}get hasMore(){return!n(this,Di)||!!(n(this,Wt)||n(this,Vt)||n(this,lt))}async*[Symbol.asyncIterator](){let e=0;for(;;){if(e===this.children.length)if(this.hasMore){if((await h(this,Ni,yo).call(this)).length===0)break}else break;if(yield this.children[e],e++,e===this.limit)break}}setMore(e){a(this,lt,e)}preventInitialFetch(){a(this,Di,!0)}async all(){for(;this.hasMore&&this.children.length<this.limit;)await h(this,Ni,yo).call(this);return this.children.slice(0,this.limit)}async get(e){let t=e<=this.limit?e:this.limit;for(;this.hasMore&&this.children.length<t;)await h(this,Ni,yo).call(this);return this.children.slice(0,t)}};Vt=new WeakMap,Wt=new WeakMap,lt=new WeakMap,Di=new WeakMap,Ni=new WeakSet,yo=async function(){if(!this.hasMore)throw new Error("This listing does not have any more items to load.");let{children:e,before:t,after:i,more:s}=await this._fetch({before:n(this,Vt),after:n(this,Wt),limit:this.pageSize,more:n(this,lt)});return this.children.push(...e),a(this,Vt,t),a(this,Wt,i),a(this,lt,s),a(this,Di,!0),e};var un,ja,ve=class{constructor(){}static get(e,t){let i=u.redditAPIPlugins.ModNote;return new V({hasMore:!0,before:e.before,limit:e.limit,pageSize:e.limit,fetch:async s=>{let o=await i.GetNotes({subreddit:e.subreddit,user:e.user,filter:e.filter,before:s.before,limit:s.limit},t);return{children:o.modNotes?.map(d=>h(this,un,ja).call(this,d))||[],before:o.hasNextPage?o.endCursor:void 0,hasMore:o.hasNextPage}}})}static async delete(e,t){let i=u.redditAPIPlugins.ModNote,{deleted:s}=await i.DeleteNotes(e,t);return!!s}static async add(e,t){let s=await u.redditAPIPlugins.ModNote.PostNotes(e,t);if(!s?.created)throw new Error("Failed to create mod note");return h(this,un,ja).call(this,s.created)}static async addRemovalNote(e,t){await u.redditAPIPlugins.ModNote.PostRemovalNote(e,t)}};un=new WeakSet,ja=function(e){return p(e.id,"Mod note ID is null or undefined"),p(e.createdAt,"Mod note createdAt is null or undefined"),p(e.type,"Mod note type is null or undefined"),p(e.subreddit,"Mod note subreddit is null or undefined"),p(e.subredditId,"Mod note subredditId is null or undefined"),p(e.operator,"Mod note operator is null or undefined"),p(e.operatorId,"Mod note operatorId is null or undefined"),p(e.user,"Mod note user is null or undefined"),p(e.userId,"Mod note userId is null or undefined"),p(e.userNoteData,"Mod note userNote is null or undefined"),p(e.modActionData,"Mod note modAction is null or undefined"),{id:e.id,user:{id:te(e.userId??""),name:e.user},subreddit:{id:K(e.subredditId??""),name:e.subreddit},operator:{id:te(e.operatorId??""),name:e.operator},createdAt:new Date(e.createdAt*1e3),userNote:{note:e.userNoteData?.note,redditId:e.userNoteData?.redditId?fe(e.userNoteData?.redditId):void 0,label:e.userNoteData?.label},type:e.type}},l(ve,un);var Y=class{static queryWithQueryString(e,t){return u.redditAPIPlugins.GraphQL.Query({query:e},t)}static query(e,t,i,s){return u.redditAPIPlugins.GraphQL.PersistedQuery({operationName:e,id:t,variables:i},s)}};var pc=["all","wiki","posts","access","mail","config","flair","channels","chat_config","chat_operator","community_chat"];function jp(r,e){return e.map(t=>(r.includes(t)?"+":"-")+t).join(",")}function Va(r){return jp(r,pc)}function gc(r){return r.filter(e=>pc.includes(e))}import"@devvit/protos";var Vp=(t=>(t.User="USER_FLAIR",t.Post="LINK_FLAIR",t))(Vp||{}),Gt,Li,_i,Hi,ji,Vi,Wi,Gi,Ji,zi,qi,bo,xe=class xe{constructor(e,t,i){l(this,Gt);l(this,Li);l(this,_i);l(this,Hi);l(this,ji);l(this,Vi);l(this,Wi);l(this,Gi);l(this,Ji);l(this,zi);Z(this),p(e.id),p(e.text),a(this,Gt,e.id),a(this,Li,t),a(this,_i,e.text),a(this,Hi,Wp(e.textColor)),a(this,ji,Gp(e.backgroundColor)),a(this,Vi,Jp(e.allowableContent)),a(this,Wi,e.modOnly),a(this,Gi,e.maxEmojis),a(this,Ji,e.textEditable),a(this,zi,i)}get id(){return n(this,Gt)}get text(){return n(this,_i)}get textColor(){return n(this,Hi)}get backgroundColor(){return n(this,ji)}get allowableContent(){return n(this,Vi)}get modOnly(){return n(this,Wi)}get maxEmojis(){return n(this,Gi)}get allowUserEdits(){return n(this,Ji)}async delete(){return xe.deleteFlairTemplate(n(this,Gt),n(this,Li),n(this,zi))}async edit(e){return xe.editFlairTemplate({id:n(this,Gt),subredditName:n(this,Li),text:e.text??n(this,_i),allowableContent:e.allowableContent??n(this,Vi),backgroundColor:e.backgroundColor??n(this,ji),maxEmojis:e.maxEmojis??n(this,Gi),modOnly:e.modOnly??n(this,Wi),textColor:e.textColor??n(this,Hi),allowUserEdits:e.allowUserEdits??n(this,Ji)},n(this,zi))}static async createPostFlairTemplate(e,t){var i;return h(i=xe,qi,bo).call(i,{...e,flairType:"LINK_FLAIR"},t)}static async createUserFlairTemplate(e,t){var i;return h(i=xe,qi,bo).call(i,{...e,flairType:"USER_FLAIR"},t)}static async editFlairTemplate(e,t){var i;return h(i=xe,qi,bo).call(i,e,t)}static async getPostFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.LinkFlair({subreddit:e},t)).flair?.map(o=>new xe(o,e,t))||[]}static async getUserFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.UserFlair({subreddit:e},t)).flair?.map(o=>new xe(o,e,t))||[]}static async deleteFlairTemplate(e,t,i){await u.redditAPIPlugins.Flair.DeleteFlairTemplate({subreddit:e,flairTemplateId:t},i)}};Gt=new WeakMap,Li=new WeakMap,_i=new WeakMap,Hi=new WeakMap,ji=new WeakMap,Vi=new WeakMap,Wi=new WeakMap,Gi=new WeakMap,Ji=new WeakMap,zi=new WeakMap,qi=new WeakSet,bo=async function(e,t){let{subredditName:i,allowableContent:s="all",backgroundColor:o="transparent",flairType:d="",maxEmojis:c=10,modOnly:m=!1,text:y,textColor:v="dark",allowUserEdits:f=!1,id:P=""}=e;if(m&&f)throw new Error("Cannot have a mod only flair that is editable by users");let W=await u.redditAPIPlugins.Flair.FlairTemplate({subreddit:i,allowableContent:s,backgroundColor:o,flairType:d,maxEmojis:c,modOnly:m,text:y,textColor:v,textEditable:f,flairTemplateId:P,cssClass:"",overrideCss:!1},t);return new xe(W,i,t)},l(xe,qi);var ne=xe;function cn(r){return{flairCssClass:r.flairCssClass,user:r.user,flairText:r.flairText}}var Oe,Wa,hc,Ga,ut=class ut{static async getUserFlairBySubreddit(e,t){return u.redditAPIPlugins.Flair.FlairList(e,t)}static setUserFlair(e,t){var i;return h(i=ut,Oe,Wa).call(i,e,t)}static setUserFlairBatch(e,t,i){var s;return h(s=ut,Oe,hc).call(s,e,t,i)}static setPostFlair(e,t){var i;return h(i=ut,Oe,Wa).call(i,{...e,postId:de(e.postId)},t)}static async removePostFlair(e,t,i){var s;return h(s=ut,Oe,Ga).call(s,e,t,void 0,i)}static async removeUserFlair(e,t,i){var s;return h(s=ut,Oe,Ga).call(s,e,void 0,t,i)}};Oe=new WeakSet,Wa=async function(e,t){await u.redditAPIPlugins.Flair.SelectFlair({subreddit:e.subredditName,flairTemplateId:e.flairTemplateId??"",text:e.text??"",name:e.username,link:e.postId,backgroundColor:e.backgroundColor??"",textColor:e.textColor??"dark",cssClass:e.cssClass??"",returnRtjson:"none"},t)},hc=async function(e,t,i){if(!t.length)return[];if(t.length>100)throw new Error("Unexpected input: flairs array cannot be longer than 100 entries.");let o=",",d=t.map(y=>{for(let v in y)if(y[v]?.includes(o))throw new Error(`Unexpected input: ${v} cannot contain the "," character`);return[y.username,y.text||"",y.cssClass||""].join(o)}).join(`
|
|
4
|
-
`);return(await u.redditAPIPlugins.Flair.FlairCsv({subreddit:e,flairCsv:d},i)).result},Ga=async function(e,t,i,s){await u.redditAPIPlugins.Flair.SelectFlair({subreddit:e,name:i??"",link:t??"",flairTemplateId:"",backgroundColor:"",text:"",textColor:"",cssClass:"",returnRtjson:"none"},s)},l(ut,Oe);var ce=ut;function Wp(r){if(p(r,"Flair text color is required"),r==="light"||r==="dark")return r;throw new Error(`Invalid flair text color: ${r}`)}function Gp(r){if(!r||r.length===0||r==="transparent")return"transparent";if(/^#([A-Fa-f0-9]{6})$/.test(r))return r;throw new Error(`Invalid flair background color: ${r}`)}function Jp(r){if(r==="all"||r==="text"||r==="emoji")return r;throw new Error(`Invalid allowable content: ${r}`)}import"@devvit/protos";import{Block as vc,UIResponse as eg}from"@devvit/protos";var qa=nd(bc(),1);var za=r=>"text"in r?r.text:Yp(r.richtext),Yp=r=>r instanceof jt?r.build():typeof r=="object"?JSON.stringify(r):r;var tg={NONE:0,BLOCKS:1,UNRECOGNIZED:-1},$i,pn,Ki,gn,Zi,hn,fn,yn,zt,bn,vn,kn,Cn,Pn,Sn,ct,wn,Fn,qt,Xi,mt,Qi,Yi,er,pt,gt,ht,tr,ft,yt,bt,je,xn,In,ir,rr,B,D=class D{constructor(e,t){l(this,$i);l(this,pn);l(this,Ki);l(this,gn);l(this,Zi);l(this,hn);l(this,fn);l(this,yn);l(this,zt);l(this,bn);l(this,vn);l(this,kn);l(this,Cn);l(this,Pn);l(this,Sn);l(this,ct);l(this,wn);l(this,Fn);l(this,qt);l(this,Xi);l(this,mt);l(this,Qi);l(this,Yi);l(this,er);l(this,pt);l(this,gt);l(this,ht);l(this,tr);l(this,ft);l(this,yt);l(this,bt);l(this,je);l(this,xn);l(this,In);l(this,ir);l(this,rr);l(this,B);Z(this),p(e.id,"Post is missing id"),p(e.title,"Post is missing title"),p(e.createdUtc,"Post is missing created date"),p(e.author,"Post is missing author name"),p(e.subreddit,"Post is missing subreddit name"),p(e.subredditId,"Post is missing subreddit id"),p(e.url,"Post is missing url"),p(e.permalink,"Post is missing permalink"),a(this,$i,de(`t3_${e.id}`)),a(this,Ki,e.author),a(this,pn,e.authorFullname?te(e.authorFullname):void 0),a(this,Zi,K(e.subredditId)),a(this,hn,e.subreddit),a(this,kn,e.score??0),a(this,Cn,e.numComments??0),a(this,Pn,e.numReports??0);let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,gn,i),a(this,yn,e.title),a(this,zt,e.selftext),a(this,bn,e.selftextHtml),a(this,vn,e.url),a(this,fn,e.permalink),e.thumbnail&&e.thumbnail!=="self"&&e.thumbnail!=="nsfw"&&e.thumbnailHeight!=null&&e.thumbnailWidth!=null&&a(this,Sn,{url:e.thumbnail,height:e.thumbnailHeight,width:e.thumbnailWidth}),a(this,ct,e.approved??!1),a(this,wn,e.approvedAtUtc??0),a(this,Fn,e.bannedAtUtc??0),a(this,mt,e.removed??!1),a(this,Qi,e.removedBy),a(this,Yi,e.removedByCategory),a(this,qt,e.spam??!1),a(this,Xi,e.stickied??!1),a(this,er,e.archived??!1),a(this,pt,e.edited??!1),a(this,gt,e.locked??!1),a(this,ht,e.over18??!1),a(this,tr,e.quarantine??!1),a(this,ft,e.spoiler),a(this,yt,e.hidden??!1),a(this,bt,e.ignoreReports??!1),a(this,je,e.distinguished),a(this,In,e.secureMedia),a(this,ir,(e.modReports??[]).map(([s])=>s)),a(this,rr,(e.userReports??[]).map(([s])=>s)),a(this,B,t),(e.linkFlairBackgroundColor||e.linkFlairCssClass||e.linkFlairText||e.linkFlairType||e.linkFlairTemplateId||e.linkFlairRichtext||e.linkFlairTextColor)&&a(this,xn,{backgroundColor:e.linkFlairBackgroundColor,cssClass:e.linkFlairCssClass,text:e.linkFlairText,type:e.linkFlairType,templateId:e.linkFlairTemplateId,richtext:(e.linkFlairRichtext??[]).map(({e:s,t:o,a:d,u:c})=>({elementType:s,text:o,emojiRef:d,url:c})),textColor:e.linkFlairTextColor})}get id(){return n(this,$i)}get authorId(){return n(this,pn)}get authorName(){return n(this,Ki)}get subredditId(){return n(this,Zi)}get subredditName(){return n(this,hn)}get permalink(){return n(this,fn)}get title(){return n(this,yn)}get body(){return n(this,zt)}get bodyHtml(){return n(this,bn)}get url(){return n(this,vn)}get thumbnail(){return n(this,Sn)}get createdAt(){return n(this,gn)}get score(){return n(this,kn)}get numberOfComments(){return n(this,Cn)}get numberOfReports(){return n(this,Pn)}get approved(){return n(this,ct)}get approvedAtUtc(){return n(this,wn)}get bannedAtUtc(){return n(this,Fn)}get spam(){return n(this,qt)}get stickied(){return n(this,Xi)}get removed(){return n(this,mt)}get removedBy(){return n(this,Qi)}get removedByCategory(){return n(this,Yi)}get archived(){return n(this,er)}get edited(){return n(this,pt)}get locked(){return n(this,gt)}get nsfw(){return n(this,ht)}get quarantined(){return n(this,tr)}get spoiler(){return n(this,ft)}get hidden(){return n(this,yt)}get ignoringReports(){return n(this,bt)}get distinguishedBy(){return n(this,je)}get comments(){return Q.getComments({postId:this.id},n(this,B))}get flair(){return n(this,xn)}get secureMedia(){return n(this,In)}get userReportReasons(){return n(this,rr)}get modReportReasons(){return n(this,ir)}toJSON(){return{id:this.id,authorId:this.authorId,authorName:this.authorName,subredditId:this.subredditId,subredditName:this.subredditName,permalink:this.permalink,title:this.title,body:this.body,bodyHtml:this.bodyHtml,url:this.url,thumbnail:this.thumbnail,score:this.score,numberOfComments:this.numberOfComments,numberOfReports:this.numberOfReports,createdAt:this.createdAt,approved:this.approved,spam:this.spam,stickied:this.stickied,removed:this.removed,removedBy:n(this,Qi),removedByCategory:n(this,Yi),archived:this.archived,edited:this.edited,locked:this.locked,nsfw:this.nsfw,quarantined:this.quarantined,spoiler:this.spoiler,hidden:this.hidden,ignoringReports:this.ignoringReports,distinguishedBy:this.distinguishedBy,flair:this.flair,secureMedia:this.secureMedia,modReportReasons:n(this,ir),userReportReasons:n(this,rr)}}isApproved(){return n(this,ct)}isSpam(){return n(this,qt)}isStickied(){return n(this,Xi)}isRemoved(){return n(this,mt)}isArchived(){return n(this,er)}isEdited(){return n(this,pt)}isLocked(){return n(this,gt)}isNsfw(){return n(this,ht)}isQuarantined(){return n(this,tr)}isSpoiler(){return n(this,ft)}isHidden(){return n(this,yt)}isIgnoringReports(){return n(this,bt)}isDistinguishedBy(){return n(this,je)}async edit(e){let t=await D.edit({id:this.id,...e},n(this,B));a(this,zt,t.body),a(this,pt,t.edited)}async setSuggestedCommentSort(e){await D.setSuggestedCommentSort({id:this.id,subredditId:n(this,Zi),suggestedSort:e},n(this,B))}async setCustomPostPreview(e){await D.setCustomPostPreview({id:this.id,ui:e},n(this,B))}async setTextFallback(e){let t=await D.setTextFallback(e,this.id,n(this,B));a(this,zt,t.body),a(this,pt,t.edited)}async addComment(e){return Q.submit({id:this.id,...e},n(this,B))}async delete(){return D.delete(this.id,n(this,B))}async approve(){await D.approve(this.id,n(this,B)),a(this,ct,!0),a(this,mt,!1)}async remove(e=!1){await D.remove(this.id,e,n(this,B)),a(this,mt,!0),a(this,qt,e),a(this,ct,!1)}async lock(){await D.lock(this.id,n(this,B)),a(this,gt,!0)}async unlock(){await D.unlock(this.id,n(this,B)),a(this,gt,!1)}async hide(){await D.hide(this.id,n(this,B)),a(this,yt,!0)}async unhide(){await D.unhide(this.id,n(this,B)),a(this,yt,!1)}async markAsNsfw(){await D.markAsNsfw(this.id,n(this,B)),a(this,ht,!0)}async unmarkAsNsfw(){await D.unmarkAsNsfw(this.id,n(this,B)),a(this,ht,!1)}async markAsSpoiler(){await D.markAsSpoiler(this.id,n(this,B)),a(this,ft,!0)}async unmarkAsSpoiler(){await D.unmarkAsSpoiler(this.id,n(this,B)),a(this,ft,!1)}async sticky(e){await D.sticky(this.id,e,n(this,B))}async unsticky(){await D.unsticky(this.id,n(this,B))}async distinguish(){let{distinguishedBy:e}=await D.distinguish(this.id,!1,n(this,B));a(this,je,e)}async distinguishAsAdmin(){let{distinguishedBy:e}=await D.distinguish(this.id,!0,n(this,B));a(this,je,e)}async undistinguish(){let{distinguishedBy:e}=await D.undistinguish(this.id,n(this,B));a(this,je,e)}async ignoreReports(){await D.ignoreReports(this.id,n(this,B)),a(this,bt,!0)}async unignoreReports(){await D.unignoreReports(this.id,n(this,B)),a(this,bt,!1)}async getAuthor(){return C.getByUsername(n(this,Ki),n(this,B))}async crosspost(e){return D.crosspost({...e,postId:this.id},n(this,B))}addRemovalNote(e){return ve.addRemovalNote({itemIds:[n(this,$i)],...e},n(this,B))}async getEnrichedThumbnail(){return ig({id:this.id},n(this,B))}static async getById(e,t){let i=u.redditAPIPlugins.LinksAndComments,s=Ft(e)?e:`t3_${e}`,o=await i.Info({subreddits:[],thingIds:[s]},t);if(!o.data?.children?.length)throw new Error("could not find post");let d=o.data.children[0];if(!d?.data)throw new Error("could not find post");return new D(d.data,t)}static async submit(e,t){let i=u.redditAPIPlugins.LinksAndComments,s=Ht.APP,o;if("preview"in e){p(t,"Missing metadata in `SubmitPostOptions`");let m=await new Ne(()=>e.preview,void 0,{},t,void 0).buildBlocksUI(),y=vc.encode(m).finish(),{textFallback:v,...f}=e,P=v?za(v):"",b={kind:"custom",sr:e.subredditName,richtextJson:(0,qa.fromByteArray)(y),richtextFallback:P,runAs:s,...f};o=await i.SubmitCustomPost(b,t)}else o=await i.Submit({kind:"kind"in e?e.kind:"url"in e?"link":"self",sr:e.subredditName,richtextJson:"richtext"in e?Ui(e.richtext):void 0,runAs:s,...e},t);if("kind"in e&&["image","video","videogif"].includes(e.kind)&&!o.json?.data?.id){if(e.kind==="image"&&"imageUrls"in e)throw new Error(`Image post type with ${e.imageUrls} is being created asynchronously and should be updated in the subreddit soon.`);if("videoPosterUrl"in e)throw new Error(`Post of ${e.kind} type with ${e.videoPosterUrl} is being created asynchronously and should be updated in the subreddit soon.`)}if(!o.json?.data?.id||o.json?.errors?.length)throw new Error(`failed to submit post - either post ID is empty or request failed with errors: ${o.json?.errors}`);return D.getById(`t3_${o.json.data.id}`,t)}static async crosspost(e,t){let i=u.redditAPIPlugins.LinksAndComments,{postId:s,subredditName:o,...d}=e,c=await i.Submit({kind:"crosspost",sr:o,crosspostFullname:de(s),runAs:Ht.APP,...d},t);if(!c.json?.data?.id||c.json?.errors?.length)throw new Error("failed to crosspost post");return D.getById(`t3_${c.json.data.id}`,t)}static async edit(e,t){let i=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;if("richtext"in e&&(o=Ui(e.richtext)),(await i.EditUserText({thingId:s,text:"text"in e?e.text:"",richtextJson:o,runAs:Ht.APP},t)).json?.errors?.length)throw new Error("Failed to edit post");return D.getById(s,t)}static async setSuggestedCommentSort(e,t){if(!(await Y.query("SetSuggestedSort","cf6052acc7fefaa65b710625b81dba8041f258313aafe9730e2a3dc855e5d10d",{input:{subredditId:e.subredditId,postId:e.id,sort:e.suggestedSort}},t)).data?.setSuggestedSort?.ok)throw new Error("Failed to set suggested sort")}static async setCustomPostPreview(e,t){if(!t)throw new Error("Failed to set custom post preview. Metadata not found");let i=u.redditAPIPlugins.LinksAndComments,s=new Ut(e.ui),d=eg.fromJSON(await s.handle({events:[]},t)).blocks,c=(0,qa.fromByteArray)(vc.encode(d).finish());await i.SetCustomPostPreview({thingId:e.id,bodyType:tg.BLOCKS,blocksRenderContent:c},t)}static async setTextFallback(e,t,i){if(!("text"in e)&&!("richtext"in e))throw new Error(`No text fallback provided for post ${t}.`);let s=u.redditAPIPlugins.LinksAndComments,o=za(e);if((await s.EditCustomPost({thingId:t,richtextFallback:o},i)).json?.errors?.length)throw new Error("Failed to set post text fallback");return D.getById(t,i)}static async delete(e,t){await u.redditAPIPlugins.LinksAndComments.Del({id:e},t)}static async approve(e,t){await u.redditAPIPlugins.Moderation.Approve({id:e},t)}static async remove(e,t=!1,i){await u.redditAPIPlugins.Moderation.Remove({id:e,spam:t},i)}static async hide(e,t){await u.redditAPIPlugins.LinksAndComments.Hide({id:e},t)}static async unhide(e,t){await u.redditAPIPlugins.LinksAndComments.Unhide({id:e},t)}static async markAsNsfw(e,t){await u.redditAPIPlugins.LinksAndComments.MarkNSFW({id:e},t)}static async unmarkAsNsfw(e,t){await u.redditAPIPlugins.LinksAndComments.UnmarkNSFW({id:e},t)}static async markAsSpoiler(e,t){await u.redditAPIPlugins.LinksAndComments.Spoiler({id:e},t)}static async unmarkAsSpoiler(e,t){await u.redditAPIPlugins.LinksAndComments.Unspoiler({id:e},t)}static async sticky(e,t,i){await u.redditAPIPlugins.LinksAndComments.SetSubredditSticky({id:e,state:!0,num:t},i)}static async unsticky(e,t){await u.redditAPIPlugins.LinksAndComments.SetSubredditSticky({id:e,state:!1},t)}static async lock(e,t){await u.redditAPIPlugins.LinksAndComments.Lock({id:e},t)}static async unlock(e,t){await u.redditAPIPlugins.LinksAndComments.Unlock({id:e},t)}static async distinguish(e,t,i){let d=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:t?"admin":"yes",sticky:!1},i)).json?.data?.things?.[0]?.data;return p(d),{distinguishedBy:d.distinguished}}static async undistinguish(e,t){let o=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:"no",sticky:!1},t)).json?.data?.things?.[0]?.data;return p(o),{distinguishedBy:o.distinguished}}static async ignoreReports(e,t){await u.redditAPIPlugins.Moderation.IgnoreReports({id:e},t)}static async unignoreReports(e,t){await u.redditAPIPlugins.Moderation.UnignoreReports({id:e},t)}static getControversialPosts(e={},t){return this.getSortedPosts({...e,sort:"controversial"},t)}static getTopPosts(e={},t){return this.getSortedPosts({...e,sort:"top"},t)}static getSortedPosts(e,t){let i=u.redditAPIPlugins.Listings;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await i.Sort({show:"all",sort:e.sort,t:e.timeframe,subreddit:e.subredditName,...s},t);return mn(o,t)}})}static getHotPosts(e={location:"GLOBAL"},t){let i=u.redditAPIPlugins.Listings;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await i.Hot({g:e.location,show:"all",subreddit:e.subredditName,...s},t);return mn(o,t)}})}static getNewPosts(e,t){let i=u.redditAPIPlugins.Listings;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await i.New({show:"all",subreddit:e.subredditName,...s},t);return mn(o,t)}})}static getRisingPosts(e,t){let i=u.redditAPIPlugins.Listings;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await i.Rising({show:"all",subreddit:e.subredditName,...s},t);return mn(o,t)}})}static getPostsByUser(e,t){let i=u.redditAPIPlugins.Users;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(s){let o=await i.UserWhere({username:e.username,where:"submitted",...s},t);return mn(o,t)}})}};$i=new WeakMap,pn=new WeakMap,Ki=new WeakMap,gn=new WeakMap,Zi=new WeakMap,hn=new WeakMap,fn=new WeakMap,yn=new WeakMap,zt=new WeakMap,bn=new WeakMap,vn=new WeakMap,kn=new WeakMap,Cn=new WeakMap,Pn=new WeakMap,Sn=new WeakMap,ct=new WeakMap,wn=new WeakMap,Fn=new WeakMap,qt=new WeakMap,Xi=new WeakMap,mt=new WeakMap,Qi=new WeakMap,Yi=new WeakMap,er=new WeakMap,pt=new WeakMap,gt=new WeakMap,ht=new WeakMap,tr=new WeakMap,ft=new WeakMap,yt=new WeakMap,bt=new WeakMap,je=new WeakMap,xn=new WeakMap,In=new WeakMap,ir=new WeakMap,rr=new WeakMap,B=new WeakMap;var G=D;function mn(r,e){if(!r.data?.children)throw new Error("Listing response is missing children");return{children:r.data.children.map(i=>new G(i.data,e)),before:r.data.before,after:r.data.after}}async function ig(r,e){let o=(await Y.query("GetThumbnailV2","81580ce4e23d748c5a59a1618489b559bf4518b6a73af41f345d8d074c8b2ce9",{id:r.id},e)).data?.postInfoById?.thumbnailV2;if(o){if(!o.image)return}else throw new Error("Failed to get thumbnail");return{attribution:o.attribution,image:{url:o.image.url,width:o.image.dimensions.width,height:o.image.dimensions.height},isObfuscatedDefault:o.isObfuscatedDefault,...o.obfuscatedImage&&{obfuscatedImage:{url:o.obfuscatedImage.url,width:o.obfuscatedImage.dimensions.width,height:o.obfuscatedImage.dimensions.height}}}}var rg=(L=>(L.Custom="CUSTOM",L.Reddit="REDDIT",L.Instagram="INSTAGRAM",L.Twitter="TWITTER",L.Tiktok="TIKTOK",L.Twitch="TWITCH",L.Facebook="FACEBOOK",L.Youtube="YOUTUBE",L.Tumblr="TUMBLR",L.Spotify="SPOTIFY",L.Soundcloud="SOUNDCLOUD",L.Beacons="BEACONS",L.Linktree="LINKTREE",L.Discord="DISCORD",L.Venmo="VENMO",L.CashApp="CASH_APP",L.Patreon="PATREON",L.Kofi="KOFI",L.Paypal="PAYPAL",L.Cameo="CAMEO",L.Onlyfans="ONLYFANS",L.Substack="SUBSTACK",L.Kickstarter="KICKSTARTER",L.Indiegogo="INDIEGOGO",L.BuyMeACoffee="BUY_ME_A_COFFEE",L.Shopify="SHOPIFY",L))(rg||{}),An,nr,En,Tn,Rn,On,Mn,vt,Bn,Un,Dn,Be,$t=class $t{constructor(e,t){l(this,An);l(this,nr);l(this,En);l(this,Tn);l(this,Rn);l(this,On);l(this,Mn);l(this,vt,new Map);l(this,Bn);l(this,Un);l(this,Dn);l(this,Be);Z(this),p(e.id,"User ID is missing or undefined"),p(e.name,"Username is missing or undefined"),p(e.createdUtc,"User is missing created date"),a(this,An,te(Ds(e.id)?e.id:`t2_${e.id}`)),a(this,nr,e.name),a(this,On,e.over18??!1),a(this,Mn,e.isEmployee??!1);let i=new Date(0);if(i.setUTCSeconds(e.createdUtc),a(this,En,i),a(this,Tn,e.linkKarma??0),a(this,Rn,e.commentKarma??0),e.modPermissions)for(let[s,o]of Object.entries(e.modPermissions))n(this,vt).set(s,gc(o));a(this,Bn,new URL(e.subreddit?.url??"","https://www.reddit.com").toString()),a(this,Un,e.subreddit?.url??""),a(this,Dn,e.hasVerifiedEmail??!1),a(this,Be,t)}get id(){return n(this,An)}get username(){return n(this,nr)}get createdAt(){return n(this,En)}get linkKarma(){return n(this,Tn)}get commentKarma(){return n(this,Rn)}get nsfw(){return n(this,On)}get isAdmin(){return n(this,Mn)}get modPermissions(){return n(this,vt)}get url(){return n(this,Bn)}get permalink(){return n(this,Un)}get hasVerifiedEmail(){return n(this,Dn)}toJSON(){return{id:this.id,username:this.username,createdAt:this.createdAt,linkKarma:this.linkKarma,commentKarma:this.commentKarma,nsfw:this.nsfw,modPermissionsBySubreddit:Object.fromEntries(this.modPermissions)}}async getModPermissionsForSubreddit(e){if(n(this,vt).has(e))return n(this,vt).get(e);let t=await $t.getSubredditUsersByType({subredditName:e,type:"moderators",username:this.username},n(this,Be)).all();if(t.length===0)return[];let i=t[0].modPermissions.get(e)??[];return i.length>0&&n(this,vt).set(e,i),i}getComments(e){return Q.getCommentsByUser({username:this.username,...e},n(this,Be))}getPosts(e){return G.getPostsByUser({username:this.username,...e},n(this,Be))}async getUserFlairBySubreddit(e){let t=await ce.getUserFlairBySubreddit({subreddit:e,name:n(this,nr)},n(this,Be));return t.users[0]?cn(t.users[0]):void 0}getSnoovatarUrl(){return $t.getSnoovatarUrl(this.username,n(this,Be))}async getSocialLinks(){let i=await Y.query("GetUserSocialLinks","2aca18ef5f4fc75fb91cdaace3e9aeeae2cb3843b5c26ad511e6f01b8521593a",{name:this.username},n(this,Be));return i.data?.user?.profile?.socialLinks?i.data.user.profile.socialLinks.map(s=>({...s,handle:s.handle??void 0})):[]}static async getById(e,t){let i=await kc(e,t);return i==null?void 0:$t.getByUsername(i,t)}static async getByUsername(e,t){let i=u.redditAPIPlugins.Users;try{let s=await i.UserAbout({username:e},t);if(s.data?.id)return new $t(s.data,t)}catch(s){if(s instanceof Error&&s.message.includes("404 Not Found"))return;throw s}}static async getFromMetadata(e,t){p(t);let i=t?.[e]?.values[0];return i?$t.getById(te(i),t):Promise.resolve(void 0)}static getSubredditUsersByType(e,t){let i=u.redditAPIPlugins.Subreddits;return new V({hasMore:!0,pageSize:e.pageSize,limit:e.limit,after:e.after,before:e.before,fetch:async s=>{let o=await i.AboutWhere({where:e.type,user:e.username,subreddit:e.subredditName,show:"all",...s},t);return sg(o,e.subredditName,t)}})}static async createRelationship(e,t){let i=u.redditAPIPlugins.Users,{type:s,subredditName:o,username:d,permissions:c,...m}=e,y=await i.Friend({type:s,subreddit:o,name:d,permissions:c?Va(c):void 0,...m},t);if(y.json?.errors?.length)throw new Error(y.json.errors.join(`
|
|
5
|
-
`))}static async removeRelationship(e,t){await u.redditAPIPlugins.Users.Unfriend({type:e.type,subreddit:e.subredditName,name:e.username},t)}static async setModeratorPermissions(e,t,
|
|
6
|
-
`))}static async getSnoovatarUrl(e,t){return(await Y.query("GetSnoovatarUrlByName","c47fd42345af268616d2d8904b56856acdc05cf61d3650380f539ad7d596ac0c",{username:e},t)).data?.redditorInfoByName?.snoovatarIcon?.url}static getOverview(e,t){let i=u.redditAPIPlugins.Users;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(s){let o=await i.UserWhere({username:e.username,where:"overview",...s},t);return ng(o,t)}})}};An=new WeakMap,nr=new WeakMap,En=new WeakMap,Tn=new WeakMap,Rn=new WeakMap,On=new WeakMap,Mn=new WeakMap,vt=new WeakMap,Bn=new WeakMap,Un=new WeakMap,Dn=new WeakMap,Be=new WeakMap;var C=$t;function ng(r,e){if(!r.data?.children)throw new Error("Listing response is missing children");return{children:r.data.children.map(i=>{if(i.kind==="t3")return new G(i.data,e);if(i.kind==="t1")return new Q(i.data,e);throw new Error(`Type ${i.kind} is not supported`)}),before:r.data.before,after:r.data.after}}async function sg(r,e,t){let i=u.redditAPIPlugins.Users;if(!r.data?.children)throw new Error("Listing response is missing children");let s=r.data.children.map(v=>(p(v.data?.id,"User id is still from listing data"),v.data.id)),o=100,d=[];for(let v=0;v<s.length;v+=o)d.push(s.slice(v,v+o));let m=(await Promise.all(d.map(v=>i.UserDataByAccountIds({ids:v.join(",")},t)))).reduce((v,f)=>({...v,...f.users}),{});return{children:r.data.children.map(v=>{let f=v.data?.id;p(f,"User id is missing from listing");let P=m[f];return p(P,"User data is missing from response"),new C({id:f,name:P.name,linkKarma:P.linkKarma,commentKarma:P.commentKarma,createdUtc:P.createdUtc,over18:P.profileOver18,snoovatarSize:[],modPermissions:{[e]:v.data?.modPermissions??[]}},t)}),before:r.data.before,after:r.data.after}}async function kc(r,e){return(await u.redditAPIPlugins.Users.UserDataByAccountIds({ids:r},e))?.users?.[r]?.name}async function Td(r){p(r);let e=r?.[S.Username]?.values[0];if(e)return e;let t=r?.[S.User]?.values[0];if(t)return kc(t,r)}var Kt,Nn,sr,or,Ln,_n,ar,Hn,jn,dr,kt,Vn,Wn,Zt,Ct,Pt,Ve,Xt,We,Gn,Jn,zn,qn,$n,Kn,Zn,St,X,Ue,ko,Co,_=class _{constructor(e,t){l(this,Kt);l(this,Nn);l(this,sr);l(this,or);l(this,Ln);l(this,_n);l(this,ar);l(this,Hn);l(this,jn);l(this,dr);l(this,kt);l(this,Vn);l(this,Wn);l(this,Zt);l(this,Ct);l(this,Pt);l(this,Ve);l(this,Xt);l(this,We);l(this,Gn);l(this,Jn);l(this,zn);l(this,qn);l(this,$n);l(this,Kn);l(this,Zn);l(this,St);l(this,X);var s;Z(this),p(e.id,"Comment id is null or undefined"),p(e.body,"Comment body is null or undefined"),p(e.createdUtc,"Comment is missing created date"),p(e.author,"Comment author is null or undefined"),p(e.parentId,"Comment parentId is null or undefined"),p(e.linkId,"Comment linkId is null or undefined"),p(e.permalink,"Comment permalink is null or undefined"),p(e.subreddit,"Comment is missing subreddit name"),p(e.subredditId,"Comment is missing subreddit id"),a(this,Kt,ti(`t1_${e.id}`)),a(this,Nn,e.authorFullname?te(e.authorFullname):void 0),a(this,sr,e.author),a(this,or,e.body),a(this,Hn,K(e.subredditId)),a(this,jn,e.subreddit),a(this,_n,Lo(e.parentId)?ti(e.parentId):de(e.parentId)),a(this,ar,de(e.linkId)),a(this,Zt,e.edited??!1),a(this,Ct,e.locked??!1),a(this,Pt,e.removed??!1),a(this,Ve,e.stickied??!1),a(this,kt,e.approved??!1),a(this,Vn,e.approvedAtUtc??0),a(this,Wn,e.bannedAtUtc??0),a(this,Xt,e.spam??!1),a(this,We,e.distinguished),a(this,Gn,e.numReports??0),a(this,Jn,e.collapsedBecauseCrowdControl??!1),a(this,zn,e.score??0),a(this,qn,e.permalink),a(this,Zn,new URL(e.permalink??"","https://www.reddit.com/").toString()),a(this,St,e.ignoreReports??!1),a(this,$n,(e.modReports??[]).map(([o])=>o)),a(this,Kn,(e.userReports??[]).map(([o])=>o));let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,Ln,i),a(this,dr,h(s=_,Ue,ko).call(s,{postId:n(this,ar),commentId:n(this,Kt)},t)),a(this,X,t)}get id(){return n(this,Kt)}get authorId(){return n(this,Nn)}get authorName(){return n(this,sr)}get subredditId(){return n(this,Hn)}get subredditName(){return n(this,jn)}get body(){return n(this,or)}get createdAt(){return n(this,Ln)}get parentId(){return n(this,_n)}get postId(){return n(this,ar)}get replies(){return n(this,dr)}get distinguishedBy(){return n(this,We)}get locked(){return n(this,Ct)}get stickied(){return n(this,Ve)}get removed(){return n(this,Pt)}get approved(){return n(this,kt)}get approvedAtUtc(){return n(this,Vn)}get bannedAtUtc(){return n(this,Wn)}get spam(){return n(this,Xt)}get edited(){return n(this,Zt)}get numReports(){return n(this,Gn)}get collapsedBecauseCrowdControl(){return n(this,Jn)}get score(){return n(this,zn)}get permalink(){return n(this,qn)}get userReportReasons(){return n(this,Kn)}get modReportReasons(){return n(this,$n)}get url(){return n(this,Zn)}get ignoringReports(){return n(this,St)}toJSON(){return{id:this.id,authorName:this.authorName,subredditId:this.subredditId,subredditName:this.subredditName,body:this.body,createdAt:this.createdAt,parentId:this.parentId,postId:this.postId,replies:this.replies,approved:this.approved,locked:this.locked,removed:this.removed,stickied:this.stickied,spam:this.spam,edited:this.edited,distinguishedBy:this.distinguishedBy,numReports:this.numReports,collapsedBecauseCrowdControl:this.collapsedBecauseCrowdControl,score:this.score,permalink:this.permalink,modReportReasons:this.modReportReasons,userReportReasons:this.userReportReasons,url:this.url,ignoringReports:this.ignoringReports}}isLocked(){return n(this,Ct)}isApproved(){return n(this,kt)}isRemoved(){return n(this,Pt)}isSpam(){return n(this,Xt)}isStickied(){return n(this,Ve)}isDistinguished(){return!!n(this,We)}isEdited(){return n(this,Zt)}isIgnoringReports(){return n(this,St)}async delete(){return _.delete(this.id,n(this,X))}async edit(e){let t=await _.edit({id:this.id,...e},n(this,X));return a(this,or,t.body),a(this,Zt,t.edited),this}async approve(){await _.approve(this.id,n(this,X)),a(this,kt,!0),a(this,Pt,!1)}async remove(e=!1){await _.remove(this.id,e,n(this,X)),a(this,Pt,!0),a(this,Xt,e),a(this,kt,!1)}async lock(){await _.lock(this.id,n(this,X)),a(this,Ct,!0)}async unlock(){await _.unlock(this.id,n(this,X)),a(this,Ct,!1)}async reply(e){return _.submit({id:this.id,...e},n(this,X))}async getAuthor(){return C.getByUsername(n(this,sr),n(this,X))}async distinguish(e=!1){let{distinguishedBy:t,stickied:i}=await _.distinguish(this.id,e,!1,n(this,X));a(this,We,t),a(this,Ve,i)}async distinguishAsAdmin(e=!1){let{distinguishedBy:t,stickied:i}=await _.distinguish(this.id,e,!0,n(this,X));a(this,We,t),a(this,Ve,i)}async undistinguish(){let{distinguishedBy:e,stickied:t}=await _.undistinguish(this.id,n(this,X));a(this,We,e),a(this,Ve,t)}async ignoreReports(){await _.ignoreReports(this.id,n(this,X)),a(this,St,!0)}async unignoreReports(){await _.unignoreReports(this.id,n(this,X)),a(this,St,!1)}addRemovalNote(e){return ve.addRemovalNote({itemIds:[n(this,Kt)],...e},n(this,X))}static async getById(e,t){let i=u.redditAPIPlugins.LinksAndComments,s=Ge(e)?e:`t1_${e}`,o=await i.Info({subreddits:[],thingIds:[s]},t);if(!o.data?.children?.[0]?.data)throw new Error("not found");return new _(o.data.children[0].data,t)}static getComments(e,t){var d;let{postId:i,commentId:s,...o}=e;return h(d=_,Ue,ko).call(d,{postId:de(i),commentId:s?ti(s):void 0,...o},t)}static async edit(e,t){let i=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;"richtext"in e&&(o=Ui(e.richtext));let d=await i.EditUserText({thingId:s,text:"text"in e?e.text:"",richtextJson:o,runAs:Ht.APP},t);if(d.json?.errors?.length)throw new Error("Failed to edit comment");let c=d.json?.data?.things?.[0]?.data;return p(c),new _(c,t)}static async delete(e,t){await u.redditAPIPlugins.LinksAndComments.Del({id:e},t)}static async approve(e,t){await u.redditAPIPlugins.Moderation.Approve({id:e},t)}static async remove(e,t=!1,i){await u.redditAPIPlugins.Moderation.Remove({id:e,spam:t},i)}static async lock(e,t){await u.redditAPIPlugins.LinksAndComments.Lock({id:e},t)}static async unlock(e,t){await u.redditAPIPlugins.LinksAndComments.Unlock({id:e},t)}static async submit(e,t){let i=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;"richtext"in e&&(o=Ui(e.richtext));let d=await i.Comment({thingId:s,text:"text"in e?e.text:"",richtextJson:o,runAs:Ht.APP},t);if(d.json?.errors?.length)throw new Error("failed to reply to comment");let c=d.json?.data?.things?.[0]?.data;return p(c),new _(c,t)}static async distinguish(e,t,i,s){let c=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:i?"admin":"yes",sticky:t},s)).json?.data?.things?.[0]?.data;return p(c),{distinguishedBy:c.distinguished,stickied:!!c.stickied}}static async undistinguish(e,t){let o=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:"no",sticky:!1},t)).json?.data?.things?.[0]?.data;return p(o),{distinguishedBy:o.distinguished,stickied:!!o.stickied}}static getCommentsByUser(e,t){let i=u.redditAPIPlugins.Users;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(s){let o=await i.UserWhere({username:e.username,where:"comments",...s},t);return p(o.data,"Failed to get comments for user"),{children:o.data.children?.map(c=>new _(c.data,t))||[],before:o.data.before,after:o.data.after}}})}static async ignoreReports(e,t){await u.redditAPIPlugins.Moderation.IgnoreReports({id:e},t)}static async unignoreReports(e,t){await u.redditAPIPlugins.Moderation.UnignoreReports({id:e},t)}};Kt=new WeakMap,Nn=new WeakMap,sr=new WeakMap,or=new WeakMap,Ln=new WeakMap,_n=new WeakMap,ar=new WeakMap,Hn=new WeakMap,jn=new WeakMap,dr=new WeakMap,kt=new WeakMap,Vn=new WeakMap,Wn=new WeakMap,Zt=new WeakMap,Ct=new WeakMap,Pt=new WeakMap,Ve=new WeakMap,Xt=new WeakMap,We=new WeakMap,Gn=new WeakMap,Jn=new WeakMap,zn=new WeakMap,qn=new WeakMap,$n=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,St=new WeakMap,X=new WeakMap,Ue=new WeakSet,ko=function(e,t,i=0){return new V({limit:e.limit,pageSize:e.pageSize,fetch:async s=>{var P,b;let o=s.limit,d=u.redditAPIPlugins.Listings,c=u.redditAPIPlugins.LinksAndComments,m=e.commentId;if(s.more)if(s.more.children.length){let W=s.more;(!o||o>100)&&(o=100);let R=W.children.splice(0,o),H=await c.MoreChildren({linkId:e.postId,children:R,sort:e.sort},t);if(!H.json?.data?.things?.length)return{children:[]};let{children:M}=h(P=_,Ue,Co).call(P,H.json.data.things,e.postId,e,t);return{children:M,more:W.children.length?W:void 0}}else m=s.more.parentId,i=i+s.more.depth;let v=(await d.Comments({article:e.postId.substring(3),comment:m?.substring(3),limit:o,depth:e.depth,sort:e.sort},t)).listings?.[1]?.data?.children??[],f=v[0];return m&&f?.data?.replyList?.data&&(v=f.data.replyList.data.children),h(b=_,Ue,Co).call(b,v,m??e.postId,e,t,i)}})},Co=function(e,t,i,s,o=0){var y,v;let d=[],c,m={};for(let f of e){if(!f.data||(f.data.depth!=null&&(f.data.depth=f.data.depth+o),f.data.depth!=null&&i.depth!=null&&f.data.depth>=i.depth))continue;let P=f.data.parentId?m[f.data.parentId]:void 0;if(f.kind==="t1"){if(f.data.name===t)continue;let b=new _(f.data,s);if(m[b.id]=b,a(b,dr,h(y=_,Ue,ko).call(y,{...i,postId:b.postId,commentId:b.id},s,o)),"replyList"in f.data&&f.data.replyList?.data){let{children:W,more:R}=h(v=_,Ue,Co).call(v,f.data.replyList.data.children,b.id,i,s,o);W.length&&b.replies.children.push(...W),R&&b.replies.setMore(R)}b.replies.preventInitialFetch(),P?P.replies.children.push(b):d.push(b)}else if(f.kind==="more"&&f.data.parentId&&f.data.depth!=null){let b={parentId:Lo(f.data.parentId)?ti(f.data.parentId):de(f.data.parentId),children:f.data.children??[],depth:f.data.depth};P?P.replies.setMore(b):b.parentId===t&&(c=b)}}return{children:d,more:c}},l(_,Ue);var Q=_;function Hs(r,e){let t=u.redditAPIPlugins.Moderation;return new V({hasMore:!0,after:r.after,before:r.before,limit:r.limit,pageSize:r.pageSize,fetch:async i=>{let s=await t.AboutLog({subreddit:r.subredditName,mod:r.moderatorUsernames?r.moderatorUsernames.join(","):void 0,type:r.type,...i},e);return og(s)}})}function og(r){if(!r.data?.children)throw new Error("AboutLogResponse is missing children");return{children:r.data.children.map(t=>{if(!t.data)throw new Error("ModAction from AboutLogResponse is missing or invalid");let{id:i,mod:s,modId36:o,createdUtc:d,subreddit:c,subredditNamePrefixed:m,action:y,srId36:v,description:f,details:P,targetAuthor:b,targetBody:W,targetFullname:R,targetPermalink:H,targetTitle:M}=t.data;p(i,"ModAction from AboutLogResponse is missing id"),p(s,"ModAction from AboutLogResponse is missing mod"),p(o,"ModAction from AboutLogResponse is missing modId36"),p(d,"ModAction from AboutLogResponse is missing createdUtc"),p(c,"ModAction from AboutLogResponse is missing subreddit"),p(m,"ModAction from AboutLogResponse is missing subredditNamePrefixed"),p(y,"ModAction from AboutLogResponse is missing action"),p(v,"ModAction from AboutLogResponse is missing srId36");let Yt=new Date(0);return Yt.setUTCSeconds(d),{id:i,type:y,moderatorName:s,moderatorId:`t2_${o}`,createdAt:Yt,subredditName:c,subredditId:`t5_${v}`,description:f,details:P,target:R?{id:R,author:b,body:W,permalink:H,title:M}:void 0}}),after:r.data.after,before:r.data.before}}import"@devvit/protos";var ag=(d=>(d.New="New",d.InProgress="InProgress",d.Archived="Archived",d.Appeals="Appeals",d.JoinRequests="JoinRequests",d.Filtered="Filtered",d))(ag||{}),dg={0:"New",1:"InProgress",2:"Archived",3:"Appeals",4:"JoinRequests",5:"Filtered"},lg=(b=>(b.Highlighted="Highlighted",b.Unhighlighted="Unhighlighted",b.Archived="Archived",b.Unarchived="Unarchived",b.ReportedToAdmins="ReportedToAdmins",b.Muted="Muted",b.Unmuted="Unmuted",b.Banned="Banned",b.Unbanned="Unbanned",b.Approved="Approved",b.Disapproved="Disapproved",b.Filtered="Filtered",b.Unfiltered="Unfiltered",b))(lg||{}),ug={0:"Highlighted",1:"Unhighlighted",2:"Archived",3:"Unarchived",4:"ReportedToAdmins",5:"Muted",6:"Unmuted",7:"Banned",8:"Unbanned",9:"Approved",10:"Disapproved",11:"Filtered",12:"Unfiltered"},N,J,re,Cc,Pc,js=class{constructor(e){l(this,J);l(this,N);this.notificationSubjectPrefix="[notification]";a(this,N,e)}async bulkReadConversations(e,t){let i=u.redditAPIPlugins.NewModmail,{conversationIds:s}=await i.BulkReadConversations({entity:e.join(","),state:t},n(this,N));return s}async getConversations(e){let i=await u.redditAPIPlugins.NewModmail.GetConversations({after:e.after,entity:e.subreddits?e.subreddits.join(","):void 0,limit:e.limit,sort:e.sort,state:e.state},n(this,N)),s={};for(let o in i.conversations)s[o]=h(this,J,re).call(this,{protoConversation:i.conversations[o],protoMessages:i.messages,protoModActions:{}});return{conversations:s,viewerId:i.viewerId,conversationIds:i.conversationIds}}async getConversation(e){let i=await u.redditAPIPlugins.NewModmail.GetConversation({...e,markRead:!!e.markRead},n(this,N));return{participantSubreddit:i.participantSubreddit,conversation:h(this,J,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async getSubreddits(){let e=u.redditAPIPlugins.NewModmail,{subreddits:t}=await e.Subreddits({},n(this,N));return t}async createConversation(e){let i=await u.redditAPIPlugins.NewModmail.CreateConversation({body:e.body,isAuthorHidden:e.isAuthorHidden??!1,srName:e.subredditName,subject:e.subject,to:e.to?e.to:void 0},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async createModDiscussionConversation(e){return $a({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:K(e.subredditId),isInternal:!0,participantType:"MODERATOR",conversationType:"INTERNAL"},n(this,N))}async createModInboxConversation(e){return $a({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:K(e.subredditId),isInternal:!1,participantType:"PARTICIPANT_USER",conversationType:"SR_USER"},n(this,N))}async createModNotification(e){let t=e.subject;return e.subject.startsWith(this.notificationSubjectPrefix)||(t=`${this.notificationSubjectPrefix} ${e.subject}`),$a({subject:t,bodyMarkdown:e.bodyMarkdown,subredditId:K(e.subredditId),isInternal:!1,participantType:"PARTICIPANT_USER",conversationType:"SR_USER"},n(this,N))}async reply(e){let i=await u.redditAPIPlugins.NewModmail.CreateConversationMessage({body:e.body,conversationId:e.conversationId,isAuthorHidden:e.isAuthorHidden??!1,isInternal:e.isInternal??!1},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:{}}),user:i.user}}async highlightConversation(e){let i=await u.redditAPIPlugins.NewModmail.HighlightConversation({conversationId:e},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions})}}async unhighlightConversation(e){let i=await u.redditAPIPlugins.NewModmail.UnhighlightConversation({conversationId:e},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions})}}async archiveConversation(e){let i=await u.redditAPIPlugins.NewModmail.ArchiveConversation({conversationId:e},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions})}}async unarchiveConversation(e){let i=await u.redditAPIPlugins.NewModmail.UnarchiveConversation({conversationId:e},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions})}}async muteConversation(e){let i=await u.redditAPIPlugins.NewModmail.MuteConversation({conversationId:e.conversationId,numHours:e.numHours},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async unmuteConversation(e){let i=await u.redditAPIPlugins.NewModmail.UnmuteConversation({conversationId:e},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async readConversations(e){await u.redditAPIPlugins.NewModmail.Read({conversationIds:e.join(",")},n(this,N))}async unreadConversations(e){await u.redditAPIPlugins.NewModmail.Unread({conversationIds:e.join(",")},n(this,N))}async approveConversation(e){let i=await u.redditAPIPlugins.NewModmail.ApproveConversation({conversationId:e},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async disapproveConversation(e){let i=await u.redditAPIPlugins.NewModmail.DisapproveConversation({conversationId:e},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async tempBanConversation(e){let i=await u.redditAPIPlugins.NewModmail.TempBan({...e},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async unbanConversation(e){let i=await u.redditAPIPlugins.NewModmail.Unban({conversationId:e},n(this,N));return{conversation:h(this,J,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async getUnreadCount(){return await u.redditAPIPlugins.NewModmail.UnreadCount({},n(this,N))}async getUserConversations(e){return await u.redditAPIPlugins.NewModmail.UserConversations({conversationId:e},n(this,N))}};N=new WeakMap,J=new WeakSet,re=function({protoConversation:e,protoMessages:t,protoModActions:i}){return{...e,state:dg[e.state],messages:h(this,J,Cc).call(this,e,t),modActions:h(this,J,Pc).call(this,e,i)}},Cc=function(e,t){let i={},s=e.objIds.filter(o=>o.key==="messages").map(({id:o})=>o);for(let o of s){let d=t[o];d&&(i[o]=d)}return i},Pc=function(e,t){let i={},s=e.objIds.filter(o=>o.key==="modActions").map(({id:o})=>o);for(let o of s){let d=t[o];d&&(i[o]={...d,actionType:ug[d.actionTypeId]})}return i};async function $a(r,e){let t=e[S.AppUser]?.values[0],o=await Y.query("CreateModmailConversation","5f9ae20b0c7bdffcafb80241728a72e67cd4239bc09f67284b79d4aa706ee0e5",{subject:r.subject,bodyMarkdown:r.bodyMarkdown,subredditId:r.subredditId,authorId:t,isInternal:r.isInternal,participantType:r.participantType,conversationType:r.conversationType},e);if(o.data?.createModmailConversationV2?.ok)return o.data?.createModmailConversationV2?.conversationId;throw new Error("modmail conversation creation failed; ${response.data?.createModmailConversationV2?.errors[0].message}")}var lr,ur,Xn,Qn,Yn,es,Ka=class Ka{constructor(e,t){l(this,lr);l(this,ur);l(this,Xn);l(this,Qn);l(this,Yn);l(this,es);if(Z(this),p(e.id,"PrivateMessage: Invalid data, no id"),p(e.name,"PrivateMessage: Invalid data, no name"),p(e.created,"PrivateMessage: Invalid data, no created date"),a(this,lr,fe(e.name)),e.author!=null)a(this,ur,{type:"user",username:e.author,id:e.authorFullname?te(e.authorFullname):void 0});else if(e.subreddit!=null)a(this,ur,{type:"subreddit",name:e.subreddit,id:e.subredditId?K(e.subredditId):void 0});else throw new Error("PrivateMessage: Invalid data, no author or subreddit");a(this,Xn,e.body??""),a(this,Qn,e.bodyHtml??"");let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,Yn,i),a(this,es,t)}static async getMessages(e,t){let i=u.redditAPIPlugins.PrivateMessages;return new V({...e,fetch:async s=>{let o=await i.MessageWhere({...s,where:e.type??"inbox"},t);return{after:o.data?.after,before:o.data?.before,children:o.data?.children?.map(d=>new Ka(d.data,t)).filter(Boolean)||[]}}})}static async send({to:e,subject:t,text:i},s){await u.redditAPIPlugins.PrivateMessages.Compose({to:e,subject:t,text:i,fromSr:""},s)}static async sendAsSubreddit({to:e,fromSubredditName:t,subject:i,text:s},o){await u.redditAPIPlugins.PrivateMessages.Compose({to:e,fromSr:t,subject:i,text:s},o)}static async markAllAsRead(e){await u.redditAPIPlugins.PrivateMessages.ReadAllMessages({filterTypes:""},e)}get id(){return n(this,lr)}get from(){return n(this,ur)}get body(){return n(this,Xn)}get bodyHtml(){return n(this,Qn)}get created(){return n(this,Yn)}async markAsRead(){await u.redditAPIPlugins.PrivateMessages.ReadMessage({id:n(this,lr)},n(this,es))}};lr=new WeakMap,ur=new WeakMap,Xn=new WeakMap,Qn=new WeakMap,Yn=new WeakMap,es=new WeakMap;var It=Ka;var Rd=(o=>(o.Reports="reports",o.Spam="spam",o.Modqueue="modqueue",o.Unmoderated="unmoderated",o.Edited="edited",o))(Rd||{}),Sc=class{},wc=class{},Fc=class{},xc=class{},cr,x,ts,is,rs,ns,ss,os,as,ds,ls,mr,T,Ie=class Ie{constructor(e,t){l(this,cr);l(this,x);l(this,ts);l(this,is);l(this,rs);l(this,ns);l(this,ss);l(this,os);l(this,as);l(this,ds);l(this,ls);l(this,mr);l(this,T);Z(this),p(e.id,"Subreddit id is missing or undefined"),p(e.displayName,"Subreddit name is missing or undefined"),a(this,cr,K(`t5_${e.id}`)),a(this,x,e.displayName),p(e.createdUtc,"Subreddit is missing created date");let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,ts,i),a(this,is,cg(e.subredditType)),a(this,rs,e.title),a(this,ns,e.description),p(e.lang,"Subreddit is missing language"),a(this,ss,e.lang),a(this,os,e.subscribers??0),a(this,as,e.activeUserCount??0),a(this,ds,e.over18??!1),a(this,mr,e.url??""),a(this,ls,{acceptFollowers:e.acceptFollowers??!1,allOriginalContent:e.allOriginalContent??!1,allowChatPostCreation:e.allowChatPostCreation??!1,allowDiscovery:e.allowDiscovery??!1,allowGalleries:e.allowGalleries??!1,allowImages:e.allowImages??!1,allowPolls:e.allowPolls??!1,allowPredictionContributors:e.allowPredictionContributors??!1,allowPredictions:e.allowPredictions??!1,allowPredictionsTournament:e.allowPredictionsTournament??!1,allowTalks:e.allowTalks??!1,allowVideoGifs:e.allowVideogifs??!1,allowVideos:e.allowVideos??!1,chatPostEnabled:e.isChatPostFeatureEnabled??!1,collectionsEnabled:e.collectionsEnabled??!1,crosspostable:e.isCrosspostableSubreddit??!1,emojisEnabled:e.emojisEnabled??!1,eventPostsEnabled:e.eventPostsEnabled??!1,linkFlairEnabled:e.linkFlairEnabled??!1,originalContentTagEnabled:e.originalContentTagEnabled??!1,restrictCommenting:e.restrictCommenting??!1,restrictPosting:e.restrictPosting??!1,shouldArchivePosts:e.shouldArchivePosts??!1,spoilersEnabled:e.spoilersEnabled??!1,wikiEnabled:e.wikiEnabled??!1,allowedPostType:mg(e.submissionType),allowedMediaInComments:(e.allowedMediaInComments??[]).map(pg),bannerBackgroundColor:e.bannerBackgroundColor,bannerBackgroundImage:e.bannerBackgroundImage,bannerImage:e.bannerImg,communityIcon:e.communityIcon,headerTitle:e.headerTitle,keyColor:e.keyColor,mobileBannerImage:e.mobileBannerImage,primaryColor:e.primaryColor,userFlairs:{enabled:e.userFlairEnabledInSr??!1,usersCanAssign:e.canAssignUserFlair??!1,userFlairBackgroundColor:e.userFlairBackgroundColor,userFlairTextColor:e.userFlairTextColor},postFlairs:{enabled:e.linkFlairEnabled??!1,usersCanAssign:e.canAssignLinkFlair??!1},url:new URL(n(this,mr),"https://www.reddit.com").toString()}),a(this,T,t)}get id(){return n(this,cr)}get name(){return n(this,x)}get createdAt(){return n(this,ts)}get type(){return n(this,is)}get title(){return n(this,rs)}get description(){return n(this,ns)}get language(){return n(this,ss)}get numberOfSubscribers(){return n(this,os)}get numberOfActiveUsers(){return n(this,as)}get nsfw(){return n(this,ds)}get settings(){return n(this,ls)}get userFlairsEnabled(){return this.settings.userFlairs.enabled}get postFlairsEnabled(){return this.settings.postFlairs.enabled}get usersCanAssignUserFlairs(){return this.settings.userFlairs.usersCanAssign}get usersCanAssignPostFlairs(){return this.settings.postFlairs.usersCanAssign}get url(){return this.settings.url}get permalink(){return n(this,mr)}toJSON(){return{id:this.id,name:this.name,createdAt:this.createdAt,type:this.type,title:this.title,description:this.description,language:this.language,nsfw:this.nsfw,numberOfSubscribers:this.numberOfSubscribers,numberOfActiveUsers:this.numberOfActiveUsers,settings:this.settings}}async submitPost(e){let t={...e,subredditName:n(this,x)};return G.submit(t,n(this,T))}getControversialPosts(e={}){if(!n(this,x))throw new Error("subreddit missing displayName - it might not have been fetched");return G.getControversialPosts({...e,subredditName:n(this,x)},n(this,T))}getTopPosts(e={}){if(!n(this,x))throw new Error("subreddit missing displayName - it might not have been fetched");return G.getTopPosts({...e,subredditName:n(this,x)},n(this,T))}getApprovedUsers(e={}){return C.getSubredditUsersByType({type:"contributors",subredditName:n(this,x),...e},n(this,T))}approveUser(e){return C.createRelationship({username:e,subredditName:n(this,x),type:"contributor"},n(this,T))}removeUser(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"contributor"},n(this,T))}getWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikicontributors",subredditName:n(this,x),...e},n(this,T))}addWikiContributor(e){return C.createRelationship({username:e,subredditName:n(this,x),type:"wikicontributor"},n(this,T))}removeWikiContributor(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"wikicontributor"},n(this,T))}getBannedUsers(e={}){return C.getSubredditUsersByType({type:"banned",subredditName:n(this,x),...e},n(this,T))}banUser(e){return C.createRelationship({username:e.username,subredditName:n(this,x),type:"banned",banReason:e.reason,banMessage:e.message,note:e.note,duration:e.duration,banContext:e.context},n(this,T))}unbanUser(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"banned"},n(this,T))}getBannedWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikibanned",subredditName:n(this,x),...e},n(this,T))}banWikiContributor(e){return C.createRelationship({username:e.username,subredditName:n(this,x),type:"wikibanned",banReason:e.reason,note:e.note,duration:e.duration},n(this,T))}unbanWikiContributor(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"wikibanned"},n(this,T))}getModerators(e={}){return C.getSubredditUsersByType({type:"moderators",subredditName:n(this,x),...e},n(this,T))}inviteModerator(e,t){return C.createRelationship({type:"moderator_invite",subredditName:n(this,x),username:e,permissions:t??[]},n(this,T))}revokeModeratorInvite(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"moderator_invite"},n(this,T))}removeModerator(e){return C.removeRelationship({type:"moderator",subredditName:n(this,x),username:e},n(this,T))}setModeratorPermissions(e,t){return C.setModeratorPermissions(e,n(this,x),t,n(this,T))}getMutedUsers(e={}){return C.getSubredditUsersByType({type:"muted",subredditName:n(this,x),...e},n(this,T))}muteUser(e,t){return C.createRelationship({username:e,subredditName:n(this,x),type:"muted",note:t},n(this,T))}unmuteUser(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"muted"},n(this,T))}getModerationLog(e){return Hs({subredditName:n(this,x),...e},n(this,T))}getUserFlairTemplates(){return ne.getUserFlairTemplates(n(this,x),n(this,T))}getPostFlairTemplates(){return ne.getPostFlairTemplates(n(this,x),n(this,T))}createPostFlairTemplate(e){return ne.createPostFlairTemplate({subredditName:n(this,x),...e},n(this,T))}createUserFlairTemplate(e){return ne.createUserFlairTemplate({subredditName:n(this,x),...e},n(this,T))}async getUserFlair(e){if(e?.usernames!==void 0)return{users:await Promise.all(e.usernames.map(async i=>{let s=await ce.getUserFlairBySubreddit({subreddit:n(this,x),name:i},n(this,T));return cn(s.users[0])}))};{let t=await ce.getUserFlairBySubreddit({...e,subreddit:n(this,x)},n(this,T));return{next:t.next,prev:t.prev,users:t.users.map(i=>cn(i))}}}getModQueue(e={type:"all"}){return Ie.aboutLocation({...e,location:"modqueue",subreddit:n(this,x)},n(this,T))}getReports(e={type:"all"}){return Ie.aboutLocation({...e,location:"reports",subreddit:n(this,x)},n(this,T))}getSpam(e={type:"all"}){return Ie.aboutLocation({...e,location:"spam",subreddit:n(this,x)},n(this,T))}getUnmoderated(e={type:"all"}){return Ie.aboutLocation({...e,location:"unmoderated",subreddit:n(this,x)},n(this,T))}getEdited(e={type:"all"}){return Ie.aboutLocation({...e,location:"edited",subreddit:n(this,x)},n(this,T))}static aboutLocation(e,t){let i=u.redditAPIPlugins.Moderation,s;switch(e.type){case"post":s="links";break;case"comment":s="comments";break;default:s=void 0}return new V({...e,fetch:async o=>{let d=await i.AboutLocation({...o,...e,only:s},t);return Ic(d,t)}})}getCommentsAndPostsByIds(e){let t=u.redditAPIPlugins.LinksAndComments;return new V({fetch:async()=>{let i=await t.Info({thingIds:e,subreddits:[n(this,cr)]},n(this,T));return Ic(i,n(this,T))}})}static async addRemovalReason(e,t,i,s){return(await u.redditAPIPlugins.Subreddits.SubredditAddRemovalReason({title:t,message:i,subreddit:e},s)).id}static async getRemovalReasons(e,t){let s=await u.redditAPIPlugins.Subreddits.SubredditGetRemovalReasons({subreddit:e},t);return s.order.map(o=>({...s.data[o]}))}static async getFromMetadata(e){p(e);let t=e?.[S.SubredditName]?.values[0];if(t)return Ie.getByName(t,e);let i=e?.[S.Subreddit]?.values[0];return p(i),Ie.getById(K(i),e)}static async getById(e,t){let i=await Jo(e,t);if(i)return Ie.getByName(i,t)}static async getByName(e,t){let s=await u.redditAPIPlugins.Subreddits.SubredditAbout({subreddit:e},t);if(!s?.data)throw new Error("not found");return new Ie(s.data,t)}};cr=new WeakMap,x=new WeakMap,ts=new WeakMap,is=new WeakMap,rs=new WeakMap,ns=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,ds=new WeakMap,ls=new WeakMap,mr=new WeakMap,T=new WeakMap;var le=Ie;async function Od(r,e){let o=(await Y.query("GetSubredditInfoById","315a9b75c22a017d526afdf2d274616946156451aacfd56dfb91e7ad3f7a2fde",{id:r},e)).data?.subredditInfoById;if(!o)throw new Error("subreddit info not found");return o}async function Md(r,e){let o=(await Y.query("GetSubredditInfoByName","4aa69726c7e3f5d33ab2bee22b3d74fce645824fddd5ea3ec6dfe30bdb4295cb",{name:r},e)).data?.subredditInfoByName;if(!o)throw new Error("subreddit info not found");return o}async function Bd(r,e){let o=(await Y.query("GetSubredditLeaderboard","18ead70c46b6446d45ecd8b679b16d9a929a933d6ef25d8262a459cb18b72848",{id:r},e)).data?.subredditInfoById?.leaderboard;if(!o)throw new Error("subreddit leaderboard not found");if(!o.summary)throw new Error("subreddit leaderboard summary not found");return{id:o.id,summary:o.summary}}async function Ud(r,e){let o=(await Y.query("GetSubredditStyles","d491d17ea8858f563ea578b26b9595d64adecf4bf34557d567c7e53c470f5f22",{id:r},e)).data?.subredditInfoById?.styles;if(!o)throw new Error("subreddit styles not found");return o}function cg(r){if(r==="public"||r==="private"||r==="restricted"||r==="employees_only"||r==="gold_only"||r==="gold_restricted"||r==="archived"||r==="user")return r;throw new Error(`invalid subreddit type: ${r}`)}function mg(r){if(r==="any"||r==="link"||r==="self")return r;throw new Error(`invalid allowed post type: ${r}`)}function pg(r){if(r==="animated"||r==="giphy"||r==="static"||r==="expression")return r;throw new Error(`invalid comment media type: ${r}`)}function Ic(r,e){let i=(r.data?.children??[]).map(d=>{let c=s(d);if(c!=null)return c;let m=o(d);return m??null}).filter(Boolean);return{after:r.data?.after,before:r.data?.before,children:i};function s(d){try{return new G(d.data,e)}catch{return null}}function o(d){try{return new Q(d.data,e)}catch{return null}}}async function Jo(r,e){return(await u.redditAPIPlugins.LinksAndComments.Info({thingIds:[r],subreddits:[]},e)).data?.children[0]?.data?.displayName}async function Dd(r,e){return Ac("GetVaultContactByAddress","3e2f7966a5c120e64fd2795d06a46595c52d988185be98d3ed71c3f81ae80d2e",{provider:"ethereum",address:r},e)}async function Nd(r,e){return Ac("GetVaultContactByUserId","a854ddc19d0e22c4f36ed917fdbd568f299f3571427e393aee5e2972080fffe9",{provider:"ethereum",userId:r},e)}async function Ac(r,e,t,i){let o=(await Y.query(r,e,t,i))?.data?.vault?.contact;return{provider:o?.provider,userId:te(o?.userId),address:o?.address,createdAt:o?.createdAt,isActive:o?.isActive}}import{CommunityListWidget_CommunityData as gg,GetWidgetsResponse_WidgetItem as ae}from"@devvit/protos";var us,cs,ms,ps,Xa=class Xa{constructor(e,t,i){l(this,us);l(this,cs);l(this,ms);l(this,ps);Z(this),a(this,us,e.id),a(this,cs,e.shortName),a(this,ms,t),a(this,ps,i)}get id(){return n(this,us)}get name(){return n(this,cs)}get subredditName(){return n(this,ms)}toJSON(){return{id:this.id,name:this.name,subredditName:this.subredditName}}delete(){return Xa.delete(this.subredditName,this.id,n(this,ps))}static async getWidgets(e,t){let s=await u.redditAPIPlugins.Widgets.GetWidgets({subreddit:e},t);p(s.layout,"Failed to load widgets for subreddit");let o=s.items,d=[];for(let c of s.layout.sidebar?.order??[]){let m=o[c];switch(m?.kind){case"image":d.push(new Po(m,e,t));break;case"calendar":d.push(new So(m,e,t));break;case"textarea":d.push(new wo(m,e,t));break;case"button":d.push(new Fo(m,e,t));break;case"community-list":d.push(new xo(m,e,t));break;case"post-flair":d.push(new Io(m,e,t));break;case"custom":d.push(new Ao(m,e,t));break;case"subreddit-rules":{let y=await u.redditAPIPlugins.Subreddits.SubredditAboutRules({subreddit:e},t);d.push(new Za(y,m,e,t));break}default:throw new Error(`Unknown widget type: ${m.kind}`)}}return d}static async delete(e,t,i){await u.redditAPIPlugins.Widgets.DeleteWidget({subreddit:e,id:t},i)}static async reorder(e,t,i){await u.redditAPIPlugins.Widgets.OrderWidgets({subreddit:e,order:t},i)}static async add(e,t){switch(e?.type){case"image":return Po.create(e,t);case"calendar":return So.create(e,t);case"textarea":return wo.create(e,t);case"button":return Fo.create(e,t);case"community-list":return xo.create(e,t);case"post-flair":return Io.create(e,t);case"custom":return Ao.create(e,t);default:throw new Error("Unknown widget type")}}};us=new WeakMap,cs=new WeakMap,ms=new WeakMap,ps=new WeakMap;var ie=Xa,gs,Eo=class Eo extends ie{constructor(t,i,s){super(t,i,s);l(this,gs);a(this,gs,t.data.map(o=>(p(o.url,"Image widget data is missing url"),p(o.height,"Image widget data is missing height"),p(o.width,"Image widget data is missing width"),p(o.linkUrl,"Image widget data is missing linkUrl"),{url:o.url,height:o.height,width:o.width,linkUrl:o.linkUrl})))}get images(){return n(this,gs)}toJSON(){return{...super.toJSON(),images:this.images}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddImageWidget(t,i);return new Eo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateImageWidget(t,i);return new Eo(ae.fromJSON(o),t.subreddit,i)}};gs=new WeakMap;var Po=Eo,hs,fs,ys,To=class To extends ie{constructor(t,i,s){super(t,i,s);l(this,hs);l(this,fs);l(this,ys);p(t.googleCalendarId,"Calendar widget data is missing googleCalendarId"),p(t.configuration,"Calendar widget data is missing configuration"),p(t.styles,"Calendar widget data is missing styles"),a(this,hs,t.googleCalendarId),a(this,fs,t.configuration),a(this,ys,t.styles)}get googleCalendarId(){return n(this,hs)}get configuration(){return n(this,fs)}get styles(){return n(this,ys)}toJSON(){return{...super.toJSON(),googleCalendarId:this.googleCalendarId,configuration:this.configuration,styles:this.styles}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddCalendarWidget(t,i);return new To(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateCalendarWidget(t,i);return new To(ae.fromJSON(o),t.subreddit,i)}};hs=new WeakMap,fs=new WeakMap,ys=new WeakMap;var So=To,bs,vs,Ro=class Ro extends ie{constructor(t,i,s){super(t,i,s);l(this,bs);l(this,vs);p(t.text,"Textarea widget data is missing text"),p(t.styles,"Textarea widget data is missing styles"),a(this,bs,t.text),a(this,vs,t.styles)}get text(){return n(this,bs)}get styles(){return n(this,vs)}toJSON(){return{...super.toJSON(),text:this.text,styles:this.styles}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddTextAreaWidget(t,i);return new Ro(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateTextAreaWidget(t,i);return new Ro(ae.fromJSON(o),t.subreddit,i)}};bs=new WeakMap,vs=new WeakMap;var wo=Ro,ks,Cs,Ps,Oo=class Oo extends ie{constructor(t,i,s){super(t,i,s);l(this,ks);l(this,Cs);l(this,Ps);p(t.styles,"Button widget data is missing styles"),a(this,ks,t.buttons),a(this,Cs,t.description??""),a(this,Ps,t.styles)}get buttons(){return n(this,ks)}get description(){return n(this,Cs)}get styles(){return n(this,Ps)}toJSON(){return{...super.toJSON(),buttons:this.buttons,description:this.description,styles:this.styles}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddButtonWidget(t,i);return new Oo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateButtonWidget(t,i);return new Oo(ae.fromJSON(o),t.subreddit,i)}};ks=new WeakMap,Cs=new WeakMap,Ps=new WeakMap;var Fo=Oo,Ss,ws,Mo=class Mo extends ie{constructor(t,i,s){super(t,i,s);l(this,Ss);l(this,ws);a(this,Ss,t.data.map(o=>gg.fromJSON(o))),p(t.styles,"Community list widget data is missing styles"),a(this,ws,t.styles)}get communities(){return n(this,Ss)}get styles(){return n(this,ws)}toJSON(){return{...super.toJSON(),communities:this.communities,styles:this.styles}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddCommunityListWidget(t,i);return new Mo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateCommunityListWidget(t,i);return new Mo(ae.fromJSON(o),t.subreddit,i)}};Ss=new WeakMap,ws=new WeakMap;var xo=Mo,Fs,xs,Is,Bo=class Bo extends ie{constructor(t,i,s){super(t,i,s);l(this,Fs);l(this,xs);l(this,Is);if(p(t.styles,"Post flair widget data is missing styles"),a(this,Fs,t.styles),a(this,xs,t.order.map(o=>t.templates[o])),!(t.display&&t.display==="list"||t.display==="cloud"))throw new Error("Post flair widget data is missing display type");a(this,Is,t.display)}get styles(){return n(this,Fs)}get templates(){return n(this,xs)}get display(){return n(this,Is)}toJSON(){return{...super.toJSON(),styles:this.styles,templates:this.templates,display:this.display}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddPostFlairWidget(t,i);return new Bo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdatePostFlairWidget(t,i);return new Bo(ae.fromJSON(o),t.subreddit,i)}};Fs=new WeakMap,xs=new WeakMap,Is=new WeakMap;var Io=Bo,As,Es,Ts,Rs,Os,Uo=class Uo extends ie{constructor(t,i,s){super(t,i,s);l(this,As);l(this,Es);l(this,Ts);l(this,Rs);l(this,Os);p(t.stylesheetUrl,"Custom widget data is missing stylesheetUrl"),p(t.height,"Custom widget data is missing height"),p(t.css,"Custom widget data is missing css"),a(this,As,t.imageData??[]),a(this,Es,t.text??""),a(this,Ts,t.stylesheetUrl),a(this,Rs,t.height),a(this,Os,t.css)}get images(){return n(this,As)}get text(){return n(this,Es)}get stylesheetUrl(){return n(this,Ts)}get height(){return n(this,Rs)}get css(){return n(this,Os)}toJSON(){return{...super.toJSON(),images:this.images,text:this.text,stylesheetUrl:this.stylesheetUrl,height:this.height,css:this.css}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddCustomWidget(t,i);return new Uo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateCustomWidget(t,i);return new Uo(ae.fromJSON(o),t.subreddit,i)}};As=new WeakMap,Es=new WeakMap,Ts=new WeakMap,Rs=new WeakMap,Os=new WeakMap;var Ao=Uo,Ms,Za=class extends ie{constructor(t,i,s,o){super(i,s,o);l(this,Ms);let d=t.rules.map(({description:c,priority:m,shortName:y,violationReason:v})=>(p(c,"Subreddit rule is missing description"),p(m,"Subreddit rule is missing priority"),p(y,"Subreddit rule is missing shortName"),p(v,"Subreddit rule is missing violationReason"),{description:c,priority:m,shortName:y,violationReason:v}));a(this,Ms,d)}get rules(){return n(this,Ms)}toJSON(){return{...super.toJSON(),rules:this.rules}}};Ms=new WeakMap;var hg=(i=>(i[i.SUBREDDIT_PERMISSIONS=0]="SUBREDDIT_PERMISSIONS",i[i.APPROVED_CONTRIBUTORS_ONLY=1]="APPROVED_CONTRIBUTORS_ONLY",i[i.MODS_ONLY=2]="MODS_ONLY",i))(hg||{}),ge,he,pr,gr,hr,fr,yr,br,Ae,we=class we{constructor(e,t,i,s){l(this,ge);l(this,he);l(this,pr);l(this,gr);l(this,hr);l(this,fr);l(this,yr);l(this,br);l(this,Ae);Z(this),a(this,ge,e),a(this,he,t),a(this,pr,i.contentMd),a(this,gr,i.contentHtml),a(this,hr,i.revisionId),a(this,fr,new Date(i.revisionDate*1e3)),a(this,yr,i.reason??""),a(this,br,i.revisionBy?.data?new C(i.revisionBy.data,s):void 0),a(this,Ae,s)}get name(){return n(this,ge)}get subredditName(){return n(this,he)}get content(){return n(this,pr)}get contentHtml(){return n(this,gr)}get revisionId(){return n(this,hr)}get revisionDate(){return n(this,fr)}get revisionReason(){return n(this,yr)}get revisionAuthor(){return n(this,br)}toJSON(){return{name:n(this,ge),subredditName:n(this,he),content:n(this,pr),contentHtml:n(this,gr),revisionId:n(this,hr),revisionDate:n(this,fr),revisionReason:n(this,yr),revisionAuthor:n(this,br)?.toJSON()}}async update(e,t){return we.updatePage({subredditName:n(this,he),page:n(this,ge),content:e,reason:t},n(this,Ae))}async getRevisions(e){return we.getPageRevisions({subredditName:n(this,he),page:n(this,ge),...e},n(this,Ae))}async revertTo(e){return we.revertPage(n(this,he),n(this,ge),e,n(this,Ae))}async getSettings(){return we.getPageSettings(n(this,he),n(this,ge),n(this,Ae))}async updateSettings(e){return we.updatePageSettings({subredditName:n(this,he),page:n(this,ge),listed:e.listed,permLevel:e.permLevel},n(this,Ae))}async addEditor(e){return we.addEditor(n(this,he),n(this,ge),e,n(this,Ae))}async removeEditor(e){return we.removeEditor(n(this,he),n(this,ge),e,n(this,Ae))}static async getPage(e,t,i){let o=await u.redditAPIPlugins.Wiki.GetWikiPage({subreddit:e,page:t},i);return p(o.data,"Failed to get wiki page"),new we(t,e,o.data,i)}static async getPages(e,t){return(await u.redditAPIPlugins.Wiki.GetWikiPages({subreddit:e},t)).data||[]}static async createPage(e,t){return we.updatePage(e,t)}static async updatePage(e,t){return await u.redditAPIPlugins.Wiki.EditWikiPage({subreddit:e.subredditName,page:e.page,content:e.content,reason:e.reason??""},t),we.getPage(e.subredditName,e.page,t)}static getPageRevisions(e,t){let i=u.redditAPIPlugins.Wiki;return new V({hasMore:!0,after:e.after,limit:e.limit,pageSize:e.pageSize,async fetch(s){let o=await i.GetWikiPageRevisions({subreddit:e.subredditName,page:e.page,limit:s.limit,after:s.after,before:s.before},t);return fg(o,t)}})}static async revertPage(e,t,i,s){await u.redditAPIPlugins.Wiki.RevertWikiPage({subreddit:e,page:t,revision:i},s)}static async getPageSettings(e,t,i){let o=await u.redditAPIPlugins.Wiki.GetWikiPageSettings({subreddit:e,page:t},i);return p(o.data,"Failed to get wiki page settings"),new Do(o.data,i)}static async updatePageSettings(e,t){let s=await u.redditAPIPlugins.Wiki.UpdateWikiPageSettings({subreddit:e.subredditName,page:e.page,listed:e.listed?"on":"",permlevel:e.permLevel},t);return p(s.data,"Failed to update wiki page settings"),new Do(s.data,t)}static async addEditor(e,t,i,s){await u.redditAPIPlugins.Wiki.AllowEditor({act:"add",subreddit:e,page:t,username:i},s)}static async removeEditor(e,t,i,s){await u.redditAPIPlugins.Wiki.AllowEditor({act:"del",subreddit:e,page:t,username:i},s)}};ge=new WeakMap,he=new WeakMap,pr=new WeakMap,gr=new WeakMap,hr=new WeakMap,fr=new WeakMap,yr=new WeakMap,br=new WeakMap,Ae=new WeakMap;var ue=we,vr,kr,Cr,Pr,Sr,wr,Qa=class{constructor(e,t){l(this,vr);l(this,kr);l(this,Cr);l(this,Pr);l(this,Sr);l(this,wr);a(this,vr,e.id),a(this,kr,e.page),a(this,Cr,new Date(e.timestamp)),p(e.author?.data,"Wiki page revision author details are missing"),a(this,Pr,new C(e.author.data,t)),a(this,Sr,e.reason??""),a(this,wr,e.revisionHidden??!1)}get id(){return n(this,vr)}get page(){return n(this,kr)}get date(){return n(this,Cr)}get author(){return n(this,Pr)}get reason(){return n(this,Sr)}get hidden(){return n(this,wr)}toJSON(){return{id:n(this,vr),page:n(this,kr),date:n(this,Cr),author:n(this,Pr).toJSON(),reason:n(this,Sr),hidden:n(this,wr)}}};vr=new WeakMap,kr=new WeakMap,Cr=new WeakMap,Pr=new WeakMap,Sr=new WeakMap,wr=new WeakMap;var Fr,xr,Ir,Do=class{constructor(e,t){l(this,Fr);l(this,xr);l(this,Ir);a(this,Fr,e.listed),a(this,xr,e.permLevel),a(this,Ir,e.editors.map(i=>(p(i.data,"Wiki page editor details are missing"),new C(i.data,t))))}get listed(){return n(this,Fr)}get permLevel(){return n(this,xr)}get editors(){return n(this,Ir)}toJSON(){return{listed:n(this,Fr),permLevel:n(this,xr),editors:n(this,Ir).map(e=>e.toJSON())}}};Fr=new WeakMap,xr=new WeakMap,Ir=new WeakMap;function fg(r,e){return p(r.data?.children,"Wiki page revision listing is missing children"),{children:r.data.children.map(i=>new Qa(i,e)),before:r.data.before,after:r.data.after}}var yg=["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"],bg=["border-image","border-image-source","behavior","expression","list-style-image","cursor","content"],vg=["onload","onerror","onclick","onmouseover"];function kg(r){return/xmlns=["']http:\/\/www\.w3\.org\/2000\/svg["']/.test(r)?r:r.replace(/<svg\b/,'<svg xmlns="http://www.w3.org/2000/svg"')}function Ec(r){if(r){if(!r.trim().startsWith("<svg")){console.log("The provided string is not a valid SVG.");return}try{let e=new RegExp(`<\\s*(${yg.join("|")})\\b`,"gi"),t=new RegExp(`(${bg.join("|")})\\s*:\\s*url\\s*\\((['"]?)(.*?)\\2\\)`,"gi"),i=new RegExp(`(${vg.join("|")})\\s*(=\\s*(['"]?)(.*?)\\3)?`,"gi");r=r.trim().replace(/\s+/g," "),r=kg(r);let s=r.match(e)||[],o=r.match(t)||[],d=r.match(i)||[],c=!1;return s.length>0&&(c=!0,console.warn(`Disallowed elements detected in SVG: ${s.map(m=>m.replace("<","")).join(", ")}`)),o.length>0&&(c=!0,console.warn(`Disallowed styles detected in SVG: ${o.map(m=>m.split(":")[0]).join(", ")}`)),d.length>0&&(c=!0,console.warn(`Disallowed attributes detected in SVG: ${d.map(m=>m.split("=")[0]).join(", ")}`)),c?void 0:r}catch{return}}}function zP(r,...e){let t="";return r.forEach((i,s)=>{t+=i;let o=e[s];o!==void 0&&(t+=`${o}`)}),t=Ec(t),t===void 0?"":`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(t)}`}import{EffectType as Tc}from"@devvit/protos";import{WebViewVisibility as Cg}from"@devvit/protos";var Ar,Bs,Er,Tr,Qt,Us,Ya=class{constructor(e,t){this.state={messageCount:0};l(this,Ar);l(this,Bs);l(this,Er);l(this,Tr);l(this,Qt);this.postMessage=e=>{try{let t=JSON.stringify(e);n(this,Qt).emitEffect(`postMessage${this.state.messageCount++}`,{type:Tc.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:n(this,Ar),app:{message:e,jsonString:t}}}})}catch(t){throw console.error(Ye.caughtToString(t)),Error("Something went wrong. Please check the contents of your postMessage.")}};this.mount=()=>{let t=(n(this,Qt)?.devvitContext?.assets).getURL(n(this,Bs),{webView:!0});if(!t)throw Error("useWebView fullscreen request failed; web view asset could not be found");n(this,Us).call(this,!0,t)};this.unmount=()=>{n(this,Us).call(this,!1,"")};l(this,Us,(e,t)=>{n(this,Qt).emitEffect("fullscreen",{type:Tc.EFFECT_WEB_VIEW,webView:{fullscreen:{id:n(this,Ar),show:e,url:t}}})});a(this,Bs,t.url??"index.html"),a(this,Ar,e.hookId),a(this,Er,t.onMessage),a(this,Tr,t.onUnmount),a(this,Qt,e.context)}async onUIEvent(e){if(e.webView?.fullScreen)!(e.webView.fullScreen.visibility===Cg.WEBVIEW_VISIBLE)&&n(this,Tr)&&await n(this,Tr).call(this,this);else if(e.webView?.postMessage)if(e.webView.postMessage.jsonString){let t=JSON.parse(e.webView.postMessage.jsonString);await n(this,Er).call(this,t,this)}else await n(this,Er).call(this,e.webView.postMessage.message,this)}};Ar=new WeakMap,Bs=new WeakMap,Er=new WeakMap,Tr=new WeakMap,Qt=new WeakMap,Us=new WeakMap;function Pg(r){let e=me({namespace:"useWebView",initializer:t=>new Ya(t,r)});return{postMessage:e.postMessage,mount:e.mount,unmount:e.unmount}}export{Mg as ALL_ICON_NAMES,Rd as AboutLocations,Fc as AuthorFlairSettings,Fo as ButtonWidget,So as CalendarWidget,Q as Comment,xo as CommunityListWidget,Ao as CustomWidget,Ng as DeletionReason,u as Devvit,Lg as EventSource,ce as Flair,ne as FlairTemplate,Vp as FlairType,Je as Hook,Po as ImageWidget,V as Listing,lg as ModMailActionType,ag as ModMailConversationState,js as ModMailService,ve as ModNote,G as Post,xc as PostFlairSettings,Io as PostFlairWidget,It as PrivateMessage,jt as RichTextBuilder,_o as SettingScope,rg as SocialLinkType,le as Subreddit,Sc as SubredditDescription,Za as SubredditRulesWidget,wc as SubredditWikiSettings,wo as TextAreaWidget,C as User,ie as Widget,ue as WikiPage,hg as WikiPagePermissionLevel,Qa as WikiPageRevision,Do as WikiPageSettings,cn as convertUserFlairProtoToAPI,Td as getCurrentUsernameFromMetadata,Hs as getModerationLog,Od as getSubredditInfoById,Md as getSubredditInfoByName,Bd as getSubredditLeaderboard,Jo as getSubredditNameById,Ud as getSubredditStyles,Dd as getVaultByAddress,Nd as getVaultByUserId,zP as svg,Ap as useAsync,Fa as useChannel,Pa as useForm,Aa as useInterval,Oa as useState,Pg as useWebView};
|
|
1
|
+
var Nc=Object.create;var ed=Object.defineProperty;var Lc=Object.getOwnPropertyDescriptor;var _c=Object.getOwnPropertyNames;var Hc=Object.getPrototypeOf,jc=Object.prototype.hasOwnProperty;var td=i=>{throw TypeError(i)};var Vc=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var ei=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Wc=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _c(e))!jc.call(i,o)&&o!==t&&ed(i,o,{get:()=>e[o],enumerable:!(n=Lc(e,o))||n.enumerable});return i};var id=(i,e,t)=>(t=i!=null?Nc(Hc(i)):{},Wc(e||!i||!i.__esModule?ed(t,"default",{value:i,enumerable:!0}):t,i));var Ns=(i,e,t)=>e.has(i)||td("Cannot "+t);var r=(i,e,t)=>(Ns(i,e,"read from private field"),t?t.call(i):e.get(i)),l=(i,e,t)=>e.has(i)?td("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),d=(i,e,t,n)=>(Ns(i,e,"write to private field"),n?n.call(i,t):e.set(i,t),t),f=(i,e,t)=>(Ns(i,e,"access private method"),t);var nd=(i,e,t,n)=>({set _(o){d(i,e,o,t)},get _(){return r(i,e,n)}});var ma=ei((cb,pl)=>{var op=Object.prototype.toString;pl.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var t=typeof e;if(t==="boolean")return"boolean";if(t==="string")return"string";if(t==="number")return"number";if(t==="symbol")return"symbol";if(t==="function")return up(e)?"generatorfunction":"function";if(sp(e))return"array";if(pp(e))return"buffer";if(mp(e))return"arguments";if(dp(e))return"date";if(ap(e))return"error";if(lp(e))return"regexp";switch(ml(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(cp(e))return"generator";switch(t=op.call(e),t){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")};function ml(i){return typeof i.constructor=="function"?i.constructor.name:null}function sp(i){return Array.isArray?Array.isArray(i):i instanceof Array}function ap(i){return i instanceof Error||typeof i.message=="string"&&i.constructor&&typeof i.constructor.stackTraceLimit=="number"}function dp(i){return i instanceof Date?!0:typeof i.toDateString=="function"&&typeof i.getDate=="function"&&typeof i.setDate=="function"}function lp(i){return i instanceof RegExp?!0:typeof i.flags=="string"&&typeof i.ignoreCase=="boolean"&&typeof i.multiline=="boolean"&&typeof i.global=="boolean"}function up(i,e){return ml(i)==="GeneratorFunction"}function cp(i){return typeof i.throw=="function"&&typeof i.return=="function"&&typeof i.next=="function"}function mp(i){try{if(typeof i.length=="number"&&typeof i.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function pp(i){return i.constructor&&typeof i.constructor.isBuffer=="function"?i.constructor.isBuffer(i):!1}});var hl=ei((mb,fl)=>{"use strict";var gl=Symbol.prototype.valueOf,gp=ma();function fp(i,e){switch(gp(i)){case"array":return i.slice();case"object":return Object.assign({},i);case"date":return new i.constructor(Number(i));case"map":return new Map(i);case"set":return new Set(i);case"buffer":return vp(i);case"symbol":return kp(i);case"arraybuffer":return yp(i);case"float32array":case"float64array":case"int16array":case"int32array":case"int8array":case"uint16array":case"uint32array":case"uint8clampedarray":case"uint8array":return bp(i);case"regexp":return hp(i);case"error":return Object.create(i);default:return i}}function hp(i){let e=i.flags!==void 0?i.flags:/\w+$/.exec(i)||void 0,t=new i.constructor(i.source,e);return t.lastIndex=i.lastIndex,t}function yp(i){let e=new i.constructor(i.byteLength);return new Uint8Array(e).set(new Uint8Array(i)),e}function bp(i,e){return new i.constructor(i.buffer,i.byteOffset,i.length)}function vp(i){let e=i.length,t=Buffer.allocUnsafe?Buffer.allocUnsafe(e):Buffer.from(e);return i.copy(t),t}function kp(i){return gl?Object(gl.call(i)):{}}fl.exports=fp});var bl=ei((pb,yl)=>{"use strict";yl.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var Cl=ei((gb,kl)=>{"use strict";var Cp=bl();function vl(i){return Cp(i)===!0&&Object.prototype.toString.call(i)==="[object Object]"}kl.exports=function(e){var t,n;return!(vl(e)===!1||(t=e.constructor,typeof t!="function")||(n=t.prototype,vl(n)===!1)||n.hasOwnProperty("isPrototypeOf")===!1)}});var Sl=ei((fb,Pl)=>{"use strict";var Pp=hl(),Sp=ma(),wp=Cl();function pa(i,e){switch(Sp(i)){case"object":return xp(i,e);case"array":return Fp(i,e);default:return Pp(i)}}function xp(i,e){if(typeof e=="function")return e(i);if(e||wp(i)){let t=new i.constructor;for(let n in i)t[n]=pa(i[n],e);return t}return i}function Fp(i,e){let t=new i.constructor(i.length);for(let n=0;n<i.length;n++)t[n]=pa(i[n],e);return t}Pl.exports=pa});var pc=ei(hs=>{"use strict";hs.byteLength=tg;hs.toByteArray=ng;hs.fromByteArray=sg;var Ue=[],we=[],eg=typeof Uint8Array<"u"?Uint8Array:Array,Ga="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Jt=0,cc=Ga.length;Jt<cc;++Jt)Ue[Jt]=Ga[Jt],we[Ga.charCodeAt(Jt)]=Jt;var Jt,cc;we[45]=62;we[95]=63;function mc(i){var e=i.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=i.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}function tg(i){var e=mc(i),t=e[0],n=e[1];return(t+n)*3/4-n}function ig(i,e,t){return(e+t)*3/4-t}function ng(i){var e,t=mc(i),n=t[0],o=t[1],s=new eg(ig(i,n,o)),a=0,c=o>0?n-4:n,m;for(m=0;m<c;m+=4)e=we[i.charCodeAt(m)]<<18|we[i.charCodeAt(m+1)]<<12|we[i.charCodeAt(m+2)]<<6|we[i.charCodeAt(m+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=we[i.charCodeAt(m)]<<2|we[i.charCodeAt(m+1)]>>4,s[a++]=e&255),o===1&&(e=we[i.charCodeAt(m)]<<10|we[i.charCodeAt(m+1)]<<4|we[i.charCodeAt(m+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function rg(i){return Ue[i>>18&63]+Ue[i>>12&63]+Ue[i>>6&63]+Ue[i&63]}function og(i,e,t){for(var n,o=[],s=e;s<t;s+=3)n=(i[s]<<16&16711680)+(i[s+1]<<8&65280)+(i[s+2]&255),o.push(rg(n));return o.join("")}function sg(i){for(var e,t=i.length,n=t%3,o=[],s=16383,a=0,c=t-n;a<c;a+=s)o.push(og(i,a,a+s>c?c:a+s));return n===1?(e=i[t-1],o.push(Ue[e>>2]+Ue[e<<4&63]+"==")):n===2&&(e=(i[t-2]<<8)+i[t-1],o.push(Ue[e>>10]+Ue[e>>4&63]+Ue[e<<2&63]+"=")),o.join("")}});var he={APP:0,USER:1};import"@devvit/protos";var S=Object.freeze({Actor:"devvit-actor",App:"devvit-app",AppUser:"devvit-app-user",AppViewerAuthToken:"devvit-app-viewer-authorization",Caller:"devvit-caller",CallerPortID:"devvit-caller-port-id",Canary:"devvit-canary",Debug:"devvit-debug",GQLHost:"devvit-gql-host",Installation:"devvit-installation",ModPermissions:"devvit-mod-permissions",Post:"devvit-post",PostAuthor:"devvit-post-author",R2Auth:"devvit-sec-authorization",R2Host:"devvit-r2-host",RemoteHostname:"devvit-remote-hostname",SettingsUri:"devvit-sec-settings-uri",StreamID:"devvit-stream-id",Subreddit:"devvit-subreddit",SubredditName:"devvit-subreddit-name",TraceID:"devvit-trace-id",User:"devvit-user",Username:"devvit-user-name",UserAgent:"devvit-user-agent",Version:"devvit-version",Language:"devvit-accept-language",Timezone:"devvit-accept-timezone",Traceparent:"traceparent",AppDependencies:"devvit-app-dependencies"}),rd;(function(i){i.Blocks="blocks",i.EmitSnapshots="emitSnapshots",i.EmitState="emitState",i.Realtime="realtime",i.Runtime="runtime",i.Surface="surface",i.UseAsync="useAsync",i.Payments="payments",i.Bootstrap="bootstrap",i.WebView="webView"})(rd||(rd={}));function Ft(i,e){if(!i)throw Error(e)}var ee;(function(i){i.COMMENT="t1_",i.ACCOUNT="t2_",i.LINK="t3_",i.MESSAGE="t4_",i.SUBREDDIT="t5_",i.AWARD="t6_"})(ee||(ee={}));function Je(i){return i.startsWith(ee.COMMENT)}function En(i){return i.startsWith(ee.ACCOUNT)}function At(i){return i.startsWith(ee.LINK)}function od(i){return i.startsWith(ee.MESSAGE)}function sd(i){return i.startsWith(ee.SUBREDDIT)}function ad(i){return i.startsWith(ee.AWARD)}function Gc(i){Ft(Je(i),`Expected comment id to start with ${ee.COMMENT}, got ${i}}`)}function Jc(i){Ft(En(i),`Expected account id to start with ${ee.ACCOUNT}, got ${i}}`)}function zc(i){Ft(At(i),`Expected link id to start with ${ee.LINK}, got ${i}}`)}function qc(i){Ft(od(i),`Expected message id to start with ${ee.MESSAGE}, got ${i}}`)}function $c(i){Ft(sd(i),`Expected subreddit id to start with ${ee.SUBREDDIT}, got ${i}}`)}function Kc(i){Ft(ad(i),`Expected award id to start with ${ee.AWARD}, got ${i}}`)}function ti(i){return Gc(i),i}function te(i){return Jc(i),i}function de(i){return zc(i),i}function Zc(i){return qc(i),i}function $(i){return $c(i),i}function Xc(i){return Kc(i),i}function ye(i){if(Je(i))return ti(i);if(En(i))return te(i);if(At(i))return de(i);if(od(i))return Zc(i);if(sd(i))return $(i);if(ad(i))return Xc(i);throw new Error(`Expected thing id to start with ${Object.values(ee).join(", ")} got ${i}}`)}function Ls(i){return Je(i)}import*as k from"@devvit/protos";var Mo=class{constructor(e){}};var _s=(t=>(t.Installation="installation",t.App="app",t))(_s||{});function It(i,e=new Set){for(let t of i){if(t.type==="group"){It(t.fields,e);continue}let n=t.name;if(e.has(n))throw new Error(`Duplicate field name: ${n}`);e.add(n)}Qc(i)}function Qc(i){for(let e of i)if(e.type==="string"&&e.isSecret&&e.scope!=="app")throw`Invalid setting: only app settings can be secrets. Add "scope: SettingScope.App" to field "${e.name}"`}var ze=Object.freeze({INTERVAL:0,FORM:1,STATE:2,CHANNEL:3,WEB_VIEW:4});var Vg=["3rd-party","activity","add-emoji","add","add-media","add-to-feed","admin","ads","ai","align-center","align-left","align-right","all","ama","appearance","approve","archived","aspect-ratio","aspect-rectangle","attach","audience","audio","author","automod","avatar-style","award","back","backup","ban","best","block","blockchain","bold","boost","bot","bounce","brand-awareness","browse","browser","cake","calendar","camera","campaign","caret-down","caret-left","caret-right","caret-up","chat","chat-group","chat-new","chat-private","checkbox-dismiss","checkbox","checkmark","chrome","clear","client-list","close","closed-captioning","code-block","code-inline","coins-color-old","coins","collapse-left","collapse-right","collectible-expressions","collection","comment","comments","communities","community","confidence","contest","controversial","conversion","copy-clipboard","crop","crosspost","crowd-control","custom-feed","customize","dashboard","day","delete-column","delete","delete-row","devvit","discover","dismiss-all","distinguish","down-arrow","down","download","downvote","downvotes","drag","drugs","duplicate","edit","effect","embed","emoji","end-live-chat","error","expand-left","expand-right","external","feed-video","filter","format","forward","funnel","gif-post","gold","hashtag","heart","help","hide","history","home","hot","ignore-reports","image-post","inbox","info","insert-column-left","insert-column-right","insert-row-above","insert-row-below","internet","invite","italic","join","joined","jump-down","jump-up","karma","keyboard","kick","language","leave","left","link","link-post","list-bulleted","list-numbered","live-chat","live","load","location","lock","logout","loop","macro","mark-read","marketplace","mask","media-gallery","meme","menu","message","mic","mic-mute","mod","mod-mail","mod-mode","mod-mute","mod-overflow","mod-queue","mod-unmute","music","mute","new","night","no-internet","notification","notification-frequent","notification-off","nsfw","nsfw-language","nsfw-violence","official","original","overflow-caret","overflow-horizontal","overflow-vertical","pause","payment","peace","pending-posts","phone","pin","play","poll-post","popular","posts","powerup","predictions","premium","privacy","profile","qa","qr-code","quarantined","quote","r-slash","radar","radio-button","raise-hand","random","ratings-everyone","ratings-mature","ratings-nsfw","ratings-violence","recovery-phrase","refresh","removal-reasons","remove","reply","report","reverse","rich-text","right","rising","rotate","rotate-image","rpan","rules","safari","save","save-view","saved","saved-response","search","self","send","settings","severity","share","share-new","show","side-menu","skipback10","skipforward10","sort-az","sort","sort-price","sort-za","spam","spoiler","sponsored","spreadsheet","star","statistics","status-live","sticker","strikethrough","subtract","superscript","swap-camera","swipe-back","swipe-down","swipe","swipe-up","table","tag","tap","text","text-post","text-size","toggle","tools","top","topic-activism","topic-addictionsupport","topic-advice","topic-animals","topic-anime","topic-art","topic-beauty","topic-business","topic-careers","topic-cars","topic-celebrity","topic-craftsdiy","topic-crypto","topic-culture","topic-diy","topic-entertainment","topic-ethics","topic-family","topic-fashion","topic","topic-fitness","topic-food","topic-funny","topic-gender","topic-health","topic-help","topic-history","topic-hobbies","topic-homegarden","topic-internet","topic-law","topic-learning","topic-lifestyle","topic-marketplace","topic-mature","topic-mensfashion","topic-menshealth","topic-meta","topic-military","topic-movies","topic-music","topic-news","topic-other","topic-outdoors","topic-pets","topic-photography","topic-places","topic-podcasts","topic-politics","topic-programming","topic-reading","topic-religion","topic-science","topic-sexorientation","topic-sports","topic-style","topic-tabletop","topic-technology","topic-television","topic-traumasupport","topic-travel","topic-videogaming","topic-womensfashion","topic-womenshealth","translate","translation-off","trim","u-slash","unban","undo","unheart","unlock","unmod","unpin","unstar","unverified","up-arrow","up","upload","upvote","upvotes","user","user-note","users","vault","verified","video-camera","video-feed","video-post","video-thread","video-transcription","view-card","view-classic","view-compact","view-grid","view-sort","views","volume","wallet","warning","webhook","whale","wiki-ban","wiki","wiki-unban","world","coins-color","powerup-color","powerup-fill-color","share-android","share-ios","video-live-1","video-live-fill-1","video-live","volume-mute","binoculars","caret-updown","planet","telescope"];import{DeletionReason as zg,EventSource as qg}from"@devvit/protos";import{AppSettingsDefinition as fm,GetFieldsResponse as hm}from"@devvit/protos";import{FormFieldType as be}from"@devvit/protos";function Le(i){return i.map(e=>{switch(e.type){case"string":return Yc(e);case"image":return em(e);case"paragraph":return tm(e);case"number":return im(e);case"select":return nm(e);case"boolean":return rm(e);case"group":return om(e);default:throw new Error("Unknown field type.")}})}function Yc(i){return{defaultValue:{fieldType:be.STRING,stringValue:i.defaultValue},disabled:i.disabled,fieldConfig:{stringConfig:{placeholder:i.placeholder}},fieldId:i.name,fieldType:be.STRING,helpText:i.helpText,label:i.label,required:i.required,isSecret:i.isSecret}}function em(i){return{disabled:i.disabled,fieldId:i.name,fieldType:be.IMAGE,helpText:i.helpText,label:i.label,required:i.required}}function tm(i){return{defaultValue:{fieldType:be.PARAGRAPH,stringValue:i.defaultValue},disabled:i.disabled,fieldConfig:{paragraphConfig:{lineHeight:i.lineHeight,placeholder:i.placeholder}},fieldId:i.name,fieldType:be.PARAGRAPH,helpText:i.helpText,label:i.label,required:i.required}}function im(i){return{defaultValue:{fieldType:be.NUMBER,numberValue:i.defaultValue},disabled:i.disabled,fieldConfig:{numberConfig:{}},fieldId:i.name,fieldType:be.NUMBER,helpText:i.helpText,label:i.label,required:i.required}}function nm(i){return{defaultValue:{fieldType:be.SELECTION,selectionValue:{values:i.defaultValue??[]}},disabled:i.disabled,fieldConfig:{selectionConfig:{choices:i.options,multiSelect:i.multiSelect}},fieldId:i.name,fieldType:be.SELECTION,helpText:i.helpText,label:i.label,required:i.required}}function rm(i){return{defaultValue:{fieldType:be.BOOLEAN,boolValue:i.defaultValue},disabled:i.disabled,fieldId:i.name,fieldType:be.BOOLEAN,helpText:i.helpText,label:i.label}}function om(i){return{fieldId:"",fieldType:be.GROUP,fieldConfig:{groupConfig:{fields:Le(i.fields)}},label:i.label,helpText:i.helpText}}var Bo=function(){try{let{AsyncLocalStorage:i}=Vc("node:async_hooks");return new i}catch{}}(),Uo;function g(){if(Bo){let i=Bo.getStore();if(!i)throw Error("API error; metadata should never be accessed outside a request");return i}if(!Uo)throw Error("Devvit metadata can only be accessed within a request");return Uo}async function dd(i,e){if(Bo)return Bo.run(i,e);try{return Uo=i,await e()}finally{Uo=void 0}}function O(i,e){u.prototype[i]=(t,n,...o)=>{let s=n??{};return dd(s,()=>e(t,s,...o))}}import{ValidateFormResponse as gm}from"@devvit/protos";import{RealtimeSubscriptionStatus as ld}from"@devvit/protos";function p(i,e){if(i==null)throw Error(e??"Expected nonnullish value.")}function ud(i){function e(t){let o=i.currentHookIndex,s=i.getCurrentComponentState(),a=i.getPreviousComponentState(),c=i.metadata[S.App]?.values[0];p(c,"useChannel - app is missing from Context");let m=i.metadata[S.Installation]?.values[0];p(m,"useChannel - installation is missing from Context");async function h(M){let Y=s[o].channel;if(s[o].active)if(s[o].connected)await i.realtime.send(Y,M);else throw Error(`Failed to send to channel '${Y}'; it is active but not yet connected`);else throw Error(`Cannot send a message over inactive channel: ${Y}`)}function v(){if(!s[o].active){let M=s[o].channel;s[o].active=!0,i.addRealtimeChannel(M)}}function y(){if(s[o].active){let M=s[o].channel;s[o].active=!1,i.removeRealtimeChannel(M)}}function P(M){return async()=>{let Y;switch(M.status){case ld.REALTIME_SUBSCRIBED:s[o].connected=!0,Y=t.onSubscribed?.();break;case ld.REALTIME_UNSUBSCRIBED:s[o].connected=!1,Y=t.onUnsubscribed?.();break;default:Y=t.onMessage(M.event?.data?.msg);break}await Y}}let b={channel:`${c}:${m}:${t.name}`,active:!1,connected:!1,preventCallback:!1,type:ze.CHANNEL};o in s?b=s[o]:o in a&&(b=a[o]);let A=i.realtimeEvent;i.isInitialRender?b.active=!1:A&&b.active&&A.event.channel===b.channel&&(b.preventCallback||i.runHook(P(A)),i.rerenderIn(0)),s[o]=b,i.currentHookIndex++;let U=0;return b.active&&b.connected?U=2:b.active&&!b.connected?U=1:!b.active&&b.connected?U=3:!b.active&&!b.connected&&(U=4),{subscribe:v,unsubscribe:y,send:h,status:U}}return e}import{FormFieldType as ii}from"@devvit/protos";function Hs(i){switch(i.fieldType){case ii.STRING:return i.stringValue;case ii.IMAGE:return i.stringValue;case ii.PARAGRAPH:return i.stringValue;case ii.NUMBER:return i.numberValue;case ii.BOOLEAN:return i.boolValue;case ii.SELECTION:return i.selectionValue?.values??[];default:return}}function qe(i){return Object.keys(i).reduce((e,t)=>{let n=Hs(i[t]);return n!==void 0&&(e[t]=n),e},{})}function cd(i){function e(t,n){let o=i.currentHookIndex,s=i.getCurrentComponentKey(),a=i.getCurrentComponentState(),c=i.getPreviousComponentState(),m=`form.hook.${s}.${o}`,h={formKey:m,preventSubmit:!1,type:ze.FORM};o in a?h=a[o]:o in c&&(h=c[o]),a[o]=h,i.forms.set(m,t);let v=i.formSubmittedEvent;return v&&!h.preventSubmit&&v.formId===m&&i.runHook(async()=>{let y=n(qe(v.results));y&&y instanceof Promise&&await y,i.rerenderIn(0)}),a[o].preventSubmit=!1,i.currentHookIndex++,m}return e}function md(i){function e(t,n){let o=i.currentHookIndex,s=i.getCurrentComponentState(),a=i.getPreviousComponentState(),c=100,m=Math.max(c,n),h={lastRun:void 0,running:!1,preventCallback:!1,type:ze.INTERVAL};o in s?h=s[o]:o in a&&(h=a[o]);function v(){n<c&&console.error(`useInterval delay must be at least ${c}ms. Your interval of ${n}ms was automatically extended.`);for(let[P,b]of Object.entries(s))if(P!==o.toString()&&b?.type===ze.INTERVAL&&b?.running)throw new Error("Only one useInterval hook may be running at a time");s[o]={running:!0,lastRun:s[o]?.lastRun??Date.now(),preventCallback:!1,type:ze.INTERVAL},i.rerenderIn(m)}function y(){s[o].running=!1,s[o].lastRun=void 0,s[o].preventCallback=!1}return i.isEffectRender&&h.running&&(h.preventCallback||(h.lastRun===void 0||h.lastRun+m<Date.now())&&i.runHook(async()=>{let P=t();P&&P instanceof Promise&&await P,h.lastRun=Date.now()}),i.rerenderIn(m)),h.preventCallback=!1,s[o]=h,i.currentHookIndex++,{start:v,stop:y}}return e}function pd(i){function e(t){let n=i.currentHookIndex,o=i.getCurrentComponentState(),s=i.getPreviousComponentState();if(n in o)return i.currentHookIndex++,[o[n],a];if(i.isInitialRender||!(n in s)){let c=t instanceof Function?t():t;if(c instanceof Promise)throw(async()=>{o[n]=await c,i.currentHookIndex=0})();o[n]=c}else o[n]=s[n];function a(c){if(i.isRendering)throw new Error("Cannot call setState while rendering.");o[n]=c instanceof Function?c(o[n]):c}return i.currentHookIndex++,[o[n],a]}return e}var Gs={now(){return new Date}};function gd(i){return`__autocache__${i}`}function fd(i){return`__lock__${i}`}var am=300,dm=1e3,Do=5e3,js=3,hd=.1,yd=1e3,lm=3e4;function bd(i){if(i.error)throw new Error(i.error);return i.value}var $e,Ke,ve,ni,J,vd,kd,Cd,Vs,Pd,Sd,Ws,wd,No=class{constructor(e,t,n=Gs){l(this,J);l(this,$e);l(this,Ke,{});l(this,ve);l(this,ni);d(this,$e,e),d(this,ni,t),d(this,ve,n)}async cache(e,t){d(this,Ke,r(this,ni).__cache=r(this,ni).__cache??{}),f(this,J,wd).call(this,t);let n=f(this,J,vd).call(this,t.key);if(n!==void 0)return n;let o=await f(this,J,Ws).call(this,t.key),s=await f(this,J,kd).call(this,t,o,e);return bd(s)}};$e=new WeakMap,Ke=new WeakMap,ve=new WeakMap,ni=new WeakMap,J=new WeakSet,vd=function(e){let t=r(this,Ke)[e];if(t){let n=r(this,ve).now().getTime(),o=t?.error&&t?.errorTime&&t.errorCount<js&&Math.random()<hd&&t.errorTime+yd<n;if(t?.expires&&t.expires<n&&t.checkedAt+yd<n||o){delete r(this,Ke)[e];return}else return bd(t)}},kd=async function(e,t,n){let o=t?.expires,s=o?f(this,J,Sd).call(this,o):1;return!t||t?.error&&t.errorCount<js&&hd>Math.random()||s>Math.random()?f(this,J,Cd).call(this,e,t,n):t},Cd=async function(e,t,n){let o=fd(e.key),s=r(this,ve).now().getTime(),a=new Date(s+e.ttl/2);if(await r(this,$e).set(o,"1",{expiration:a,nx:!0}))return f(this,J,Pd).call(this,e.key,t,n,e.ttl);if(t)return t;{let m=r(this,ve).now();return f(this,J,Vs).call(this,m,e.key,e.ttl)}},Vs=async function(e,t,n){let o=Math.min(n,dm),s=await f(this,J,Ws).call(this,t);if(s)return s;if(r(this,ve).now().getTime()-e.getTime()>=o)throw new Error(`Cache request timed out trying to get data at key: ${t}`);return await new Promise(a=>setTimeout(a,am)),f(this,J,Vs).call(this,e,t,n)},Pd=async function(e,t,n,o){let s=r(this,ve).now().getTime()+o;t=t??{value:null,expires:s,errorCount:0,error:null,errorTime:null,checkedAt:0};try{t.value=await n(),t.error=null,t.errorCount=0,t.errorTime=null}catch(a){t.value=null,t.error=a.message??"Unknown error",t.errorTime=r(this,ve).now().getTime(),t.errorCount++}return r(this,Ke)[e]=t,await r(this,$e).set(gd(e),JSON.stringify(t),{expiration:new Date(s+lm)}),t.error&&t.errorCount<js&&await r(this,$e).del(fd(e)),t},Sd=function(e){let t=r(this,ve).now().getTime(),n=e-t;return n<0?1:n<1e3?.1:n<2e3?.01:n<3e3?.001:0},Ws=async function(e){let t=await r(this,$e).get(gd(e));if(t){let n=JSON.parse(t);return n.checkedAt=r(this,ve).now().getTime(),r(this,Ke)[e]=n,n}},wd=function(e){e.ttl<Do&&(console.warn(`Cache TTL cannot be less than ${Do} milliseconds! Updating ttl value of ${e.ttl} to ${Do}.`),e.ttl=Do)};function xd(i,e,t=Gs){let n=new No(i,e,t);return n.cache.bind(n)}function Fd(i){new URL(i.slice(0,i.indexOf(",")))}var ri,oi,ai,Ad,Id,si=class{constructor(){l(this,ai);l(this,ri,{});l(this,oi,{});d(this,ri,u.assets),d(this,oi,u.webViewAssets)}getURL(e,t){return typeof e=="string"?f(this,ai,Ad).call(this,e,t??{webView:!1}):f(this,ai,Id).call(this,e,t??{webView:!1})}};ri=new WeakMap,oi=new WeakMap,ai=new WeakSet,Ad=function(e,t){let n=t.webView?r(this,oi)[e]:r(this,ri)[e];if(n)return n;try{return Fd(e),e}catch{return""}},Id=function(e,t){let n={},o=[],s=t.webView?r(this,oi):r(this,ri);if(s)for(let a of e)if(s[a])n[a]=s[a];else try{Fd(a),n[a]=a}catch{o.push(a)}else o=e;if(o.length>0)throw new Error(`The following assets were missing from the assets list: ${o.join(", ")}`);return n};var Ze,di=class{constructor(e){l(this,Ze);d(this,Ze,e)}async get(e){let{messages:t}=await u.kvStorePlugin.Get({keys:[e]},r(this,Ze));try{if(t[e])return JSON.parse(t[e])}catch{return}}async put(e,t){let n={};n[e]=JSON.stringify(t),await u.kvStorePlugin.Put({messages:n},r(this,Ze))}async delete(e){await u.kvStorePlugin.Del({keys:[e]},r(this,Ze))}async list(){let{keys:e}=await u.kvStorePlugin.List({filter:"*"},r(this,Ze));return e}};Ze=new WeakMap;var Tn,li=class{constructor(e){l(this,Tn);d(this,Tn,e)}async upload(e){let t=await u.mediaPlugin.Upload(e,r(this,Tn));if(!t.mediaId)throw new Error("unable to get mediaId via uploads");return Promise.resolve({mediaId:t.mediaId,mediaUrl:t.mediaUrl})}};Tn=new WeakMap;var Rn,ui=class{constructor(e){l(this,Rn);d(this,Rn,e)}async add(e){await u.modLogPlugin.Add(e,r(this,Rn))}};Rn=new WeakMap;var On,ci=class{constructor(e){l(this,On);d(this,On,e)}async send(e,t){await u.realtimePlugin.Send({channel:e,data:{msg:t}},r(this,On))}};On=new WeakMap;import{BitfieldOverflowBehavior as Js,RedisKeyScope as zs}from"@devvit/protos";function Mn(i){return i&&typeof i=="object"&&"message"in i&&i.message!==void 0&&typeof i.message=="string"?i.message.includes("redis: nil"):!1}var I,E,T,qs=class{constructor(e,t,n){l(this,I);l(this,E);l(this,T);d(this,I,e),d(this,E,t),d(this,T,n)}async get(e){return await r(this,I).Get({key:e,transactionId:r(this,E)},r(this,T)),this}async multi(){await r(this,I).Multi(r(this,E),r(this,T))}async set(e,t,n){let o;return n?.expiration&&(o=Math.floor((n.expiration.getTime()-Date.now())/1e3),o<1&&(o=1)),await r(this,I).Set({key:e,value:t,nx:n?.nx===!0,xx:n?.xx===!0,expiration:o||0,transactionId:r(this,E)},r(this,T)),this}async del(...e){return await r(this,I).Del({keys:e,transactionId:r(this,E)},r(this,T)),this}async type(e){return await r(this,I).Type({key:e,transactionId:r(this,E)},r(this,T)),this}async exec(){let e=await r(this,I).Exec(r(this,E),r(this,T)),t=[];for(let n of e.response)n.members?t.push(n.members):n.nil!==void 0?t.push(null):n.num!==void 0?t.push(n.num):n.values!==void 0?t.push(n.values.values):n.str!==void 0?t.push(n.str):n.dbl!==void 0&&t.push(n.dbl);return t}async discard(){await r(this,I).Discard(r(this,E),r(this,T))}async watch(...e){return await r(this,I).Watch({keys:e,transactionId:r(this,E)},r(this,T)),this}async unwatch(){return await r(this,I).Unwatch(r(this,E),r(this,T)),this}async getRange(e,t,n){return await r(this,I).GetRange({key:e,start:t,end:n,transactionId:r(this,E)},r(this,T)),this}async setRange(e,t,n){return await r(this,I).SetRange({key:e,offset:t,value:n,transactionId:r(this,E)},r(this,T)),this}async strlen(e){return this.strLen(e)}async strLen(e){return await r(this,I).Strlen({key:e,transactionId:r(this,E)},r(this,T)),this}async mget(e){return this.mGet(e)}async mGet(e){return await r(this,I).MGet({keys:e,transactionId:r(this,E)},r(this,T)),this}async mset(e){return this.mSet(e)}async mSet(e){let t=Object.entries(e).map(([n,o])=>({key:n,value:o}));return await r(this,I).MSet({kv:t,transactionId:r(this,E)},r(this,T)),this}async incrBy(e,t){return await r(this,I).IncrBy({key:e,value:t,transactionId:r(this,E)},r(this,T)),this}async expire(e,t){return await r(this,I).Expire({key:e,seconds:t,transactionId:r(this,E)},r(this,T)),this}async expireTime(e){return await r(this,I).ExpireTime({key:e,transactionId:r(this,E)},r(this,T)),this}async zAdd(e,...t){return await r(this,I).ZAdd({key:e,members:t,transactionId:r(this,E)},r(this,T)),this}async zScore(e,t){return await r(this,I).ZScore({key:{key:e,transactionId:r(this,E)},member:t},r(this,T)),this}async zRank(e,t){return await r(this,I).ZRank({key:{key:e,transactionId:r(this,E)},member:t},r(this,T)),this}async zIncrBy(e,t,n){return await r(this,I).ZIncrBy({key:e,member:t,value:n,transactionId:r(this,E)},r(this,T)),this}async zScan(e,t,n,o){let s={key:e,cursor:t,pattern:n,count:o,transactionId:r(this,E)};return await r(this,I).ZScan(s,r(this,T)),this}async zCard(e){return await r(this,I).ZCard({key:e,transactionId:r(this,E)},r(this,T)),this}async zRange(e,t,n,o){let s={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};if(o?.reverse&&(s.rev=o.reverse),o?.by==="lex"?s.byLex=!0:o?.by==="score"&&(s.byScore=!0),o?.limit)if(s.byLex||s.byScore)s.offset=o.limit.offset,s.count=o.limit.count;else throw new Error("zRange parsing error: 'limit' only allowed when 'options.by' is 'lex' or 'score'");return await r(this,I).ZRange({key:{key:e,transactionId:r(this,E)},start:t+"",stop:n+"",...s},r(this,T)),this}async zRem(e,t){return await r(this,I).ZRem({key:{key:e,transactionId:r(this,E)},members:t},r(this,T)),this}async zRemRangeByLex(e,t,n){return await r(this,I).ZRemRangeByLex({key:{key:e,transactionId:r(this,E)},min:t,max:n},r(this,T)),this}async zRemRangeByRank(e,t,n){return await r(this,I).ZRemRangeByRank({key:{key:e,transactionId:r(this,E)},start:t,stop:n},r(this,T)),this}async zRemRangeByScore(e,t,n){return await r(this,I).ZRemRangeByScore({key:{key:e,transactionId:r(this,E)},min:t,max:n},r(this,T)),this}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){return await r(this,I).HGetAll({key:e,transactionId:r(this,E)},r(this,T)),this}async hget(e,t){return this.hGet(e,t)}async hGet(e,t){return await r(this,I).HGet({key:e,field:t,transactionId:r(this,E)},r(this,T)),this}async hMGet(e,t){return await r(this,I).HMGet({key:e,fields:t,transactionId:r(this,E)},r(this,T)),this}async hset(e,t){return this.hSet(e,t)}async hSet(e,t){let n=Object.entries(t).map(([o,s])=>({field:o,value:s}));return await r(this,I).HSet({key:e,fv:n,transactionId:r(this,E)},r(this,T)),this}async hincrby(e,t,n){return this.hIncrBy(e,t,n)}async hIncrBy(e,t,n){return await r(this,I).HIncrBy({key:e,field:t,value:n,transactionId:r(this,E)},r(this,T)),this}async hdel(e,t){return this.hDel(e,t)}async hDel(e,t){return await r(this,I).HDel({key:e,fields:t,transactionId:r(this,E)},r(this,T)),this}async hscan(e,t,n,o){return this.hScan(e,t,n,o)}async hScan(e,t,n,o){let s={key:e,cursor:t,pattern:n,count:o,transactionId:r(this,E)};return await r(this,I).HScan(s,r(this,T)),this}async hkeys(e){return this.hKeys(e)}async hKeys(e){return await r(this,I).HKeys({key:e,transactionId:r(this,E)},r(this,T)),this}async hlen(e){return this.hLen(e)}async hLen(e){return await r(this,I).HLen({key:e,transactionId:r(this,E)},r(this,T)),this}};I=new WeakMap,E=new WeakMap,T=new WeakMap;var w,mi,$s=class $s{constructor(e,t=void 0,n=zs.INSTALLATION){l(this,w);l(this,mi);d(this,w,e),d(this,mi,t),this.scope=n,this.global=n===zs.INSTALLATION?new $s(r(this,w),r(this,mi),zs.GLOBAL):this}get storage(){return r(this,mi)||u.redisPlugin}async watch(...e){let t=await this.storage.Watch({keys:e},r(this,w));return new qs(this.storage,t,r(this,w))}async get(e){try{let t=await this.storage.Get({key:e,scope:this.scope},{...r(this,w),"throw-redis-nil":{values:["true"]}});return t!==null?t.value??void 0:t}catch(t){if(Mn(t))return;throw t}}async getBuffer(e){try{let t=await this.storage.GetBytes({key:e,scope:this.scope},{...r(this,w),"throw-redis-nil":{values:["true"]}});return t!==null?Buffer.from(t.value):t}catch(t){if(Mn(t))return;throw t}}async set(e,t,n){let o;return n?.expiration&&(o=Math.floor((n.expiration.getTime()-Date.now())/1e3),o<1&&(o=1)),(await this.storage.Set({key:e,value:t,nx:n?.nx===!0&&!n.xx,xx:n?.xx===!0&&!n.nx,expiration:o||0,scope:this.scope},r(this,w))).value}async exists(...e){return(await this.storage.Exists({keys:e,scope:this.scope},r(this,w))).existingKeys}async del(...e){await this.storage.Del({keys:e,scope:this.scope},r(this,w))}async incrBy(e,t){return(await this.storage.IncrBy({key:e,value:t,scope:this.scope},r(this,w))).value}async getRange(e,t,n){let o=await this.storage.GetRange({key:e,start:t,end:n,scope:this.scope},r(this,w));return o!==null?o.value:o}async setRange(e,t,n){return(await this.storage.SetRange({key:e,offset:t,value:n,scope:this.scope},r(this,w))).value}async strlen(e){return this.strLen(e)}async strLen(e){return(await this.storage.Strlen({key:e,scope:this.scope},r(this,w))).value}async expire(e,t){await this.storage.Expire({key:e,seconds:t,scope:this.scope},r(this,w))}async expireTime(e){return(await this.storage.ExpireTime({key:e,scope:this.scope},r(this,w))).value}async zAdd(e,...t){return(await this.storage.ZAdd({key:e,members:t,scope:this.scope},r(this,w))).value}async zRange(e,t,n,o){let s={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};if(o?.reverse&&(s.rev=o.reverse),o?.by==="lex"?s.byLex=!0:o?.by==="score"?s.byScore=!0:(s.offset=0,s.count=0),o?.limit)if(s.byLex||s.byScore)s.offset=o.limit.offset,s.count=o.limit.count;else throw new Error("zRange parsing error: 'limit' only allowed when 'options.by' is 'lex' or 'score'");return(await this.storage.ZRange({key:{key:e},start:t+"",stop:n+"",...s,scope:this.scope},r(this,w))).members}async zRem(e,t){return(await this.storage.ZRem({key:{key:e},members:t,scope:this.scope},r(this,w))).value}async zRemRangeByLex(e,t,n){return(await this.storage.ZRemRangeByLex({key:{key:e},min:t,max:n,scope:this.scope},r(this,w))).value}async zRemRangeByRank(e,t,n){return(await this.storage.ZRemRangeByRank({key:{key:e},start:t,stop:n,scope:this.scope},r(this,w))).value}async zRemRangeByScore(e,t,n){return(await this.storage.ZRemRangeByScore({key:{key:e},min:t,max:n,scope:this.scope},r(this,w))).value}async zScore(e,t){try{let n=await this.storage.ZScore({key:{key:e},member:t,scope:this.scope},{...r(this,w),"throw-redis-nil":{values:["true"]}});return n!==null?n.value:n}catch(n){if(Mn(n))return;throw n}}async zRank(e,t){try{let n=await this.storage.ZRank({key:{key:e},member:t,scope:this.scope},{...r(this,w),"throw-redis-nil":{values:["true"]}});return n!==null?n.value:n}catch(n){if(Mn(n))return;throw n}}async zIncrBy(e,t,n){let o=await this.storage.ZIncrBy({key:e,member:t,value:n,scope:this.scope},r(this,w));return o!==null?o.value:o}async mget(e){return this.mGet(e)}async mGet(e){let t=await this.storage.MGet({keys:e,scope:this.scope},r(this,w));return t!==null?t.values.map(n=>n||null):t}async mset(e){return this.mSet(e)}async mSet(e){let t=Object.entries(e).map(([n,o])=>({key:n,value:o}));await this.storage.MSet({kv:t,scope:this.scope},r(this,w))}async zCard(e){let t=await this.storage.ZCard({key:e,scope:this.scope},r(this,w));return t!==null?t.value:t}async zScan(e,t,n,o){let s={key:e,cursor:t,pattern:n,count:o,scope:this.scope};return await this.storage.ZScan(s,r(this,w))}async type(e){let t=await this.storage.Type({key:e,scope:this.scope},r(this,w));return t!==null?t.value:t}async rename(e,t){return(await this.storage.Rename({key:e,newKey:t,scope:this.scope},r(this,w))).result}async hget(e,t){return this.hGet(e,t)}async hGet(e,t){try{let n=await this.storage.HGet({key:e,field:t,scope:this.scope},{...r(this,w),"throw-redis-nil":{values:["true"]}});return n!==null?n.value??void 0:n}catch(n){if(Mn(n))return;throw n}}async hMGet(e,t){let n=await this.storage.HMGet({key:e,fields:t,scope:this.scope},r(this,w));return n!==null?n.values.map(o=>o||null):n}async hset(e,t){return this.hSet(e,t)}async hSet(e,t){let n=Object.entries(t).map(([s,a])=>({field:s,value:a}));return(await this.storage.HSet({key:e,fv:n,scope:this.scope},r(this,w))).value}async hSetNX(e,t,n){return(await this.storage.HSetNX({key:e,field:t,value:n,scope:this.scope},r(this,w))).success}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){let t=await this.storage.HGetAll({key:e,scope:this.scope},r(this,w));return t!==null?t.fieldValues:t}async hdel(e,t){return this.hDel(e,t)}async hDel(e,t){return(await this.storage.HDel({key:e,fields:t,scope:this.scope},r(this,w))).value}async hscan(e,t,n,o){return this.hScan(e,t,n,o)}async hScan(e,t,n,o){let s={key:e,cursor:t,pattern:n,count:o,scope:this.scope};return await this.storage.HScan(s,r(this,w))}async hkeys(e){return this.hKeys(e)}async hKeys(e){let t=await this.storage.HKeys({key:e,scope:this.scope},r(this,w));return t!==null?t.keys:t}async hincrby(e,t,n){return this.hIncrBy(e,t,n)}async hIncrBy(e,t,n){return(await this.storage.HIncrBy({key:e,field:t,value:n,scope:this.scope},r(this,w))).value}async hlen(e){return this.hLen(e)}async hLen(e){return(await this.storage.HLen({key:e,scope:this.scope})).value}async bitfield(e,...t){let n=[];for(let s=0;s<t.length;){let a=t[s],c={};switch(a){case"get":{if(s+2>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'get' command");c.get={encoding:t[s+1],offset:t[s+2].toString()},s+=3;break}case"set":{if(s+3>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'set' command");c.set={encoding:t[s+1],offset:t[s+2].toString(),value:t[s+3].toString()},s+=4;break}case"incrBy":{if(s+3>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'incrBy' command");c.incrBy={encoding:t[s+1],offset:t[s+2].toString(),increment:t[s+3].toString()},s+=4;break}case"overflow":{if(s+1>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'overflow' command");let m=t[s+1].toString();c.overflow={behavior:um(m)},s+=2;break}default:throw Error(`bitfield command parse failed; ${a} unrecognized (must be 'get', 'set', 'incrBy', or 'overflow')`)}n.push(c)}return(await this.storage.Bitfield({key:e,commands:n})).results}};w=new WeakMap,mi=new WeakMap;var pi=$s;function um(i){let e=i.toLowerCase();switch(e){case"wrap":return Js.BITFIELD_OVERFLOW_BEHAVIOR_WRAP;case"sat":return Js.BITFIELD_OVERFLOW_BEHAVIOR_SAT;case"fail":return Js.BITFIELD_OVERFLOW_BEHAVIOR_FAIL;default:throw Error(`unknown bitfield overflow behavior: ${e}`)}}var Et,gi=class{constructor(e){l(this,Et);d(this,Et,e)}async runJob(e){return(await u.schedulerPlugin.Schedule({action:{type:e.name,data:e.data},cron:"cron"in e?e.cron:void 0,when:"runAt"in e?e.runAt:void 0},r(this,Et))).id}async cancelJob(e){await u.schedulerPlugin.Cancel({id:e},r(this,Et))}async listJobs(){return(await u.schedulerPlugin.List({after:new Date(0),before:new Date(Date.now()+31536e7)},r(this,Et))).actions.map(t=>(p(t.request?.action,"Scheduled job is malformed"),"when"in t.request&&t.request.when!=null?{id:t.id,name:t.request.action.type,runAt:t.request.when,data:t.request.action.data}:{id:t.id,name:t.request.action.type,cron:t.request.cron??"",data:t.request.action}))}};Et=new WeakMap;import{FormFieldType as Lo}from"@devvit/protos";var Bn,fi=class{constructor(e){l(this,Bn);d(this,Bn,e)}async get(e){return(await this.getAll())[e]}async getAll(){let t=await u.settingsPlugin.GetSettings({},r(this,Bn));if(!t.installationSettings)throw new Error("Could not get installation settings");if(!t.appSettings)throw new Error("Could not get app settings");return cm(t),{...Ed(t.installationSettings.settings,u.installationSettings),...Ed(t.appSettings.settings,u.appSettings)}}};Bn=new WeakMap;function cm(i){if(!i.appSettings)throw new Error("Could not get app settings");for(let[e,t]of Object.entries(i.appSettings.settings)){let n=u.appSettings?.find(o=>o.type!=="group"&&o.name===e);n&&(n.type==="boolean"&&t.fieldType===Lo.STRING&&t.boolValue==null&&t.stringValue!=null?(t.fieldType=Lo.BOOLEAN,t.boolValue=!!t.stringValue,delete t.stringValue):n.type==="number"&&t.fieldType===Lo.STRING&&t.numberValue==null&&t.stringValue!=null&&(t.fieldType=Lo.NUMBER,t.numberValue=Number(t.stringValue),delete t.stringValue))}}function Ed(i,e){let t=Object.keys(i).reduce((n,o)=>(n[o]=Hs(i[o]),n),{});return e&&Td(t,e),t}function Td(i,e){for(let t of e)t.type==="group"?Td(i,t.fields):!(t.name in i)&&"defaultValue"in t&&(i[t.name]=t.defaultValue)}import{EffectType as _o,ToastAppearance as Rd}from"@devvit/protos";var Xe,hi,Un,jo,Ho=class{constructor(e){l(this,Xe,[]);l(this,hi);l(this,Un);l(this,jo,(e,t)=>{let n=t!==void 0?e:"",o=t!==void 0?t:e;r(this,Xe).push({type:_o.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:n,app:{message:o}}}})});d(this,hi,e),d(this,Un,{postMessage:r(this,jo)})}get webView(){return r(this,Un)}showForm(e,t){let n=u.formDefinitions.get(e);if(!n&&r(this,hi)){let a=r(this,hi).forms.get(e);a&&(n={form:a,onSubmit:()=>{}})}if(!n)throw new Error("Form does not exist. Make sure you have added it using Devvit.createForm at the root of your app.");let o=n.form instanceof Function?n.form(t??{}):n.form,s={fields:[],id:e,title:o.title,acceptLabel:o.acceptLabel,cancelLabel:o.cancelLabel,shortDescription:o.description};It(o.fields),s.fields=Le(o.fields),r(this,Xe).push({type:_o.EFFECT_SHOW_FORM,showForm:{form:s}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Rd.SUCCESS:Rd.NEUTRAL}:t={text:e},r(this,Xe).push({type:_o.EFFECT_SHOW_TOAST,showToast:{toast:t}})}navigateTo(e){let t;typeof e=="string"?t=new URL(e).toString():t=new URL(e.permalink,"https://www.reddit.com").toString(),r(this,Xe).push({type:_o.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}get __effects(){return r(this,Xe)}};Xe=new WeakMap,hi=new WeakMap,Un=new WeakMap,jo=new WeakMap;function ke({metadata:i,ui:e,hooks:t,reconciler:n}){let o=new ui(i),s=new di(i),a=new pi(i),c=xd(a,n?n.state:{}),m=new gi(i),h=new fi(i),v=e?new Ho(n):void 0,y=new li(i),P=new si,b=new ci(i),A=t&&n?pd(n):void 0,U=t&&n?md(n):void 0,M=t&&n?cd(n):void 0,Y=t&&n?ud(n):void 0;return{modLog:o,kvStore:s,redis:a,scheduler:m,settings:h,media:y,assets:P,realtime:b,get useForm(){return M??(()=>{throw new Error("useForm() is unavailable")})},get cache(){return c??(()=>{throw new Error("cache() is unavailable")})},get useState(){return A??(()=>{throw new Error("useState() is unavailable")})},get useInterval(){return U??(()=>{throw new Error("useInterval() is unavailable")})},get useChannel(){return Y??(()=>{throw new Error("useChannel() is unavailable")})},get ui(){if(!v)throw new Error("ui client is not available");return v}}}var Od={name:"@devvit/public-api",version:"0.12.0-dev",license:"BSD-3-Clause",repository:{type:"git",url:"https://developers.reddit.com/"},type:"module",exports:{".":"./dist/index.js","./package.json":"./package.json","./*":"./dist/*"},main:"./dist/index.js",files:["dist/**"],scripts:{build:"yarn build:icon-types && yarn build:semantic-colors && tsc && cp -af devvit.tsconfig.json dist/ && yarn build:types && yarn build:min && yarn build:unmin","build:icon-types":"make-icons src/types/icons.ts","build:min":"esbuild --bundle --sourcemap=linked --target=es2020 --format=esm --metafile=dist/meta.min.json --outfile=dist/public-api.min.js --external:@devvit/protos --minify src/index.ts","build:semantic-colors":"node scripts/make-semantic-colors.js","build:types":"api-extractor run && sed -ne '/declare global {/,$ p' src/devvit/Devvit.ts >> dist/public-api.d.ts","build:unmin":"esbuild --bundle --sourcemap=inline --target=es2020 --format=iife --metafile=dist/meta.json --outfile=dist/public-api.iife.js --global-name=devvitPublicAPI src/index.ts",clean:"rm -rf .turbo api-extractor coverage dist src/devvit/internals/semanticColors.ts src/types/icons.ts || :",clobber:"yarn clean && rm -rf node_modules",dev:"tsc -w","dev:build":"chokidar ./src ../shared-types/dist --command 'yarn build' --ignore './src/types/icons.ts' --ignore './src/devvit/internals/semanticColors.ts'",lint:"redlint .","lint:fix":"yarn lint --fix",prepublishOnly:"publish-package-json",test:"yarn test:unit && yarn test:types && yarn test:size","test:size":"filesize","test:types":"tsc --noEmit","test:unit":"vitest run","test:unit-with-coverage":"vitest run --coverage"},types:"./dist/index.d.ts",dependencies:{"@devvit/metrics":"0.12.0-dev","@devvit/protos":"0.12.0-dev","@devvit/shared-types":"0.12.0-dev","base64-js":"1.5.1","clone-deep":"4.0.1",moderndash:"4.0.0"},devDependencies:{"@ampproject/filesize":"4.3.0","@devvit/repo-tools":"0.12.0-dev","@devvit/tsconfig":"0.12.0-dev","@microsoft/api-extractor":"7.41.0","@reddit/faceplate-ui":"18.0.1","@types/clone-deep":"4.0.1","@vitest/coverage-c8":"0.32.0","chokidar-cli":"3.0.0",esbuild:"0.23.0",eslint:"9.11.1",typescript:"5.3.2",vitest:"1.6.0"},publishConfig:{directory:"dist"},filesize:{"dist/public-api.min.js":{gzip:"62 KB",none:"218 KB"}},source:"./src/index.ts"};function re(i,e,t){let n=i[S.Subreddit]?.values[0];p(n,"subreddit is missing from Context");let o=i[S.SubredditName]?.values[0],s=i[S.AppUser]?.values[0],a=i[S.App]?.values[0],c=i[S.Version]?.values[0],m=i[S.User]?.values[0],h=pm(i);return{get appAccountId(){return p(s,"appAccountId is missing from Context"),s},subredditId:n,subredditName:o,userId:m,postId:e,commentId:t,appName:a,appVersion:c,debug:h,metadata:i,toJSON(){return{appAccountId:s,appName:a,appVersion:c,subredditId:n,subredditName:o,userId:m,postId:e,commentId:t,debug:h,metadata:i}}}}function pm(i){let e={blocks:void 0,emitSnapshots:void 0,emitState:void 0,realtime:void 0,runtime:void 0,surface:void 0,useAsync:void 0,payments:void 0,bootstrap:void 0,webView:void 0},t={};for(let o in e)t[o.toLowerCase()]=o;let n={};for(let o of(i[S.Debug]?.values??[]).join().split(",")){let[s,a]=o.split("=");s&&(s=s.trim(),a=a?.trim(),s.toLowerCase()in t&&(s=t[s.toLowerCase()]),n[s]??(n[s]=a||"true"))}return i[S.Debug]&&console.info(`[api] @devvit/public-api v${Od.version} ${Object.entries(n).map(([o,s])=>`${o}=${s}`).join(" ")}`),{...n}}function Md(i){return i.flatMap(e=>e.type==="group"?Md(e.fields):e)}async function Vo(i,e,t){if(!e)throw new Error("Settings were not defined.");let n={success:!0,errors:{}},o=qe(i.fieldValues),s=Md(e);return await Promise.all(s.map(async a=>{let c=a.name;if(c&&a.onValidate){let m=o[c],h=a.onValidate,v=Object.assign(ke({metadata:t}),re(t)),y=await h({value:m,isEditing:i.editing},v);y&&(n.success=!1,n.errors[c]=y)}})),gm.fromJSON(n)}async function ym(){if(!u.appSettings)throw new Error("App settings were not defined.");return hm.fromJSON({fields:{fields:Le(u.appSettings)}})}async function bm(i,e){return Vo(i,u.appSettings,e)}function Bd(i){i.provides(fm),O("GetAppSettingsFields",ym),O("ValidateAppForm",bm)}import{CustomPostDefinition as xm,RenderPostResponse as Fm}from"@devvit/protos";import{BlockRenderEventType as da,EffectType as Kd}from"@devvit/protos";function yi(i){return i.__effects}function Ud(){let i=new Set;return e=>{let t=e,n=1;for(;i.has(t);)t=`${e}.${n++}`;return i.add(t),t}}import{BlockActionType as aa,BlockAvatarBackground as Jd,BlockAvatarFacing as zd,BlockAvatarSize as Qe,BlockBorderWidth as zo,BlockButtonAppearance as Ye,BlockButtonSize as Ys,BlockGap as qo,BlockHorizontalAlignment as ea,BlockIconSize as $o,BlockImageResizeMode as Dn,BlockPadding as Nn,BlockRadius as Ln,BlockSpacerShape as ta,BlockSpacerSize as Ko,BlockStackDirection as ia,BlockTextOutline as na,BlockTextOverflow as ra,BlockTextSize as vi,BlockTextStyle as oa,BlockTextWeight as qd,BlockType as Re,BlockVerticalAlignment as sa}from"@devvit/protos";var Ks={"alienblue-100":"#DCE2FB","alienblue-200":"#B8C5FC","alienblue-25":"#F7F8FD","alienblue-300":"#90A9FD","alienblue-400":"#648EFC","alienblue-50":"#EEF0FB","alienblue-500":"#1870F4","alienblue-600":"#115BCA","alienblue-700":"#0A449B","alienblue-75":"#E6E9FB","alienblue-800":"#0A2F6C","alienblue-900":"#0A1A3F","alienblue-950":"#07102B","berrypurple-100":"#F3DAFB","berrypurple-200":"#EAB3FD","berrypurple-25":"#FBF6FD","berrypurple-300":"#DE8BFF","berrypurple-400":"#CF5FFF","berrypurple-50":"#F8EDFC","berrypurple-500":"#BC0EFF","berrypurple-600":"#9B00D4","berrypurple-700":"#7600A3","berrypurple-75":"#F6E4FB","berrypurple-800":"#520472","berrypurple-900":"#300643","berrypurple-950":"#20042A",black:"#000000","black-opacity-0":"#00000000","black-opacity-10":"#00000019","black-opacity-15":"#00000026","black-opacity-20":"#00000033","black-opacity-25":"#0000003F","black-opacity-33":"#00000054","black-opacity-5":"#0000000C","black-opacity-50":"#0000007F","black-opacity-60":"#00000099","black-opacity-67":"#000000AA","black-opacity-80":"#000000CC","black-opacity-90":"#000000E5","brown-100":"#F1DFCF","brown-200":"#E9BE95","brown-25":"#FBF7F4","brown-300":"#DC9D5D","brown-400":"#BA854E","brown-50":"#F7EFE9","brown-500":"#9A6D3F","brown-600":"#7B5631","brown-700":"#5D4023","brown-75":"#F4E7DC","brown-800":"#3F2C19","brown-900":"#221A11","brown-950":"#15100A","coolgray-100":"#DBE4E9","coolgray-150":"#C9D7DE","coolgray-200":"#B7CAD4","coolgray-25":"#F6F8F9","coolgray-250":"#A4BDCA","coolgray-300":"#97AFBC","coolgray-350":"#8BA2AD","coolgray-400":"#7F949F","coolgray-450":"#748791","coolgray-50":"#EEF1F3","coolgray-500":"#667780","coolgray-525":"#576F76","coolgray-550":"#5C6C74","coolgray-600":"#536168","coolgray-650":"#48545B","coolgray-700":"#3D494E","coolgray-75":"#E5EBEE","coolgray-750":"#333D42","coolgray-800":"#2A3236","coolgray-850":"#21272A","coolgray-900":"#181C1F","coolgray-950":"#0E1113","global-black":{light:"#000000",dark:"#000000"},"global-brand-orangered":{light:"#FF4500",dark:"#FF4500"},"global-white":{light:"#FFFFFF",dark:"#FFFFFF"},"kiwigreen-100":"#A8F5A0","kiwigreen-200":"#58E15B","kiwigreen-25":"#EBFDE7","kiwigreen-300":"#00C61C","kiwigreen-400":"#01A816","kiwigreen-50":"#DDF8D7","kiwigreen-500":"#008A10","kiwigreen-600":"#016E0B","kiwigreen-700":"#005306","kiwigreen-75":"#CAF5C2","kiwigreen-800":"#033902","kiwigreen-900":"#0D2005","kiwigreen-950":"#081404","lightblue-100":"#CAE7FB","lightblue-200":"#87D0FD","lightblue-25":"#F3F9FD","lightblue-300":"#02B9FB","lightblue-400":"#029DD5","lightblue-50":"#E6F3FC","lightblue-500":"#007FAE","lightblue-600":"#01668D","lightblue-700":"#014D6B","lightblue-75":"#D9EDFB","lightblue-800":"#03354B","lightblue-900":"#051E2B","lightblue-950":"#04131A","lime-100":"#B7F28E","lime-200":"#90DA58","lime-25":"#EEFDDC","lime-300":"#6DBF01","lime-400":"#5BA200","lime-50":"#E0F8C8","lime-500":"#4A8500","lime-600":"#3A6A00","lime-700":"#2A5000","lime-75":"#CEF5AD","lime-800":"#1E3702","lime-900":"#151E05","lime-950":"#0D1304","mintgreen-100":"#9BF5D9","mintgreen-200":"#00E2B7","mintgreen-25":"#E7FDF5","mintgreen-300":"#00C29D","mintgreen-400":"#01A484","mintgreen-50":"#D7F8EC","mintgreen-500":"#01876D","mintgreen-600":"#006C56","mintgreen-700":"#015140","mintgreen-75":"#C0F5E3","mintgreen-800":"#00382B","mintgreen-900":"#032019","mintgreen-950":"#03140F","orangered-100":"#FCDBCF","orangered-200":"#FDB498","orangered-25":"#FDF6F4","orangered-300":"#FF895D","orangered-400":"#FF4500","orangered-50":"#FCEEE8","orangered-500":"#D93900","orangered-600":"#AE2C00","orangered-700":"#842100","orangered-75":"#FBE5DC","orangered-800":"#591B02","orangered-900":"#2F1405","orangered-950":"#1C0D04","periwinkle-100":"#E6DFFB","periwinkle-200":"#CDBEFD","periwinkle-25":"#F9F7FD","periwinkle-300":"#B29FFF","periwinkle-400":"#9580FF","periwinkle-50":"#F2EFFC","periwinkle-500":"#6A5CFF","periwinkle-600":"#523DFF","periwinkle-700":"#4001EA","periwinkle-75":"#ECE7FB","periwinkle-800":"#250AA6","periwinkle-900":"#160E5B","periwinkle-950":"#0C083F","poopbrown-100":"#FEEEDD","poopbrown-200":"#F6DDC3","poopbrown-300":"#EECCAA","poopbrown-400":"#CAA075","poopbrown-50":"#FEF7EE","poopbrown-500":"#9A6D3F","poopbrown-600":"#6E4924","poopbrown-700":"#54371A","poopbrown-800":"#3B2510","poopbrown-900":"#29190A","poopbrown-950":"#110B04","puregray-100":"#F2F2F2","puregray-150":"#EBEBEB","puregray-200":"#E4E4E4","puregray-250":"#DDDDDD","puregray-300":"#D6D6D6","puregray-350":"#C3C3C3","puregray-400":"#ACACAC","puregray-450":"#919191","puregray-50":"#F8F8F8","puregray-500":"#767676","puregray-550":"#5C5C5C","puregray-600":"#434343","puregray-650":"#393939","puregray-700":"#303030","puregray-750":"#272727","puregray-800":"#1E1E1E","puregray-850":"#181818","puregray-900":"#131313","puregray-950":"#080808","red-100":"#FBDBD4","red-200":"#FDB3A4","red-25":"#FDF6F5","red-300":"#FF8773","red-400":"#FF4F40","red-50":"#FCEEEA","red-500":"#EB001F","red-600":"#BC0117","red-700":"#90000F","red-75":"#FBE4DF","red-800":"#650405","red-900":"#340F05","red-950":"#1F0B04","sakurapink-100":"#FBD9EB","sakurapink-200":"#FDAEDA","sakurapink-25":"#FDF6F9","sakurapink-300":"#FF7ECA","sakurapink-400":"#FF38BB","sakurapink-50":"#FCEDF4","sakurapink-500":"#DE019F","sakurapink-600":"#B2007F","sakurapink-700":"#880060","sakurapink-75":"#FBE3EF","sakurapink-800":"#5F0443","sakurapink-900":"#380626","sakurapink-950":"#250419",transparent:"transparent",white:"#ffffff","white-opacity-0":"#FFFFFF00","white-opacity-10":"#FFFFFF19","white-opacity-15":"#FFFFFF26","white-opacity-20":"#FFFFFF33","white-opacity-25":"#FFFFFF3F","white-opacity-5":"#FFFFFF0C","white-opacity-50":"#FFFFFF7F","yellow-100":"#FFE284","yellow-200":"#FFBF0B","yellow-25":"#FFF9E0","yellow-300":"#D8A100","yellow-400":"#B78800","yellow-50":"#FFF3C0","yellow-500":"#977000","yellow-600":"#785800","yellow-700":"#5B4200","yellow-75":"#FFEAA2","yellow-800":"#3F2D00","yellow-900":"#231A03","yellow-950":"#161003","yelloworange-100":"#FCDCC8","yelloworange-200":"#FDB586","yelloworange-25":"#FDF7F3","yelloworange-300":"#FF8A35","yelloworange-400":"#E46C00","yelloworange-50":"#FCEEE6","yelloworange-500":"#BD5800","yelloworange-600":"#974500","yelloworange-700":"#733300","yelloworange-75":"#FBE5D7","yelloworange-800":"#4E2402","yelloworange-900":"#2A1705","yelloworange-950":"#1A0E04","action-downvote":{light:"#6A5CFF",dark:"#6A5CFF"},"action-upvote":{light:"#D93900",dark:"#D93900"},"ai-background-weaker":{light:"#E7FDF5",dark:"#00382B"},"ai-plain":{light:"#006C56",dark:"#01A484"},"ai-plain-hover":{light:"#015140",dark:"#00C29D"},"alert-caution":{light:"#977000",dark:"#977000"},"avatar-gradient":{light:"",dark:""},"brand-background":{light:"#D93900",dark:"#D93900"},"brand-background-hover":{light:"#AE2C00",dark:"#AE2C00"},"brand-gradient-active":{light:"",dark:""},"brand-gradient-active-highlight":{light:"",dark:""},"brand-gradient-default":{light:"",dark:""},"brand-gradient-default-highlight":{light:"",dark:""},"brand-gradient-hover":{light:"",dark:""},"brand-gradient-hover-highlight":{light:"",dark:""},"brand-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"category-live":{light:"#D93900",dark:"#D93900"},"category-nsfw":{light:"#DE019F",dark:"#DE019F"},"category-spoiler":{light:"#131313",dark:"#F2F2F2"},"caution-background":{light:"#FFBF0B",dark:"#D8A100"},"caution-background-hover":{light:"#D8A100",dark:"#FFBF0B"},"caution-onBackground":{light:"#000000",dark:"#000000"},"caution-plain":{light:"#785800",dark:"#FFBF0B"},"caution-plain-hover":{light:"#5B4200",dark:"#FFE284"},"danger-background":{light:"#EB001F",dark:"#BC0117"},"danger-background-disabled":{light:"#FDB3A4",dark:"#340F05"},"danger-background-hover":{light:"#BC0117",dark:"#EB001F"},"danger-background-weaker":{light:"#FBDBD4",dark:"#650405"},"danger-content":{light:"#BC0117",dark:"#FF4F40"},"danger-content-default":{light:"#ffffff",dark:"#ffffff"},"danger-content-hover":{light:"#90000F",dark:"#FF8773"},"danger-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"danger-plain":{light:"#BC0117",dark:"#FF8773"},"danger-plain-hover":{light:"#90000F",dark:"#FDB3A4"},"downvote-background":{light:"#6A5CFF",dark:"#6A5CFF"},"downvote-background-disabled":{light:"#6a5cff4d",dark:"#6a5cff4d"},"downvote-background-hover":{light:"#523DFF",dark:"#523DFF"},"downvote-content":{light:"#523DFF",dark:"#9580FF"},"downvote-content-weak":{light:"#6A5CFF",dark:"#6A5CFF"},"downvote-disabled":{light:"#523DFF4c",dark:"#9580FF4c"},"downvote-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"downvote-onStrongScrim":{light:"#B29FFF",dark:"#B29FFF"},"downvote-onStrongScrim-disabled":{light:"#b29fff4d",dark:"#b29fff4d"},"downvote-onStrongScrim-weaker":{light:"#9580FF",dark:"#9580FF"},"downvote-plain":{light:"#523DFF",dark:"#9580FF"},"downvote-plain-disabled":{light:"#523dff4d",dark:"#9580ff4d"},"downvote-plain-weaker":{light:"#6A5CFF",dark:"#6A5CFF"},"elevation-large1":{light:"#0000003F",dark:"#0000007F"},"elevation-large2":{light:"#00000026",dark:"#00000033"},"elevation-medium1":{light:"#0000003F",dark:"#0000007F"},"elevation-medium2":{light:"#00000019",dark:"#00000033"},"elevation-small":{light:"#00000026",dark:"#00000054"},"elevation-xsmall":{light:"#0000003F",dark:"#000000AA"},favorite:{light:"#977000",dark:"#B78800"},"global-admin":{light:"#D93900",dark:"#D93900"},"global-alienblue":{light:"#1870F4",dark:"#1870F4"},"global-darkblue":{light:"#2A3236",dark:"#2A3236"},"global-focus":{light:"#029DD5",dark:"#007FAE"},"global-gold":{light:"#B78800",dark:"#D8A100"},"global-moderator":{light:"#008A10",dark:"#008A10"},"global-nsfw":{light:"#DE019F",dark:"#DE019F"},"global-offline":{light:"#667780",dark:"#667780"},"global-online":{light:"#00C61C",dark:"#00C61C"},"global-orangered":{light:"#FF4500",dark:"#FF4500"},"global-stars":{light:"#977000",dark:"#D8A100"},"gradient-media":{light:"",dark:""},"gradient-media-strong":{light:"",dark:""},"identity-admin":{light:"#D93900",dark:"#D93900"},"identity-coins":{light:"#B78800",dark:"#B78800"},"identity-moderator":{light:"#008A10",dark:"#008A10"},"identity-self":{light:"#01876D",dark:"#01876D"},"interactive-background-disabled":{light:"#0000000C",dark:"#FFFFFF0C"},"interactive-content-disabled":{light:"#0000003F",dark:"#FFFFFF3F"},"interactive-focused":{light:"#007FAE",dark:"#007FAE"},"interactive-pressed":{light:"#00000026",dark:"#FFFFFF26"},"inverted-interactive-background-disabled":{light:"#FFFFFF0C",dark:"#0000000C"},"inverted-interactive-content-disabled":{light:"#FFFFFF3F",dark:"#0000003F"},"inverted-interactive-pressed":{light:"#FFFFFF26",dark:"#00000026"},"inverted-neutral-background":{light:"#0E1113",dark:"#FFFFFF"},"inverted-neutral-background-hover":{light:"#181C1F",dark:"#F6F8F9"},"inverted-neutral-border":{light:"#FFFFFF33",dark:"#00000033"},"inverted-neutral-content":{light:"#B7CAD4",dark:"#333D42"},"inverted-neutral-content-strong":{light:"#EEF1F3",dark:"#181C1F"},"inverted-secondary-background":{light:"#2A3236",dark:"#E5EBEE"},"inverted-secondary-background-hover":{light:"#333D42",dark:"#DBE4E9"},"inverted-secondary-background-selected":{light:"#3D494E",dark:"#C9D7DE"},"inverted-secondary-onBackground":{light:"#FFFFFF",dark:"#000000"},"inverted-secondary-plain":{light:"#DBE4E9",dark:"#181C1F"},"inverted-secondary-plain-hover":{light:"#FFFFFF",dark:"#000000"},"media-background":{light:"#00000099",dark:"#00000099"},"media-background-hover":{light:"#000000cc",dark:"#000000cc"},"media-background-selected":{light:"#000000cc",dark:"#000000cc"},"media-border-selected":{light:"#FFFFFF",dark:"#FFFFFF"},"media-border-weak":{light:"#FFFFFF19",dark:"#FFFFFF19"},"media-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"media-onBackground-disabled":{light:"#FFFFFF3F",dark:"#FFFFFF3F"},"media-onBackground-weak":{light:"#E5EBEE",dark:"#E5EBEE"},"media-onbackground":{light:"#ffffff",dark:"#ffffff"},"media-onbackground-disabled":{light:"#ffffff3f",dark:"#ffffff3f"},"media-onbackground-weak":{light:"#B7CAD4",dark:"#B7CAD4"},"neutral-background":{light:"#FFFFFF",dark:"#0E1113"},"neutral-background-container":{light:"#F6F8F9",dark:"#181C1F"},"neutral-background-container-hover":{light:"#EEF1F3",dark:"#21272A"},"neutral-background-container-strong":{light:"#EEF1F3",dark:"#21272A"},"neutral-background-container-strong-hover":{light:"#E5EBEE",dark:"#2A3236"},"neutral-background-gilded":{light:"#FFF9E0",dark:"#181C1F"},"neutral-background-gilded-hover":{light:"#FFF3C0",dark:"#21272A"},"neutral-background-hover":{light:"#F6F8F9",dark:"#181C1F"},"neutral-background-medium":{light:"#F8F8F8",dark:"#131313"},"neutral-background-pinned":{light:"#FFFFFF",dark:"#0E1113"},"neutral-background-selected":{light:"#E5EBEE",dark:"#2A3236"},"neutral-background-strong":{light:"#FFFFFF",dark:"#181C1F"},"neutral-background-strong-hover":{light:"#F6F8F9",dark:"#21272A"},"neutral-background-weak":{light:"#F6F8F9",dark:"#000000"},"neutral-background-weak-hover":{light:"#EEF1F3",dark:"#0E1113"},"neutral-border":{light:"#00000033",dark:"#FFFFFF33"},"neutral-border-medium":{light:"#0000007F",dark:"#FFFFFF7F"},"neutral-border-strong":{light:"#181C1F",dark:"#F6F8F9"},"neutral-border-weak":{light:"#00000019",dark:"#FFFFFF19"},"neutral-content":{light:"#333D42",dark:"#B7CAD4"},"neutral-content-disabled":{light:"#D6D6D6",dark:"#303030"},"neutral-content-strong":{light:"#181C1F",dark:"#EEF1F3"},"neutral-content-weak":{light:"#5C6C74",dark:"#8BA2AD"},offline:{light:"#767676",dark:"#767676"},online:{light:"#01A816",dark:"#01A816"},"opacity-08":{light:"#13131314",dark:"#13131314"},"opacity-50":{light:"#0000007f",dark:"#F2F2F27f"},"opacity-highlight":{light:"",dark:""},pizzaRed:{light:"#ef5350",dark:"#c62828"},primary:{light:"#115BCA",dark:"#648EFC"},"primary-background":{light:"#0A449B",dark:"#115BCA"},"primary-background-hover":{light:"#0A2F6C",dark:"#1870F4"},"primary-background-selected":{light:"#0A1A3F",dark:"#648EFC"},"primary-border":{light:"#0A449B",dark:"#648EFC"},"primary-border-hover":{light:"#0A2F6C",dark:"#90A9FD"},"primary-hover":{light:"#0A449B",dark:"#90A9FD"},"primary-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"primary-onBackground-selected":{light:"#FFFFFF",dark:"#000000"},"primary-plain":{light:"#0A449B",dark:"#648EFC"},"primary-plain-hover":{light:"#0A2F6C",dark:"#90A9FD"},"primary-plain-visited":{light:"#7600A3",dark:"#CF5FFF"},"primary-visited":{light:"#9B00D4",dark:"#CF5FFF"},scrim:{light:"#00000099",dark:"#00000099"},"scrim-background":{light:"#00000099",dark:"#00000099"},"scrim-background-strong":{light:"#000000CC",dark:"#000000CC"},"scrim-gradient":{light:"",dark:""},"scrim-strong":{light:"#000000cc",dark:"#000000cc"},secondary:{light:"#21272A",dark:"#DBE4E9"},"secondary-background":{light:"#E5EBEE",dark:"#2A3236"},"secondary-background-hover":{light:"#DBE4E9",dark:"#333D42"},"secondary-background-selected":{light:"#C9D7DE",dark:"#3D494E"},"secondary-hover":{light:"#000000",dark:"#ffffff"},"secondary-onBackground":{light:"#000000",dark:"#FFFFFF"},"secondary-plain":{light:"#181C1F",dark:"#DBE4E9"},"secondary-plain-hover":{light:"#000000",dark:"#FFFFFF"},"secondary-plain-weak":{light:"#5C6C74",dark:"#8BA2AD"},"secondary-weak":{light:"#576F76",dark:"#748791"},"success-background":{light:"#008A10",dark:"#016E0B"},"success-background-hover":{light:"#016E0B",dark:"#008A10"},"success-content":{light:"#016E0B",dark:"#01A816"},"success-hover":{light:"#005306",dark:"#00C61C"},"success-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"success-plain":{light:"#016E0B",dark:"#00C61C"},"success-plain-hover":{light:"#005306",dark:"#58E15B"},"tone-1":{light:"#131313",dark:"#F2F2F2"},"tone-2":{light:"#434343",dark:"#ACACAC"},"tone-3":{light:"#ACACAC",dark:"#434343"},"tone-4":{light:"#E4E4E4",dark:"#303030"},"tone-5":{light:"#F2F2F2",dark:"#1E1E1E"},"tone-6":{light:"#F8F8F8",dark:"#131313"},"tone-7":{light:"#ffffff",dark:"#080808"},"transparent-background-hover":{light:"#74879119",dark:"#66778019"},"ui-canvas":{light:"#F2F2F2",dark:"#080808"},"ui-modalbackground":{light:"#FFFFFF",dark:"#181C1F"},"upvote-background":{light:"#D93900",dark:"#D93900"},"upvote-background-disabled":{light:"#d939004d",dark:"#d939004d"},"upvote-background-hover":{light:"#AE2C00",dark:"#AE2C00"},"upvote-content":{light:"#AE2C00",dark:"#FF4500"},"upvote-content-weak":{light:"#FF4500",dark:"#FF4500"},"upvote-disabled":{light:"#AE2C004c",dark:"#FF45004c"},"upvote-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"upvote-onStrongScrim":{light:"#FF895D",dark:"#FF895D"},"upvote-onStrongScrim-disabled":{light:"#ff895d4d",dark:"#ff895d4d"},"upvote-onStrongScrim-weaker":{light:"#FF4500",dark:"#FF4500"},"upvote-plain":{light:"#AE2C00",dark:"#FF895D"},"upvote-plain-disabled":{light:"#ae2c004d",dark:"#ff895d4d"},"upvote-plain-weaker":{light:"#FF4500",dark:"#FF4500"},"warning-background":{light:"#B78800",dark:"#B78800"},"warning-background-hover":{light:"#977000",dark:"#D8A100"},"warning-content":{light:"#785800",dark:"#B78800"},"warning-content-hover":{light:"#5B4200",dark:"#D8A100"},"warning-onBackground":{light:"#000000",dark:"#000000"}};var Dd={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",transparent:"#FFFFFF00",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},Nd=i=>!!i.match(/^(#[0-9a-fA-F]{3,8}).*/),Ld=i=>i in Ks,Zs=i=>i in Dd,_d=i=>!!i.match(/^rgba?\(.*/),Hd=i=>!!i.match(/^hsla?\(.*/),jd=(i,e="light")=>{if(Zs(i))return Wo(i);let n=Ks[i];return typeof n=="string"?n:n[e]},Wo=i=>Dd[i]??i,Vd=i=>{let[e,t,n,o]=i.replace(/^rgba?\(|\s+|\)$/g,"").split(",");if(!e||!t||!n)return i;let a=[...[e,t,n].map(m=>parseFloat(m))];if(o){let m=parseFloat(o),h=Math.round(m*255);a.push(h)}return`#${a.map(m=>m.toString(16).padStart(2,"0")).join("")}`};import{BlockStackDirection as Go}from"@devvit/protos";var Xs={stackParentLayout:{hasHeight:!0,hasWidth:!0,direction:Go.UNRECOGNIZED,alignment:void 0}};function Gd(i,e,t){if(!e)return{hasHeight:!1,hasWidth:!1};let{growDirection:n,stretchDirection:o}=vm(i?.grow,e.direction,e.alignment),s=t?.height?.value?.value||t?.height?.min?.value||Wd(2,n,o,e.hasHeight),a=t?.width?.value?.value||t?.width?.min?.value||Wd(1,n,o,e.hasWidth);return{hasHeight:!!s,hasWidth:!!a}}function Wd(i,e,t,n){return e===i&&n||t===i&&n}function vm(i,e,t){let n=e===Go.STACK_VERTICAL||e===Go.UNRECOGNIZED,o=e===Go.STACK_HORIZONTAL,s=0;o&&i?s=1:n&&i&&(s=2);let a=t===void 0||t.horizontal===void 0,c=t===void 0||t.vertical===void 0,m=o?!!c:n?!!a:!1,h=0;return o&&m?h=2:n&&m&&(h=1),{growDirection:s,stretchDirection:h}}import{BlockSizeUnit as Tt,BlockStackDirection as Jo}from"@devvit/protos";function bi(i){if(i==null)return;if(typeof i=="number")return{value:i,unit:Tt.SIZE_UNIT_PERCENT};let e=i.match(/^(\d+(?:\.\d+)?)(px|%)?$/);if(e==null)return;let t=Tt.SIZE_UNIT_PERCENT;return e.at(2)==="px"&&(t=Tt.SIZE_UNIT_PIXELS),{value:Number.parseFloat(e[1]),unit:t}}function km(i,e){return(i.width?.value?.unit===Tt.SIZE_UNIT_PERCENT||i.width?.min?.unit===Tt.SIZE_UNIT_PERCENT)&&(e.direction===Jo.STACK_HORIZONTAL||e.direction===Jo.STACK_DEPTH)&&(e.hasWidth||(i.width=void 0)),(i.height?.value?.unit===Tt.SIZE_UNIT_PERCENT||i.height?.min?.unit===Tt.SIZE_UNIT_PERCENT)&&(e.direction===Jo.STACK_VERTICAL||e.direction===Jo.STACK_DEPTH)&&(e.hasHeight||(i.height=void 0)),i}function Qs(i,e){if(i){let t=i.width!=null||i.minWidth!=null||i.maxWidth!=null,n=i.height!=null||i.minHeight!=null||i.maxHeight!=null;if(t||n||i.grow!=null){let o={width:t?{value:bi(i.width),min:bi(i.minWidth),max:bi(i.maxWidth)}:void 0,height:n?{value:bi(i.height),min:bi(i.minHeight),max:bi(i.maxHeight)}:void 0,grow:i.grow};return e.stackParentLayout&&(o=km(o,e.stackParentLayout)),o}}}var $d="data-",Cm=new Set(["onPress","onMessage"]),Pm=new Map([["onPress",aa.ACTION_CLICK],["onMessage",aa.ACTION_WEBVIEW]]),_n,ki=class{constructor(e=()=>{}){l(this,_n);d(this,_n,e)}createBlocksElementOrThrow({type:e,props:t,children:n}){let o=this.createBlocksElement({type:e,props:t,children:n},Xs);if(!o)throw new Error(`Could not create block of type ${e}`);return o}createBlocksElement({type:e,props:t,children:n},o){switch(e){case"blocks":return this.makeRoot(t,...n);case"hstack":return this.makeHStack(t,o,...n);case"vstack":return this.makeVStack(t,o,...n);case"zstack":return this.makeZStack(t,o,...n);case"text":return this.makeText(t,o,...n);case"button":return this.makeButton(t,o,...n);case"image":return this.makeImage(t,o);case"spacer":return this.makeSpacer(t,o);case"icon":return this.makeIcon(t,o);case"avatar":return this.makeAvatar(t,o);case"webview":return this.makeWebView(t,o);case"__fragment":throw new Error("root fragment is not supported - use 'blocks' instead")}}makeRootHeight(e){switch(e){case"regular":return 320;case"tall":return 512}}makeBlockPadding(e){switch(e){case"none":return Nn.PADDING_NONE;case"xsmall":return Nn.PADDING_XSMALL;case"small":return Nn.PADDING_SMALL;case"medium":return Nn.PADDING_MEDIUM;case"large":return Nn.PADDING_LARGE}}makeBlockRadius(e){switch(e){case"none":return Ln.RADIUS_NONE;case"small":return Ln.RADIUS_SMALL;case"medium":return Ln.RADIUS_MEDIUM;case"large":return Ln.RADIUS_LARGE;case"full":return Ln.RADIUS_FULL}}makeBlockGap(e){switch(e){case"none":return qo.GAP_NONE;case"small":return qo.GAP_SMALL;case"medium":return qo.GAP_MEDIUM;case"large":return qo.GAP_LARGE}}makeBlockAlignment(e){if(e===void 0)return;let t,n;if(e.includes("top")?t=sa.ALIGN_TOP:e.includes("middle")?t=sa.ALIGN_MIDDLE:e.includes("bottom")&&(t=sa.ALIGN_BOTTOM),e.includes("start")?n=ea.ALIGN_START:e.includes("center")?n=ea.ALIGN_CENTER:e.includes("end")&&(n=ea.ALIGN_END),t!==void 0||n!==void 0)return{vertical:t,horizontal:n}}makeBlockBorder(e,t,n,o){if(!e&&!t)return;let s;switch(e){case"none":s=zo.BORDER_WIDTH_NONE;break;case"thin":s=zo.BORDER_WIDTH_THIN;break;case"thick":s=zo.BORDER_WIDTH_THICK;break;default:s=zo.BORDER_WIDTH_THIN;break}let a=t??"neutral-border-weak",c=this.getThemedColors(a,n,o);return{width:s,color:c?.light,colors:c}}makeBlockTextSize(e){switch(e){case"xsmall":return vi.TEXT_SIZE_XSMALL;case"small":return vi.TEXT_SIZE_SMALL;case"medium":return vi.TEXT_SIZE_MEDIUM;case"large":return vi.TEXT_SIZE_LARGE;case"xlarge":return vi.TEXT_SIZE_XLARGE;case"xxlarge":return vi.TEXT_SIZE_XXLARGE}}makeBlockTextStyle(e){switch(e){case"body":return oa.TEXT_STYLE_BODY;case"metadata":return oa.TEXT_STYLE_METADATA;case"heading":return oa.TEXT_STYLE_HEADING}}makeBlockTextOutline(e){switch(e){case"none":return na.TEXT_OUTLINE_NONE;case"thin":return na.TEXT_OUTLINE_THIN;case"thick":return na.TEXT_OUTLINE_THICK}}makeBlockTextWeight(e){switch(e){case"regular":return qd.TEXT_WEIGHT_REGULAR;case"bold":return qd.TEXT_WEIGHT_BOLD}}makeBlockTextOverflow(e){switch(e){case"clip":return ra.TEXT_OVERFLOW_CLIP;case"ellipsis":return ra.TEXT_OVERFLOW_ELLIPSE}return ra.TEXT_OVERFLOW_ELLIPSE}makeBlockButtonAppearance(e){switch(e){case"secondary":return Ye.BUTTON_APPEARANCE_SECONDARY;case"primary":return Ye.BUTTON_APPEARANCE_PRIMARY;case"plain":return Ye.BUTTON_APPEARANCE_PLAIN;case"bordered":return Ye.BUTTON_APPEARANCE_BORDERED;case"media":return Ye.BUTTON_APPEARANCE_MEDIA;case"destructive":return Ye.BUTTON_APPEARANCE_DESTRUCTIVE;case"caution":return Ye.BUTTON_APPEARANCE_CAUTION;case"success":return Ye.BUTTON_APPEARANCE_SUCCESS}}makeBlockButtonSize(e){switch(e){case"small":return Ys.BUTTON_SIZE_SMALL;case"medium":return Ys.BUTTON_SIZE_MEDIUM;case"large":return Ys.BUTTON_SIZE_LARGE}}makeBlockImageResizeMode(e){switch(e){case"none":return Dn.IMAGE_RESIZE_NONE;case"fit":return Dn.IMAGE_RESIZE_FIT;case"fill":return Dn.IMAGE_RESIZE_FILL;case"cover":return Dn.IMAGE_RESIZE_COVER;case"scale-down":return Dn.IMAGE_RESIZE_SCALE_DOWN}}makeBlockSpacerSize(e){switch(e){case"xsmall":return Ko.SPACER_XSMALL;case"small":return Ko.SPACER_SMALL;case"medium":return Ko.SPACER_MEDIUM;case"large":return Ko.SPACER_LARGE}}makeBlockSpacerShape(e){switch(e){case"invisible":return ta.SPACER_INVISIBLE;case"thin":return ta.SPACER_THIN;case"square":return ta.SPACER_SQUARE}}makeBlockIconSize(e){switch(e){case"xsmall":return $o.ICON_SIZE_XSMALL;case"small":return $o.ICON_SIZE_SMALL;case"medium":return $o.ICON_SIZE_MEDIUM;case"large":return $o.ICON_SIZE_LARGE}}makeBlockAvatarSize(e){switch(e){case"xxsmall":return Qe.AVATAR_SIZE_XXSMALL;case"xsmall":return Qe.AVATAR_SIZE_XSMALL;case"small":return Qe.AVATAR_SIZE_SMALL;case"medium":return Qe.AVATAR_SIZE_MEDIUM;case"large":return Qe.AVATAR_SIZE_LARGE;case"xlarge":return Qe.AVATAR_SIZE_XXLARGE;case"xxlarge":return Qe.AVATAR_SIZE_XXLARGE;case"xxxlarge":return Qe.AVATAR_SIZE_XXXLARGE}}makeBlockAvatarFacing(e){switch(e){case"left":return zd.AVATAR_FACING_LEFT;case"right":return zd.AVATAR_FACING_RIGHT}}makeBlockAvatarBackground(e){switch(e){case"dark":return Jd.AVATAR_BG_DARK;case"light":return Jd.AVATAR_BG_LIGHT}}getDataSet(e){return Object.keys(e).filter(t=>t.startsWith($d)).reduce((t,n)=>(t[n.substring($d.length)]=e[n],t),{})}makeActions(e,t){let n=[],o=this.getDataSet(t);return Cm.forEach(s=>{if(s in t){let a=t[s];n.push({type:Pm.get(s)??aa.UNRECOGNIZED,id:a.toString(),data:o})}}),n}blockColorToHex(e,t="light"){if(e)return e=e.toLowerCase(),Nd(e)?e:Ld(e)?jd(e,t):Zs(e)?Wo(e):_d(e)?Vd(e):Hd(e)?e:(console.warn(`Could not parse color: ${e}.`),Wo("red"))}childrenToBlocks(e,t){return e.flatMap(n=>(typeof n!="string"?this.createBlocksElement(n,t):void 0)??[])}getThemedColors(e,t,n){let o=this.blockColorToHex(t,"light"),s=this.blockColorToHex(n,"dark"),a=[];if(e&&(!o||!s)){let c=Array.from(e?.matchAll(/[\w#-]+(?:\([\w\t ,.#-]+\))?/g)??[]);a.push(...c.map(m=>m[0]))}return o||(o=this.blockColorToHex(a?.at(0),"light")),s||(s=this.blockColorToHex(a?.at(1)??a?.at(0),"dark")),o||s?{light:o,dark:s}:void 0}parsePixels(e){return typeof e=="string"?Number(e.slice(0,-2)):e}resolveAssetUrl(e,t){return r(this,_n).call(this)?.getURL(e,t)??e}childrenToString(e){return e.map(t=>t.toString()).join("")}makeRoot(e,...t){return this.wrapRoot(e,this.childrenToBlocks(t,Xs))}wrapRoot(e,t){return this.makeBlock(Re.BLOCK_ROOT,{},{},{rootConfig:{children:t,height:this.makeRootHeight(u.customPostType?.height??e?.height??"regular")}})}makeStackBlock(e,t,n,o){let s=this.getThemedColors(t?.backgroundColor,t?.lightBackgroundColor,t?.darkBackgroundColor),a=this.makeBlockAlignment(t?.alignment),c=Qs(t,n),m=Gd(t,n.stackParentLayout,c);return this.makeBlock(Re.BLOCK_STACK,t,n,{stackConfig:{alignment:a,backgroundColor:s?.light,backgroundColors:s,border:this.makeBlockBorder(t?.border,t?.borderColor,t?.lightBorderColor,t?.darkBorderColor),children:this.childrenToBlocks(o,{stackParentLayout:{...m,direction:e,alignment:a}}),cornerRadius:this.makeBlockRadius(t?.cornerRadius),direction:e,gap:this.makeBlockGap(t?.gap),padding:this.makeBlockPadding(t?.padding),reverse:t?.reverse}})}makeHStack(e,t,...n){return this.makeStackBlock(ia.STACK_HORIZONTAL,e,t,n)}makeVStack(e,t,...n){return this.makeStackBlock(ia.STACK_VERTICAL,e,t,n)}makeZStack(e,t,...n){return this.makeStackBlock(ia.STACK_DEPTH,e,t,n)}makeText(e,t,...n){let o=this.getThemedColors(e?.color,e?.lightColor,e?.darkColor);return this.makeBlock(Re.BLOCK_TEXT,e,t,{textConfig:{alignment:this.makeBlockAlignment(e?.alignment),color:o?.light,colors:o,outline:this.makeBlockTextOutline(e?.outline),size:this.makeBlockTextSize(e?.size),style:this.makeBlockTextStyle(e?.style),text:this.childrenToString(n),weight:this.makeBlockTextWeight(e?.weight),selectable:e?.selectable,wrap:e?.wrap,overflow:this.makeBlockTextOverflow(e?.overflow)}})}makeButton(e,t,...n){let o=this.getThemedColors(e?.textColor,e?.lightTextColor,e?.darkTextColor);return this.makeBlock(Re.BLOCK_BUTTON,e,t,{buttonConfig:{buttonAppearance:this.makeBlockButtonAppearance(e?.appearance),icon:e?.icon,buttonSize:this.makeBlockButtonSize(e?.size),text:this.childrenToString(n),textColor:o?.light,textColors:o,disabled:e?.disabled}})}makeImage(e,t){return e&&this.makeBlock(Re.BLOCK_IMAGE,e,t,{imageConfig:{description:e?.description,resizeMode:this.makeBlockImageResizeMode(e.resizeMode),url:this.resolveAssetUrl(e.url),width:this.parsePixels(e.imageWidth),height:this.parsePixels(e.imageHeight)}})}makeSpacer(e,t){return this.makeBlock(Re.BLOCK_SPACER,e,t,{spacerConfig:{size:this.makeBlockSpacerSize(e?.size),shape:this.makeBlockSpacerShape(e?.shape)}})}makeIcon(e,t){let n=this.getThemedColors(e?.color,e?.lightColor,e?.darkColor);return e&&this.makeBlock(Re.BLOCK_ICON,e,t,{iconConfig:{icon:e.name,color:n?.light,colors:n,size:this.makeBlockIconSize(e.size)}})}makeAvatar(e,t){return e&&this.makeBlock(Re.BLOCK_AVATAR,e,t,{avatarConfig:{thingId:e.thingId,size:this.makeBlockAvatarSize(e.size),facing:this.makeBlockAvatarFacing(e.facing),background:this.makeBlockAvatarBackground(e.background)}})}makeWebView(e,t){return e&&this.makeBlock(Re.BLOCK_WEBVIEW,e,t,{webviewConfig:{url:this.resolveAssetUrl(e.url,{webView:!0})}})}makeBlock(e,t,n,o){return{type:e,sizes:Qs(t,n),config:o,actions:(t&&this.makeActions(e,t))??[],id:t?.id,key:t?.key}}ensureRootBlock(e){let t;if(e.type===Re.BLOCK_ROOT?(e.config?.rootConfig&&u.customPostType?.height&&(e.config.rootConfig.height=this.makeRootHeight(u.customPostType?.height)),t=e):t=this.wrapRoot(void 0,[e]),!t)throw new Error("Could not create root block");return t}};_n=new WeakMap;function Zd(i){if(typeof i=="string")throw new Error("Root element cannot be a string")}var Xd=i=>{let e="",t=i.props?Object.keys(i.props).map(n=>n==="onPress"?"":`${n}="${i.props[n]}"`).join(" "):"";e+=`<${i.type}${t?" "+t:""}>`;for(let n of i.children)typeof n=="string"?e+=n:e+=Xd(n);return e+=`</${i.type}>`,e};function Sm(i){return" ".repeat(i)}function wm(i){let e="",t=0,n=i.split(/>\s*</);for(let o=0;o<n.length;o++){let s=n[o];o===0&&(s=s.trim()),o===n.length-1&&(s=s.trim());let a=s.charAt(0)==="/";a&&t--,e+=Sm(t),o!==0&&(e+="<"),e+=s,o!==n.length-1&&(e+=`>
|
|
2
|
+
`),!a&&s.indexOf("</")===-1&&s.charAt(s.length-1)!=="/"&&t++}return e}var Fe,Qd,Zo,la,Hn,_e=class{constructor(e,t,n,o,s){l(this,Fe);this.renderState={};this.currentComponentKey=[];this.currentHookIndex=0;this.actions=new Map;this.forms=new Map;this.realtimeChannels=[];this.realtimeUpdated=!1;this.pendingHooks=[];this.isRendering=!1;this.transformer=new ki(()=>this.assets);this.effects=[];l(this,Hn,!1);this.component=e,this.event=t,this.state={__renderState:{},...n},this.metadata=o,this.state.__realtimeChannels&&(this.realtimeChannels=this.state.__realtimeChannels);let a=ke({reconciler:this,hooks:!0,ui:!0,metadata:o});this.cache=a.cache,this.modLog=a.modLog,this.kvStore=a.kvStore,this.redis=a.redis,this.settings=a.settings,this.scheduler=a.scheduler,this.media=a.media,this.assets=a.assets,this.realtime=a.realtime,this.dimensions=s,this.ui=a.ui,this.hooks={useState:a.useState,useInterval:a.useInterval,useForm:a.useForm,useChannel:a.useChannel}}emitEffect(e,t){this.effects.push(t)}async render(){await this.reconcile(),this.isRendering=!0;let e=await this.buildBlocksUI();return this.isRendering=!1,e}makeUniqueActionID(e){let t=e,n=1;for(;this.actions.has(t);)t=`${e}.${n++}`;return t}async reconcile(){let e=f(this,Fe,Zo).call(this),t={type:this.component,props:e,children:[]},n=await this.processBlock(t);if(Zd(n),this.transformer.createBlocksElementOrThrow(n),this.isUserActionRender&&this.blockRenderEventId){let o=this.actions.get(this.blockRenderEventId);o&&await o(this.event.data)}for(let o of this.pendingHooks)await o();this.buildNextState(),f(this,Fe,Qd).call(this)}async buildBlocksUI(){let e=f(this,Fe,Zo).call(this),t={type:this.component,props:e,children:[]},n=await this.renderElement(e,t);return this.transformer.ensureRootBlock(n)}async renderElement(e,t){let n=await this.processBlock(t);return Zd(n),(u.debug.emitSnapshots||e.debug.emitSnapshots)&&console.debug(wm(Xd(n))),(u.debug.emitState||e.debug.emitState)&&console.debug(JSON.stringify(this.state,void 0,2)),this.transformer.createBlocksElementOrThrow(n)}async processProps(e){let t=e.props??{},n=["onPress","onMessage"];for(let o of n)if(o in t){let s=t[o],a=s?.name,c=this.makeUniqueActionID(`${e.type}.${a??o}`);this.actions.set(c,s),t[o]=c}}async processBlock(e,t=Ud(),n=[]){if(typeof e=="string")return e;if(typeof e=="number")return`${e}`;let o=e;if(typeof o.type=="string"){let c=[];for(let v=0;v<o.children.length;v++){let y=o.children[v];y!=null&&c.push(await this.processBlock(y,t,[...n,`${o.type}.${v}`]))}let m=c.flat(),h=f(this,Fe,la).call(this,m);return await this.processProps(o),{type:o.type,props:o.props,children:h}}if(typeof o.type=="function"){let c=t(`${n.length?n.join("."):"root"}.${o.type.name.length?o.type.name:"anonymous"}`);this.currentComponentKey.push(c),this.renderState[c]||(this.renderState[c]={});let m=o.children.flatMap(P=>P),h=f(this,Fe,Zo).call(this),v={...h,...o.props,children:m},y;for(;y===void 0;)try{y=await o.type(v,h)}catch(P){if(P instanceof Promise)y=await P;else throw P}if(!this.isInitialRender){let P=this.getPreviousComponentState();if(Object.keys(P).length!==this.currentHookIndex)throw new Error("Invalid hook call. Hooks can only be called at the top-level of a function component. Make sure that you are not calling hooks inside loops, conditions, or nested functions.")}if(this.currentComponentKey.pop(),this.currentHookIndex=0,typeof y=="object")return this.processBlock(y,t,[...n,o.type.name])}let s=[],a="";return Array.isArray(o)?s=o:typeof o.type>"u"&&o.children&&(s=o.children,a="fragmentChild."),{type:"__fragment",props:void 0,children:await Promise.all(s.flatMap(async(c,m)=>await this.processBlock(c,t,[...n,`${a}${m}`])))}}getCurrentComponentKey(){if(!this.currentComponentKey.at(-1))throw new Error("Current component key is missing");return this.currentComponentKey}getCurrentComponentState(){let e=this.currentComponentKey.at(-1);if(!e)throw new Error("Current component key is missing");return this.renderState[e]}getPreviousComponentState(){let e=this.currentComponentKey.at(-1);if(!e)throw new Error("Current component key is missing");return this.state.__renderState[e]||(this.state.__renderState[e]={}),this.state.__renderState[e]}get isInitialRender(){return this.event?this.event.type===da.RENDER_INITIAL:!1}get isUserActionRender(){return this.event?this.event.type===da.RENDER_USER_ACTION:!1}get isEffectRender(){return this.event?this.event.type===da.RENDER_EFFECT_EVENT:!1}get formSubmittedEvent(){return this.event?this.event.formSubmitted:!1}get blockRenderEventId(){return this.event?this.event.id:!1}get realtimeEvent(){if(!this.event)return!1;let e=this.event.realtimeEvent;return e?.event?.channel?e:!1}runHook(e){this.pendingHooks.push(e)}rerenderIn(e){r(this,Hn)||(d(this,Hn,!0),this.effects.push({type:Kd.EFFECT_RERENDER_UI,rerenderUi:{delaySeconds:e/1e3}}))}addRealtimeChannel(e){this.realtimeChannels.push(e),this.realtimeUpdated=!0}removeRealtimeChannel(e){this.realtimeChannels=this.realtimeChannels.filter(t=>t!==e),this.realtimeUpdated=!0}get realtimeEffect(){return this.realtimeUpdated&&this.realtimeChannels.length>0?[{type:Kd.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:this.realtimeChannels}}]:[]}getEffects(){return[...yi(this.ui),...this.effects,...this.realtimeEffect]}buildNextState(){for(let e of Object.keys(this.renderState))this.renderState[e]=Object.values(this.renderState[e]);this.state={__postData:this.state.__postData,__renderState:this.renderState,__cache:this.state.__cache,...this.realtimeChannels.length>0?{__realtimeChannels:this.realtimeChannels}:{}}}};Fe=new WeakSet,Qd=function(){this.actions.clear(),this.currentComponentKey=[],this.currentHookIndex=0,this.pendingHooks=[],this.realtimeChannels=[],this.realtimeUpdated=!1},Zo=function(){let e={...re(this.metadata,this.state.__postData?.thingId),modLog:this.modLog,cache:this.cache,kvStore:this.kvStore,redis:this.redis,settings:this.settings,scheduler:this.scheduler,media:this.media,assets:this.assets,realtime:this.realtime,ui:this.ui,dimensions:this.dimensions,uiEnvironment:{timezone:this.metadata[S.Timezone]?.values[0],locale:this.metadata[S.Language]?.values[0],dimensions:this.dimensions},...this.hooks};return e.debug.effects=this,e},la=function(e){let t=[];for(let n of e)typeof n=="string"?t.push(n):n.type==="__fragment"?t.push(...f(this,Fe,la).call(this,n.children)):t.push(n);return t},Hn=new WeakMap;async function Am(i,e){let t=u.customPostType;if(!t)throw new Error("Custom post type not registered");let n=new _e((s,a)=>t.render(a),i.blocks,i.state,e,i.dimensions),o=await n.render();return Fm.fromJSON({state:n.state,blocks:{ui:o},effects:n.getEffects()})}function Yd(i){i.provides(xm),O("RenderPost",Am)}import{GetFieldsResponse as Im,InstallationSettingsDefinition as Em}from"@devvit/protos";async function Tm(){if(!u.installationSettings)throw new Error("Installation settings were not defined.");return Im.fromJSON({fields:{fields:Le(u.installationSettings)}})}async function Rm(i,e){return Vo(i,u.installationSettings,e)}function el(i){i.provides(Em),O("GetSettingsFields",Tm),O("ValidateForm",Rm)}import{ContextActionDefinition as Om,ContextActionList as Mm,ContextActionResponse as Bm}from"@devvit/protos";function ua(i){let e=i.metadata[S.User].values[0];if(!e)throw new Error("User missing from context");return e}function ca(i){let e=i.metadata[S.Subreddit].values[0];if(!e)throw new Error("Subreddit missing from context");return e}async function tl(i,e){let t=ua(i),n=ca(i);if(!t||!n)throw new Error("User or subreddit missing from context");let o=e.comment?.id&&`t1_${e.comment.id}`,s=e.post?.id&&`t3_${e.post.id}`,a=e.subreddit?.id&&`t5_${e.subreddit.id}`,c=o||s||a;if(!c)throw new Error("targetId is missing from ContextActionRequest");if(o){let y=await sl(o);if(!y)throw new Error(`Comment ${o} not found`);if(y.subredditId!==n)throw new Error("Comment does not belong to the subreddit")}if(s){let y=await ol(s);if(!y)throw new Error(`Post ${s} not found`);if(y.subredditId!==n)throw new Error("Post does not belong to the subreddit")}if(a&&a!==n)throw new Error(`Subreddit ${a} ${n} not found`);let m=jn(e.actionId);if(!m)throw new Error("Action not found");let h=!!m.forUserType?.includes("moderator");if(h&&!il(i))throw new Error("User is not a moderator");let v={needsModCheck:h};await i.redis.set(`${t}${n}${c}${e.actionId}`,JSON.stringify(v)),await i.redis.expire(`${t}${n}${c}${e.actionId}`,600)}async function il(i){let e=ua(i),t=ca(i),n=await rl(t);return!!(await al({subredditName:n.name}).all()).find(s=>s.id===e)}async function nl(i,e){let t=ua(i),n=ca(i),{actionId:o,thingId:s}=e.state?.__contextAction??{},a=await i.redis.get(`${t}${n}${s}${o}`);if(!a)throw new Error("CSRF token not found");if(JSON.parse(a).needsModCheck&&!await il(i))throw new Error("User is not a moderator: "+t+"; "+n)}var dl=i=>`menuItem.${i}`;function jn(i){return u.menuItems.find((e,t)=>dl(t)===i)}async function Um(i,e){let t=u.menuItems;if(!t.length)throw new Error("No menu items registered.");let n=t.map((o,s)=>({actionId:dl(s),name:o.label,description:o.description,contexts:{subreddit:o.location.includes("subreddit"),post:o.location.includes("post"),comment:o.location.includes("comment")},users:{loggedOut:o.forUserType?.includes("loggedOut"),moderator:o.forUserType?.includes("moderator")},postFilters:o.postFilter==="currentApp"?{currentApp:!0}:void 0}));return Mm.fromJSON({actions:n})}async function Dm(i,e){let t=jn(i.actionId);if(!t)throw new Error(`MenuItem ${i.actionId} not found`);let n=i.comment?.id&&`t1_${i.comment.id}`,o=i.post?.id&&`t3_${i.post.id}`,s=i.subreddit?.id&&`t5_${i.subreddit.id}`,a=n||o||s;p(a,"targetId is missing from ContextActionRequest");let c={targetId:a,location:i.comment?"comment":i.post?"post":"subreddit"},m=Object.assign(ke({ui:!0,metadata:e}),re(e,o,n),{uiEnvironment:{timezone:e[S.Timezone]?.values[0],locale:e[S.Language]?.values[0]}});return await tl(m,i),await t.onPress(c,m),Bm.fromJSON({effects:yi(m.ui)})}function ll(i){i.provides(Om),O("GetActions",Um),O("OnAction",Dm)}function Ce(i){return i?i===!0?!0:i.enabled:!1}import{SchedulerHandlerDefinition as Nm}from"@devvit/protos";async function Lm(i,e){let t=i.type,n=u.scheduledJobHandlers.get(t);if(!n)throw new Error(`Job ${t} not found`);let o={name:t,data:i.data},s=Object.assign(ke({metadata:e}),re(e));await n(o,s)}function ul(i){i.provides(Nm),O("HandleScheduledAction",Lm)}import{OnAppInstallDefinition as _m,OnAppUpgradeDefinition as Hm,OnAutomoderatorFilterCommentDefinition as jm,OnAutomoderatorFilterPostDefinition as Vm,OnCommentCreateDefinition as Wm,OnCommentDeleteDefinition as Gm,OnCommentReportDefinition as Jm,OnCommentSubmitDefinition as zm,OnCommentUpdateDefinition as qm,OnModActionDefinition as $m,OnModMailDefinition as Km,OnPostCreateDefinition as Zm,OnPostDeleteDefinition as Xm,OnPostFlairUpdateDefinition as Qm,OnPostNsfwUpdateDefinition as Ym,OnPostReportDefinition as ep,OnPostSpoilerUpdateDefinition as tp,OnPostSubmitDefinition as ip,OnPostUpdateDefinition as np}from"@devvit/protos";var et;(function(i){function e(a,c){return a.length<=c?a:`${a.slice(0,c-1)}\u2026`}i.ellipsize=e;function t(a){return a[0]==null?a:`${a[0].toLocaleUpperCase()}${a.slice(1)}`}i.capitalize=t;function n(a){return a==null||/^\s*$/.test(a)}i.isBlank=n;function o(a,c="stack"){return a instanceof Error?`${a[c]||a.stack||a.message||a.name}`:String(a)}i.caughtToString=o;function s(a,c="stack"){return a instanceof Error?`${a[c]||a.stack||a.message||a.name}`:String(a)}i.caughtToStringUntyped=s})(et||(et={}));function q(i,e){return p(e),async(t,n)=>{let o={...t,type:i},s=Object.assign(ke({metadata:n}),re(n)),a=await Promise.allSettled(e.map(m=>m(o,s))),c=rp(a);if(c)throw c.err;return{}}}function cl(i){for(let e of u.triggerOnEventHandlers.keys())switch(e){case"PostSubmit":i.provides(ip),O("OnPostSubmit",q("PostSubmit",u.triggerOnEventHandlers.get(e)));break;case"PostCreate":i.provides(Zm),O("OnPostCreate",q("PostCreate",u.triggerOnEventHandlers.get(e)));break;case"PostUpdate":i.provides(np),O("OnPostUpdate",q("PostUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostReport":i.provides(ep),O("OnPostReport",q("PostReport",u.triggerOnEventHandlers.get(e)));break;case"PostDelete":i.provides(Xm),O("OnPostDelete",q("PostDelete",u.triggerOnEventHandlers.get(e)));break;case"PostFlairUpdate":i.provides(Qm),O("OnPostFlairUpdate",q("PostFlairUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentSubmit":i.provides(zm),O("OnCommentSubmit",q("CommentSubmit",u.triggerOnEventHandlers.get(e)));break;case"CommentCreate":i.provides(Wm),O("OnCommentCreate",q("CommentCreate",u.triggerOnEventHandlers.get(e)));break;case"CommentUpdate":i.provides(qm),O("OnCommentUpdate",q("CommentUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentReport":i.provides(Jm),O("OnCommentReport",q("CommentReport",u.triggerOnEventHandlers.get(e)));break;case"CommentDelete":i.provides(Gm),O("OnCommentDelete",q("CommentDelete",u.triggerOnEventHandlers.get(e)));break;case"AppInstall":i.provides(_m),O("OnAppInstall",q("AppInstall",u.triggerOnEventHandlers.get(e)));break;case"AppUpgrade":i.provides(Hm),O("OnAppUpgrade",q("AppUpgrade",u.triggerOnEventHandlers.get(e)));break;case"ModAction":i.provides($m),O("OnModAction",q("ModAction",u.triggerOnEventHandlers.get(e)));break;case"ModMail":i.provides(Km),O("OnModMail",q("ModMail",u.triggerOnEventHandlers.get(e)));break;case"PostNsfwUpdate":i.provides(Ym),O("OnPostNsfwUpdate",q("PostNsfwUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostSpoilerUpdate":i.provides(tp),O("OnPostSpoilerUpdate",q("PostSpoilerUpdate",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterPost":i.provides(Vm),O("OnAutomoderatorFilterPost",q("AutomoderatorFilterPost",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterComment":i.provides(jm),O("OnAutomoderatorFilterComment",q("AutomoderatorFilterComment",u.triggerOnEventHandlers.get(e)));break;default:throw new Error(`Unknown trigger event: ${e}`)}}function rp(i){let e=i.reduce((t,n)=>n.status==="rejected"?[...t,n.reason]:t,[]);if(e.length!==0)return e.length===1?{err:e[0]}:{err:new Error(e.map(t=>et.caughtToString(t)).join(`
|
|
3
|
+
`))}}import{EffectType as Ip,HandleUIEventResponse as ga,UIEventHandlerDefinition as Ep}from"@devvit/protos";var Il=id(Sl(),1);function wl(i){return i?.constructor===Object}function Rt(i,e){return Object.is(i,e)?!0:typeof i!=typeof e?!1:Array.isArray(i)&&Array.isArray(e)?xl(i,e):i instanceof Date&&e instanceof Date?i.getTime()===e.getTime():i instanceof RegExp&&e instanceof RegExp?i.toString()===e.toString():wl(i)&&wl(e)?Ap(i,e):i instanceof ArrayBuffer&&e instanceof ArrayBuffer?Fl(new DataView(i),new DataView(e)):i instanceof DataView&&e instanceof DataView?Fl(i,e):Al(i)&&Al(e)?i.byteLength!==e.byteLength?!1:xl(i,e):!1}function Ap(i,e){let t=Object.keys(i),n=Object.keys(e);if(!Rt(t,n))return!1;for(let o of t)if(!Rt(i[o],e[o]))return!1;return!0}function xl(i,e){return i.length!==e.length?!1:i.every((t,n)=>Rt(t,e[n]))}function Fl(i,e){if(i.byteLength!==e.byteLength)return!1;for(let t=0;t<i.byteLength;t++)if(i.getUint8(t)!==e.getUint8(t))return!1;return!0}function Al(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}async function Tp(i,e){let t=i.state??{},n=(0,Il.default)(t),o=ke({ui:!0,metadata:e});if(i.event?.formSubmitted&&i.event.formSubmitted.formId){let m=i.event.formSubmitted.formId;if(m.includes("form.hook.")&&u.customPostType){let b=new _e((A,U)=>u.customPostType?.render(U)??null,i.event,i.state,e,void 0);return await b.reconcile(),ga.fromJSON({state:b.state,effects:b.getEffects()})}let h=u.formDefinitions.get(m);if(!h)throw new Error(`Form with key ${m} not found`);let v,y;if(n.__contextAction){let{actionId:b,thingId:A}=n.__contextAction,U=jn(b);U?.location==="post"?v=A:U?.location==="comment"&&(y=A)}let P=Object.assign(o,re(e,v,y),{uiEnvironment:{timezone:e[S.Timezone]?.values[0],locale:e[S.Language]?.values[0]}});await nl(P,i),await h.onSubmit({values:qe(i.event.formSubmitted.results)},P)}else if(i.event?.realtimeEvent){if(u.customPostType){let m=new _e((h,v)=>u.customPostType?.render(v)??null,i.event,i.state,e,void 0);return await m.reconcile(),ga.fromJSON({state:m.state,effects:m.getEffects()})}}else if(i.event?.toastAction)throw new Error("Toast actions not yet implemented");let s=!Rt(t,n),a=yi(o.ui),c=s?[...a,{type:Ip.EFFECT_RERENDER_UI,rerenderUi:{delaySeconds:0}}]:a;return ga.fromJSON({state:n,effects:c})}function El(i){i.provides(Ep),O("HandleUIEvent",Tp)}import{CustomPostDefinition as us,UIResponse as iu}from"@devvit/protos";import{UIEventScope as Lp}from"@devvit/protos";var fa="ServerCallRequired";function Xo(i){return i?.message===fa}var va={now(){return new Date}};function Tl(i){return`__autocache__${i}`}function Rl(i){return`__lock__${i}`}var Rp=300,Op=1e3,Qo=5e3,ha=3,Ol=.1,Ml=1e3,Mp=3e4;function Bl(i){if(i.error)throw new Error(i.error);return i.value}var tt,it,Pe,Ci,z,Ul,Dl,Nl,ya,Ll,_l,ba,Hl,Yo=class{constructor(e,t,n=va){l(this,z);l(this,tt);l(this,it,{});l(this,Pe);l(this,Ci);d(this,tt,e),d(this,Ci,t),d(this,Pe,n)}async cache(e,t){var a;(a=r(this,Ci)).__cache??(a.__cache={}),d(this,it,r(this,Ci).__cache),f(this,z,Hl).call(this,t);let n=f(this,z,Ul).call(this,t.key);if(n!==void 0)return n;let o=await f(this,z,ba).call(this,t.key),s=await f(this,z,Dl).call(this,t,o,e);return Bl(s)}};tt=new WeakMap,it=new WeakMap,Pe=new WeakMap,Ci=new WeakMap,z=new WeakSet,Ul=function(e){let t=r(this,it)[e];if(t){let n=r(this,Pe).now().getTime(),o=t?.error&&t?.errorTime&&t.errorCount<ha&&Math.random()<Ol&&t.errorTime+Ml<n;if(t?.expires&&t.expires<n&&t.checkedAt+Ml<n||o){delete r(this,it)[e];return}else return Bl(t)}},Dl=async function(e,t,n){let o=t?.expires,s=o?f(this,z,_l).call(this,o):1;return!t||t?.error&&t.errorCount<ha&&Ol>Math.random()||s>Math.random()?f(this,z,Nl).call(this,e,t,n):t},Nl=async function(e,t,n){let o=Rl(e.key),s=r(this,Pe).now().getTime(),a=new Date(s+e.ttl/2);if(await r(this,tt).set(o,"1",{expiration:a,nx:!0}))return f(this,z,Ll).call(this,e.key,t,n,e.ttl);if(t)return t;{let m=r(this,Pe).now();return f(this,z,ya).call(this,m,e.key,e.ttl)}},ya=async function(e,t,n){let o=Math.min(n,Op),s=await f(this,z,ba).call(this,t);if(s)return s;if(r(this,Pe).now().getTime()-e.getTime()>=o)throw new Error(`Cache request timed out trying to get data at key: ${t}`);return await new Promise(a=>setTimeout(a,Rp)),f(this,z,ya).call(this,e,t,n)},Ll=async function(e,t,n,o){let s=r(this,Pe).now().getTime()+o;t=t??{value:null,expires:s,errorCount:0,error:null,errorTime:null,checkedAt:0};try{t.value=await n(),t.error=null,t.errorCount=0,t.errorTime=null}catch(a){t.value=null,t.error=a.message??"Unknown error",t.errorTime=r(this,Pe).now().getTime(),t.errorCount++}return r(this,it)[e]=t,await r(this,tt).set(Tl(e),JSON.stringify(t),{expiration:new Date(s+Mp)}),t.error&&t.errorCount<ha&&await r(this,tt).del(Rl(e)),t},_l=function(e){let t=r(this,Pe).now().getTime(),n=e-t;return n<0?1:n<1e3?.1:n<2e3?.01:n<3e3?.001:0},ba=async function(e){let t=await r(this,tt).get(Tl(e));if(t){let n=JSON.parse(t);return n.checkedAt=r(this,Pe).now().getTime(),r(this,it)[e]=n,n}},Hl=function(e){e.ttl<Qo&&(console.warn(`Cache TTL cannot be less than ${Qo} milliseconds! Updating ttl value of ${e.ttl} to ${Qo}.`),e.ttl=Qo)};function jl(i,e,t=va){let n=new Yo(i,e,t);return n.cache.bind(n)}import{EffectType as es,ToastAppearance as Gl}from"@devvit/protos";function Vl(i){let e=i.match(/form\.hook\.(.+)\.0/);if(e?.[1])return e[1]}var ka=class{constructor(e,t,n){this.state=null;this.hookId=e.hookId,this.form=t,this.onSubmit=n,this.onUIEvent=async o=>{o.formSubmitted&&await n(qe(o.formSubmitted.results))}}};function Ca(i,e){let t=le({namespace:"useForm",initializer:n=>new ka(n,i,e)});return Bp({id:t.hookId})}function Bp(i){return`form.hook.${i.id}.0`}function Wl(i,e){let t=Vl(e);return i.getHook({id:t})}var He,is,Vn,ns,ts=class{constructor(e){l(this,He);l(this,is,0);l(this,Vn);l(this,ns,(e,t)=>{let n=t!==void 0?e:"",o=t!==void 0?t:e;r(this,He).emitEffect(`postMessage${nd(this,is)._++}`,{type:es.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:n,app:{message:o,jsonString:JSON.stringify(o)}}}})});d(this,He,e),d(this,Vn,{postMessage:r(this,ns)})}get webView(){return r(this,Vn)}showForm(e,t){let n=Wl(r(this,He),e);if(!n)throw new Error("Form does not exist. Make sure you have added it using useForm.");let o=n.form instanceof Function?n.form(t??{}):n.form,s={fields:[],id:e,title:o.title,acceptLabel:o.acceptLabel,cancelLabel:o.cancelLabel,shortDescription:o.description};It(o.fields),s.fields=Le(o.fields),r(this,He).emitEffect(e,{type:es.EFFECT_SHOW_FORM,showForm:{form:s}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Gl.SUCCESS:Gl.NEUTRAL}:t={text:e},r(this,He).emitEffect(e.toString(),{type:es.EFFECT_SHOW_TOAST,showToast:{toast:t}})}navigateTo(e){let t;typeof e=="string"?t=new URL(e).toString():t=new URL(e.permalink,"https://www.reddit.com").toString(),r(this,He).emitEffect(t,{type:es.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}};He=new WeakMap,is=new WeakMap,Vn=new WeakMap,ns=new WeakMap;import{EffectType as Up,RealtimeSubscriptionStatus as Jl}from"@devvit/protos";var nt,Oe,rt,Ot,Wn,Sa,rs=class rs{constructor(e,t){l(this,Wn);l(this,nt);l(this,Oe);l(this,rt);l(this,Ot);d(this,nt,t.context),d(this,Oe,!!t.context._devvitContext?.debug.realtime),d(this,Ot,e),d(this,rt,t.invalidate);let n=t.context.meta[S.App]?.values[0];if(!n)throw Error("useChannel missing app ID metadata");let o=t.context.meta[S.Installation]?.values[0];if(!o)throw Error("useChannel missing install ID from metadata");let s=`${n}:${o}:${e.name}`;if(Object.values(r(this,nt)._hooks).filter(c=>c instanceof rs).some(c=>c.state.channel===s))throw Error(`useChannel channel names must be unique; "${s}" duplicated`);this.state={channel:s,connected:!1,subscribed:!1}}async onUIEvent(e){let t=e.realtimeEvent;if(!(!t||!this.state.subscribed))switch(t.status){case Jl.REALTIME_SUBSCRIBED:r(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" connected`),this.state.connected=!0,r(this,rt).call(this),await r(this,Ot).onSubscribed?.();break;case Jl.REALTIME_UNSUBSCRIBED:r(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" disconnected`),this.state.connected=!1,r(this,rt).call(this),await r(this,Ot).onUnsubscribed?.();break;default:r(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" received message: ${JSON.stringify(e,void 0,2)}`),r(this,Ot).onMessage(t.event?.data?.msg);break}}async send(e){if(r(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" send message: ${JSON.stringify(e,void 0,2)}`),!this.state.subscribed||!this.state.connected)throw console.debug(`[realtime] "${this.state.channel}" send failed; channel not connected`),Error(`useChannel send failed; "${this.state.channel}" channel not connected`);await r(this,nt).devvitContext.realtime.send(this.state.channel,e)}get status(){return this.state.subscribed&&this.state.connected?2:this.state.subscribed&&!this.state.connected?1:!this.state.subscribed&&this.state.connected?3:4}subscribe(){this.state.subscribed||(r(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" subscribed`),this.state.subscribed=!0,r(this,rt).call(this),f(this,Wn,Sa).call(this))}unsubscribe(){this.state.subscribed&&(r(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" unsubscribed`),this.state.subscribed=!1,r(this,rt).call(this),f(this,Wn,Sa).call(this))}};nt=new WeakMap,Oe=new WeakMap,rt=new WeakMap,Ot=new WeakMap,Wn=new WeakSet,Sa=function(){let e=Object.values(r(this,nt)._hooks).filter(t=>t instanceof rs&&t.state.subscribed).map(t=>t.state.channel);r(this,nt).emitEffect(this.state.channel,{type:Up.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:e}})};var Pa=rs;function wa(i){if(!i.name||/[^a-zA-Z0-9_]/.test(i.name))throw Error(`useChannel error: The name "${i.name}" you provided for the hook is invalid. Valid names can only contain letters, numbers, and underscores (_).`);let e=`useChannel:${i.name}`;return le({id:e,namespace:e,initializer:t=>new Pa(i,t)})}import{EffectType as xa}from"@devvit/protos";function zl(i){return typeof i=="object"&&i!==null&&"__deleted"in i}var Mt,ot,Pi=class Pi{constructor(e,t){l(this,Mt);this._segments=[];l(this,ot,{});this._prevHooks={};this._prevHookId="";this._effects={};this._changed={};this._touched={};this._requeueEvents=[];this._rootProps={};this._generated={};this._undeliveredHandlers={};this.request=e,this.meta=t,d(this,Mt,e.state??{__cache:{}}),this._rootProps=e.props??{}}get devvitContext(){if(!this._devvitContext)throw new Error("Devvit context not available");return this._devvitContext}set devvitContext(e){this._devvitContext=e}get _changedState(){let e={__cache:r(this,Mt).__cache??{}};for(let n in this._changed)e[n]=this._state[n];let t=new Set(Object.keys(this._state));return Object.keys(r(this,ot)).forEach(n=>{n!=="__cache"&&t.delete(n)}),t.forEach(n=>{if(n==="__cache")return;let o={__deleted:!0};this._state[n]=e[n]=o}),e}get _hooks(){return r(this,ot)}set _hooks(e){this._prevHooks=r(this,ot),d(this,ot,e)}get _state(){return r(this,Mt)}set _state(e){d(this,Mt,e)}push(e){this._segments.push({...e,next:0})}pop(){this._segments.pop()}addUndeliveredEventHandler(e,t){this._undeliveredHandlers[e]=t}addGlobalUndeliveredEventHandler(e,t){Pi.addGlobalUndeliveredEventHandler(e,t)}getHook(e){return r(this,ot)[e.id]}static addGlobalUndeliveredEventHandler(e,t){Pi._staticUndeliveredHandlers[e]=t}async handleUndeliveredEvent(e){let t={...Pi._staticUndeliveredHandlers,...this._undeliveredHandlers};for(let[n,o]of Object.entries(t))await o(e,this)}emitEffect(e,t){this._effects[e]=t}addToRequeueEvents(...e){this._devvitContext?.debug.blocks&&console.debug("[blocks] requeueing events",e);let t=e.reduce((n,o)=>(o.retry?n.retry.push(o):n.normal.push(o),n),{retry:[],normal:[]});this._requeueEvents=[...t.retry,...this._requeueEvents,...t.normal]}get effects(){return Object.values(this._effects)}nextHookId(e){e.key===void 0&&(e.key=this._segments[this._segments.length-1].next+++""),this.push(e);try{let t=[];for(let o=this._segments.length-1;o>=0;o--){let s=this._segments[o];if(s.id){t.unshift(s.id);break}let a=[];s.namespace&&a.push(s.namespace),s.key!==void 0&&s.key!==!1&&a.push(s.key),t.unshift(a.join("-"))}let n=t.join(".");if(this._generated[n]&&!e.shared)throw new Error(`Hook id ${n} already used, cannot register another hook with the same id`);return this._generated[n]=!0,this._prevHookId=n,n}finally{this.pop()}}};Mt=new WeakMap,ot=new WeakMap,Pi._staticUndeliveredHandlers={};var Si=Pi;var st={};Si.addGlobalUndeliveredEventHandler("intervals",async(i,e)=>{i.timer&&i.hook&&(delete st[i.hook],e.emitEffect("timers",{type:xa.EFFECT_SET_INTERVALS,interval:{intervals:st}}))});var at,wi,Gn,xi,Fa=class{constructor(e,t,n){l(this,at);l(this,wi);l(this,Gn);l(this,xi);this.state={duration:{seconds:0,nanos:0},running:!1};d(this,wi,n.invalidate),d(this,at,n.hookId),d(this,Gn,e),d(this,xi,n.context);let o=Math.floor(t/1e3),s=t%1e3*1e6;this.state.duration={seconds:o,nanos:s}}onStateLoaded(){this.state.running?st[r(this,at)]={duration:this.state.duration}:delete st[r(this,at)]}async onUIEvent(e){await r(this,Gn).call(this)}start(){st[r(this,at)]={duration:this.state.duration},this.state.running=!0,r(this,wi).call(this),r(this,xi).emitEffect("timers",{type:xa.EFFECT_SET_INTERVALS,interval:{intervals:st}})}stop(){delete st[r(this,at)],this.state.running=!1,r(this,wi).call(this),r(this,xi).emitEffect("timers",{type:xa.EFFECT_SET_INTERVALS,interval:{intervals:st}})}};at=new WeakMap,wi=new WeakMap,Gn=new WeakMap,xi=new WeakMap;function Aa(i,e){let t=le({namespace:"useInterval",initializer:n=>new Fa(i,e,n)});return{start:()=>t.start(),stop:()=>t.stop()}}import{UIEventScope as Np}from"@devvit/protos";var Bt=class extends Error{};import{UIEventScope as ql}from"@devvit/protos";function Ea(i){if(i instanceof Error){if(i.message===fa)throw i;return console.error(i),{message:i.message,details:i.stack??""}}else return console.error(i),{message:"Unknown error",details:et.caughtToString(i)}}var Ae,Me,Fi,Jn,Ai,Ia=class{constructor(e,t,n){l(this,Ae);l(this,Me);l(this,Fi);l(this,Jn);l(this,Ai);d(this,Ae,!!n.context.devvitContext.debug.useAsync),r(this,Ae)&&console.debug("[useAsync] v1",t),this.state={data:null,load_state:"initial",error:null,depends:null},d(this,Me,n.hookId),this.initializer=e,d(this,Fi,n.invalidate),d(this,Jn,n.context),this.localDepends=t.depends??null,d(this,Ai,t)}onStateLoaded(){if(r(this,Ae)&&console.debug("[useAsync] async onLoad ",r(this,Me),this.state),r(this,Ae)&&console.debug("[useAsync] async onLoad have ",this.localDepends,"and",this.state.depends),!Rt(this.localDepends,this.state.depends)||this.state.load_state==="initial"){r(this,Ae)&&console.debug("[useAsync] attempting to resolve for hookId",r(this,Me)),this.state.load_state="loading",this.state.depends=this.localDepends,r(this,Fi).call(this);let e={scope:ql.ALL,hook:r(this,Me),async:!0,asyncRequest:{requestId:r(this,Me)+"-"+JSON.stringify(this.state.depends)}};r(this,Ae)&&console.debug("[useAsync] onLoad requeue"),r(this,Jn).addToRequeueEvents(e)}}async onUIEvent(e,t){if(e.asyncRequest){let n={requestId:e.asyncRequest.requestId};try{n.data={value:await this.initializer()}}catch(s){n.error=Ea(s)}let o={scope:ql.ALL,asyncResponse:n,hook:r(this,Me)};r(this,Ae)&&console.debug("[useAsync] onReq requeue"),t.addToRequeueEvents(o)}else if(e.asyncResponse){let n=r(this,Me)+"-"+JSON.stringify(this.state.depends);e.asyncResponse.requestId===n?(this.state={...this.state,data:e.asyncResponse.data?.value??null,error:e.asyncResponse.error??null,load_state:e.asyncResponse.error?"error":"loaded"},r(this,Ai).finally&&await r(this,Ai).finally(this.state.data,this.state.error?new Error(this.state.error?.message??"Unknown error"):null),r(this,Fi).call(this)):r(this,Ae)&&console.debug("[useAsync] onResp skip, stale event",e.asyncResponse.requestId," !== ",n)}else throw new Error("Unknown event type")}};Ae=new WeakMap,Me=new WeakMap,Fi=new WeakMap,Jn=new WeakMap,Ai=new WeakMap;function Dp(i,e={}){let t=le({namespace:"useAsync",initializer:n=>new Ia(i,e,n)});return{data:t.state.data,error:t.state.error,loading:t.state.load_state==="loading"}}var je,Ii,Ut,dt,Ta=class{constructor(e,t){this.state={value:null,load_state:"initial",error:null};l(this,je);l(this,Ii);l(this,Ut);l(this,dt);d(this,Ut,e),d(this,dt,t.hookId),d(this,je,t.invalidate),d(this,Ii,t.context)}async onUIEvent(){if(this.state.load_state==="loading"&&this._promise){try{this.state.value=await this._promise,this.state.load_state="loaded"}catch(e){this.state.load_state="error",this.state.error=Ea(e)}r(this,je).call(this)}else console.warn(`Invalid state for hook (${r(this,dt)}):`,this.state.load_state,this._promise)}setter(e){this.state.value=e instanceof Function?e(this.state.value):e,this.state.load_state="loaded",r(this,je).call(this)}onStateLoaded(){if(this._promise=r(this,Ii)._prevHooks[r(this,dt)]?._promise,this.state.load_state==="loading")throw new Bt;if(this.state.load_state==="error")throw new Error(this.state.error?.message??"Unknown error");if(this.state.load_state==="initial"){let e;try{e=r(this,Ut)instanceof Function?r(this,Ut).call(this):r(this,Ut)}catch(t){console.log("error in loading async",t),this.state.load_state="error",r(this,je).call(this);return}if(e instanceof Promise){this._promise=e,this.state.load_state="loading";let t={scope:Np.ALL,asyncRequest:{requestId:r(this,dt)},hook:r(this,dt)};throw r(this,Ii).addToRequeueEvents(t),r(this,je).call(this),new Bt}else this.state.value=e,this.state.load_state="loaded";r(this,je).call(this)}}};je=new WeakMap,Ii=new WeakMap,Ut=new WeakMap,dt=new WeakMap;function Ra(i){let e=le({namespace:"useState",initializer:t=>new Ta(i,t)});return[e.state.value,e.setter.bind(e)]}var os=class{buildContext(e,t,n){let o=new ui(n),s=new di(n),a=new pi(n),c=new gi(n),m=new fi(n),h=new ts(e),v=new li(n),y=new si,P=new ci(n),b=jl(a,e._state),A={modLog:o,kvStore:s,redis:a,scheduler:c,settings:m,media:v,assets:y,realtime:P,ui:h,useState:Ra,useChannel:wa,useInterval:Aa,useForm:Ca,cache:b,dimensions:t.env?.dimensions,uiEnvironment:{timezone:n[S.Timezone]?.values[0],locale:n[S.Language]?.values[0],dimensions:t.env?.dimensions,colorScheme:t.env?.colorScheme}},U=re(n,t.props?.postId);return U.debug.effects=e,{...U,...A}}};var ue=null;function $l(i){return JSON.parse(JSON.stringify(i))}function _p(i){if(!(i!==""&&!/[-.]/.test(i)))throw new Error(`Hook with namespace '${i}' is invalid. Hook namespaces cannot be empty string or contain dashes/dots because they are used as delimiters internally. Please update the hook namespace and try again.`)}function le({initializer:i,...e}){if(!ue)throw new Error("Hooks can only be declared at the top of a component. You cannot declare hooks outside of components or inside of event handlers. It's almost always a mistake to declare hooks inside of loops or conditionals.");_p(e.namespace);let t=ue.nextHookId(e),n=ue,o={hookId:t,invalidate:()=>{n._changed[t]=!0,n._state[t]=n?._hooks[t]?.state},context:ue},s=ue._state[t]===void 0||zl(ue._state[t]);ue._hooks[t]=ue._hooks[t]??i(o);let a=ue._hooks[t];return s||(a.state=ue._state[t]),a.onStateLoaded?.(),s&&a.state!==void 0&&a.state!==null&&o.invalidate(),a}var Hp=null,ss=128,Ei,ls,zn,x,oe,as,Kl,Oa,Zl,Ma,Ba,ds,Ua,Xl,Dt=class{constructor(e){l(this,x);l(this,Ei);l(this,ls,new os);l(this,zn,new ki(()=>this._latestRenderContext?.devvitContext?.assets));this._latestRenderContext=null;r(this,x,oe)&&console.debug("[blocks] BlocksHandler v1"),d(this,Ei,e),Hp=this}async handle(e,t){let n=new Si(e,t);n.devvitContext=r(this,ls).buildContext(n,e,t);let o,s=e.events.length-ss,a=e.events;if(s>0){a=[];{let A=0;for(let U of e.events)A<s&&U.realtimeEvent?A++:a.push(U)}for(;a.length>ss;)a.shift();console.warn(`dropped ${s} events`)}let m=!a.length||a.some(A=>!A.async),h=a.some(A=>A.blocking),v,y,P=[...a];a.length===0&&a.push({scope:Lp.ALL}),r(this,x,oe)&&console.debug("[blocks] starting processing events");let b=0;for(;a.length>0;){if(b++>ss)throw new Error(`Exceeded maximum iterations of ${ss}`);r(this,x,oe)&&console.debug("[blocks] processing events loop iteration",a.length);let A=[];if(!a[0].async)A.push(a.shift());else for(;a[0]?.async;)A.push(a.shift());if(!A.length)throw Error("batch must have at least one event");try{if(A[0].async){let M=$l(n._state);await f(this,x,Kl).call(this,n,...A),n._state=M}else await f(this,x,Zl).call(this,n,...A)}catch(M){if(!Xo(M))throw M;if(r(this,x,oe)&&console.debug("[blocks] caught in handler",M),n._latestRenderContent=void 0,y){n._state=y._state,n._changed=v,n._effects=y._effects;let Y=P.map(Oo=>{let Ds={...Oo};return Ds.retry=!0,Ds});n.addToRequeueEvents(...Y);break}else throw Xo(M)||console.error("[blocks] unhandled error in handler",M),M}r(this,x,oe)&&console.debug("[blocks] remaining events",n._requeueEvents);let U=[];for(let M of n._requeueEvents){if(!m&&!M.async){r(this,x,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch A",M),U.push(M);continue}if(m&&M.async&&!h){r(this,x,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch B",M),U.push(M);continue}r(this,x,oe)&&console.debug("[blocks] reprocessing event in BlocksHandler",M),a.push(M)}n._requeueEvents=U,a.length>0&&(v={...n._changed},y={_state:$l(n._state),_effects:{...n._effects}},P=[...a])}if(m){n._latestRenderContent||(n._latestRenderContent=f(this,x,Ma).call(this,r(this,Ei),n.request.props??{},n));let A=n._latestRenderContent;A&&(o=r(this,zn).createBlocksElementOrThrow(A),o=r(this,zn).ensureRootBlock(o))}return{state:n._changedState,effects:n.effects,blocks:o,events:n._requeueEvents}}};Ei=new WeakMap,ls=new WeakMap,zn=new WeakMap,x=new WeakSet,oe=function(){return!!this._latestRenderContext?.devvitContext.debug.blocks},as=function(e,...t){e._hooks={},f(this,x,Ma).call(this,r(this,Ei),e.request.props??{},e)},Kl=async function(e,...t){f(this,x,as).call(this,e,...t),await Promise.all(t.map(async n=>{if(!n.async)throw new Error("You can't mix main and other queues in one batch. This is likely a platform bug. Please file an issue in the Discord for someone to help! https://discord.com/channels/1050224141732687912/1115441897079574620");await f(this,x,Oa).call(this,e,n)}))},Oa=async function(e,t){let n=e._hooks[t.hook];if(n?.onUIEvent)try{await n.onUIEvent(t,e)}catch(o){throw Xo(o)?r(this,x,oe)&&console.error("Server call required",o):console.error("Error in event handler",o),o}else await e.handleUndeliveredEvent(t)},Zl=async function(e,...t){for(let n of t)r(this,x,oe)&&console.log("[blocks] handling main queue event",n),r(this,x,oe)&&console.log("[blocks] before",e._state),f(this,x,as).call(this,e,n),await f(this,x,Oa).call(this,e,n),r(this,x,oe)&&console.log("[blocks] after",e._state);f(this,x,as).call(this,e)},Ma=function(e,t,n){r(this,x,oe)&&console.debug("[blocks] renderRoot"),n._generated={},ue=n,this._latestRenderContext=n;try{let o=f(this,x,Ba).call(this,e,t,n);if(o.length!==1)throw new Error(`There can only be one root element, received: ${o.length}. Please wrap these elements in a <vstack></vstack> or <hstack></hstack> to continue. Fragments cannot be used as a root element.`);let s=o[0];if(s==="[object Promise]")throw new Error('Root elements cannot be async. To use data from an async endpoint, please use "const [data] = useState(async () => {/** your async code */})".');if(typeof s=="string")throw new Error("The root element must return a valid block, not a string. Try wrapping the element in a <text>your content</text> tag to continue.");return n._latestRenderContent=s,s}catch(o){if(o instanceof Bt)return;throw o}finally{ue=null}},Ba=function(e,t,n){n.push({namespace:e.name||"anonymous",...t});try{let o=e(t,n.devvitContext);if(o instanceof Promise)throw new Error(`Components (found: ${e.name??"unknown component"}) cannot be async. To use data from an async endpoint, please use "const [data] = useState(async () => {/** your async code */})".`);return f(this,x,Ua).call(this,o,n)}finally{n.pop()}},ds=function(e,t){return e=e.flat(1/0),e.flatMap((n,o)=>(n&&typeof n=="object"&&"props"in n&&(n.props?.key||(n.props=n.props??{},n.props.key=`${o}`)),f(this,x,Ua).call(this,n,t)))},Ua=function(e,t){if(Array.isArray(e))return f(this,x,ds).call(this,e,t);if(jp(e))if(e.type===void 0)try{return t.push({namespace:"fragment",...e.props}),f(this,x,ds).call(this,e.children,t)}finally{t.pop()}else if(typeof e.type=="function"){let n={...e.props,children:e.children.flat(1/0)};return f(this,x,Ba).call(this,e.type,n,t)}else try{t.push({namespace:e.type,...e.props});let n=f(this,x,ds).call(this,e.children,t),o=f(this,x,Xl).call(this,e.props??{});return[{type:e.type,children:n,props:o}]}finally{t.pop()}else return[(e??"").toString()]},Xl=function(e){let t={};for(let n in e)if(!(typeof e[n]>"u"))if(typeof e[n]=="function"){let o=le({namespace:n,key:!1,initializer:({hookId:s})=>({hookId:s,state:null,onUIEvent:a=>{if(a.userAction)return e[n](a.userAction.data);if(a.webView?.postMessage){let c=a.webView.postMessage.jsonString?JSON.parse(a.webView.postMessage.jsonString):a.webView.postMessage.message;return e[n](c)}}})});t[n]=o.hookId,"captureHookRef"in e[n]&&e[n].captureHookRef()}else{let o=JSON.parse(JSON.stringify(e[n]));o!=null&&(t[n]=o)}return t};function jp(i){return typeof i=="object"&&i!=null&&"type"in i}var Ql=i=>{let e=Number(i.trim().split(".").pop());return isNaN(e)?void 0:e},Yl=i=>{let[e,t,n]=i.trim().split(";");if(!e||!t||!n){console.warn(`Received a malformed devvit-user-agent! Received: '${i}'`);return}if(e!=="Reddit"){console.warn(`Received unknown company name in user agent! Received: '${i}'`);return}if(t==="iOS"){let o=Ql(n);if(o===void 0){console.warn(`Could not parse version number from user agent! Received: '${i}'`);return}return{company:"Reddit",platform:"iOS",rawVersion:n,versionNumber:o}}if(t==="Android"){let o=Ql(n);if(o===void 0){console.warn(`Could not parse version number from user agent! Received: '${i}'`);return}return{company:"Reddit",platform:"Android",rawVersion:n,versionNumber:o}}if(t==="Shreddit")return{company:"Reddit",platform:"Shreddit",rawVersion:n};if(t==="Play")return{company:"Reddit",platform:"Play",rawVersion:n};console.warn("Received unknown platform:",t)},eu=i=>i?i.platform==="Android"?i.versionNumber<1875012:i.platform==="iOS"?i.versionNumber<614973:!1:(console.warn(`Could not parse devvit-user-agent! Received: '${JSON.stringify(i)}'`),!1),Vp=i=>{switch(i){case"Android":return"https://play.google.com/store/apps/details?id=com.reddit.frontpage";case"iOS":return"https://apps.apple.com/us/app/reddit/id1064216828";case"Play":case"Shreddit":break;default:console.error(`No upgrade link for platform: ${i}`)}},Wp=({platform:i},e)=>u.createElement("blocks",null,u.createElement("vstack",{alignment:"middle center",height:100,width:100},u.createElement("vstack",{maxWidth:"300px",gap:"large",alignment:"middle center"},u.createElement("vstack",{gap:"medium",alignment:"middle center"},u.createElement("image",{imageHeight:100,imageWidth:100,url:"https://i.redd.it/p1vmc5ulmpib1.png"}),u.createElement("text",{size:"large",weight:"bold",wrap:!0,alignment:"center"},"Uh oh, the app you're trying to use requires the latest version of Reddit. Please upgrade your app to continue.")),u.createElement("hstack",{alignment:"middle center"},u.createElement("button",{onPress:()=>{let t=Vp(i);t?e.ui.navigateTo(t):console.warn("No upgrade link found for platform:",i)}},"Upgrade"))))),tu=i=>()=>u.createElement(Wp,{platform:i});var Gp=()=>u.createElement("vstack",{alignment:"center middle",width:"100%",height:"100%"},u.createElement("text",null,"This feature is not available yet")),Jp=[[us,us.methods.renderPostContent,(i,e)=>u.customPostType?.render(e)??null],[us,us.methods.renderPostComposer,(i,e)=>u.createElement(Gp,null)]];function zp(i){return async(e,t)=>{let n=Yl(t["devvit-user-agent"]?.values?.[0]??"");if(n&&eu(n)){let s=new Dt(tu(n.platform));return iu.fromJSON(await s.handle(e,t))}let o=new Dt(i);return iu.fromJSON(await o.handle(e,t))}}function nu(i){for(let[e,t,n]of Jp)i.provides(e),O(t.name,zp(n))}var Ti,qn,lt,Nt,Lt,Ri,Oi,_t,ut,$n,Kn,Ht,H,D=class D extends Mo{static configure(e){d(this,lt,{...r(this,lt),...e}),Ce(e.http)&&this.use(k.HTTPDefinition),(e.redis===void 0||Ce(e.kvStore)||Ce(e.redis))&&(this.use(k.KVStoreDefinition),this.use(k.RedisAPIDefinition)),Ce(e.media)&&this.use(k.MediaServiceDefinition),Ce(e.modLog)&&this.use(k.ModlogDefinition),Ce(e.redditAPI)&&(this.use(k.FlairDefinition),this.use(k.GraphQLDefinition),this.use(k.LinksAndCommentsDefinition),this.use(k.ListingsDefinition),this.use(k.ModerationDefinition),this.use(k.ModNoteDefinition),this.use(k.NewModmailDefinition),this.use(k.PrivateMessagesDefinition),this.use(k.SubredditsDefinition),this.use(k.UsersDefinition),this.use(k.WidgetsDefinition),this.use(k.WikiDefinition)),Ce(e.realtime)&&this.use(k.RealtimeDefinition),Ce(e.userActions)&&this.use(k.UserActionsDefinition)}static addMenuItem(e){r(this,Oi).push(e)}static addCustomPostType(e){d(this,Nt,e)}static createForm(e,t){let n=`form.${r(this,Lt).size}`;return r(this,Lt).set(n,{form:e,onSubmit:t}),n}static addSchedulerJob(e){if(r(this,H)[k.SchedulerDefinition.fullName]||this.use(k.SchedulerDefinition),r(this,_t).has(e.name))throw new Error(`Job ${e.name} is already defined`);r(this,_t).set(e.name,e.onRun)}static addSettings(e){It(e);let t=e.filter(o=>o.type==="group"||!o.scope||o.scope==="installation"),n=e.filter(o=>o.type!=="group"&&o.scope==="app");t.length>0&&d(this,Ri,t),n.length>0&&d(this,Ti,n),r(this,H)[k.SettingsDefinition.fullName]||this.use(k.SettingsDefinition)}static addTrigger(e){if("events"in e){for(let t of e.events)this.addTrigger({event:t,onEvent:(n,o)=>e.onEvent(n,o)});return this}return r(this,ut).has(e.event)?r(this,ut).get(e.event)?.push(e.onEvent):r(this,ut).set(e.event,[e.onEvent]),D}static provide(e){r(this,Kn).push(e)}static use(e,t){r(this,Ht)[e.fullName]={def:e,options:t??{},handler:void 0};let n={};for(let o of Object.values(e.methods))n[o.name]=(s,a)=>r(this,Ht)[e.fullName].handler?.[o.name]?.(o.requestType?.fromPartial(s??{}),a);return r(this,H)[e.fullName]=n,n}static get redditAPIPlugins(){if(!Ce(r(this,lt).redditAPI))throw new Error("Reddit API is not enabled. You can enable it by passing `redditAPI: true` to `Devvit.configure`.");return{Flair:r(this,H)[k.FlairDefinition.fullName],GraphQL:r(this,H)[k.GraphQLDefinition.fullName],LinksAndComments:r(this,H)[k.LinksAndCommentsDefinition.fullName],Listings:r(this,H)[k.ListingsDefinition.fullName],Moderation:r(this,H)[k.ModerationDefinition.fullName],ModNote:r(this,H)[k.ModNoteDefinition.fullName],NewModmail:r(this,H)[k.NewModmailDefinition.fullName],PrivateMessages:r(this,H)[k.PrivateMessagesDefinition.fullName],Subreddits:r(this,H)[k.SubredditsDefinition.fullName],Users:r(this,H)[k.UsersDefinition.fullName],Widgets:r(this,H)[k.WidgetsDefinition.fullName],Wiki:r(this,H)[k.WikiDefinition.fullName]}}static get modLogPlugin(){let e=r(this,H)[k.ModlogDefinition.fullName];if(!e)throw new Error("ModLog is not enabled. You can enable it by passing `modLog: true` to `Devvit.configure`");return e}static get schedulerPlugin(){let e=r(this,H)[k.SchedulerDefinition.fullName];if(!e)throw new Error("Scheduler is not enabled. You can enable it by calling `Devvit.addSchedulerJob` at the top level of your app.");return e}static get kvStorePlugin(){let e=r(this,H)[k.KVStoreDefinition.fullName];if(!e)throw new Error("Key Value Store is not enabled. You can enable it by passing `kvStore: true` to `Devvit.configure`");return e}static get redisPlugin(){let e=r(this,H)[k.RedisAPIDefinition.fullName];if(!e)throw new Error("Redis is not enabled. You can enable it by passing `redis: true` to `Devvit.configure`");return e}static get mediaPlugin(){let e=r(this,H)[k.MediaServiceDefinition.fullName];if(!e)throw new Error("MediaService is not enabled. You can enable it by passing `media: true` to `Devvit.configure`");return e}static get settingsPlugin(){let e=r(this,H)[k.SettingsDefinition.fullName];if(!e)throw new Error("Settings must first be configured with `Devvit.addSettings()` before they can be accessed");return e}static get realtimePlugin(){let e=r(this,H)[k.RealtimeDefinition.fullName];if(!e)throw new Error("Realtime is not enabled. You can enable it by passing `realtime: true` to `Devvit.configure`");return e}static get userActionsPlugin(){if(!(Ce(r(this,lt).userActions)&&Ce(r(this,lt).redditAPI)))throw new Error("UserActions is not enabled. You can enable it by passing both `userActions: true` and `redditAPI: true` to `Devvit.configure`");return r(this,H)[k.UserActionsDefinition.fullName]}static get menuItems(){return r(this,Oi)}static get customPostType(){return r(this,Nt)}static get formDefinitions(){return r(this,Lt)}static get scheduledJobHandlers(){return r(this,_t)}static get installationSettings(){return r(this,Ri)}static get appSettings(){return r(this,Ti)}static get triggerOnEventHandlers(){return r(this,ut)}static get assets(){return r(this,qn)}static get webViewAssets(){return r(this,$n)}constructor(e){super(e),d(D,qn,e.assets??{}),d(D,$n,e.webviewAssets??{});for(let t in r(D,Ht)){let n=r(D,Ht)[t];n.handler=e.use(n.def,n.options)}r(D,Oi).length>0&&ll(e),r(D,_t).size>0&&ul(e),r(D,Nt)&&(Yd(e),nu(e)),(r(D,Nt)||r(D,Lt).size>0)&&El(e),r(D,Ri)&&el(e),r(D,Ti)&&Bd(e),r(D,ut).size>0&&cl(e);for(let t of r(D,Kn))e.provides(t)}};Ti=new WeakMap,qn=new WeakMap,lt=new WeakMap,Nt=new WeakMap,Lt=new WeakMap,Ri=new WeakMap,Oi=new WeakMap,_t=new WeakMap,ut=new WeakMap,$n=new WeakMap,Kn=new WeakMap,Ht=new WeakMap,H=new WeakMap,D.debug={},l(D,Ti),l(D,qn,{}),l(D,lt,{}),l(D,Nt),l(D,Lt,new Map),l(D,Ri),l(D,Oi,[]),l(D,_t,new Map),l(D,ut,new Map),l(D,$n,{}),l(D,Kn,[]),l(D,Ht,{}),l(D,H,{});var u=D;(e=>{function i(t,n,...o){return{type:t,props:n,children:o}}e.createElement=i})(u||(u={}));function K(i){let e=Object.getOwnPropertyDescriptors(i.constructor.prototype);for(let[t,n]of Object.entries(e))n.get&&Object.defineProperty(i,t,{...n,enumerable:!0})}var Da;(function(i){i[i.bold=1]="bold",i[i.italic=2]="italic",i[i.underline=4]="underline",i[i.strikethrough=8]="strikethrough",i[i.subscript=16]="subscript",i[i.superscript=32]="superscript",i[i.monospace=64]="monospace"})(Da||(Da={}));var ru="text",ou="raw",su="br",au="link",du="c/",lu="p/",uu="r/",cu="u/",mu="@",pu="spoilertext",gu="par",fu="h",hu="hr",yu="blockquote",bu="code",vu="li",ku="list",Cu="L",Pu="R",Su="C",wu="table",xu="embed",Fu="img",Au="gif",Iu="video";function Eu(i){return{e:Au,id:i.mediaId,...i.caption&&{c:i.caption},...i.blur&&{o:i.blur}}}function Tu(i,e){let t={},n=[];return Object.assign(t,Zn(t,n),Xn(t,n),Qn(t,n),tr(t,n),ir(t,n),nr(t,n)),e(t),{e:yu,c:n,...i.author&&{a:i.author}}}function Ru(i,e){let t={},n=[];return Object.assign(t,La(t,n)),e(t),{e:bu,c:n,...i.language&&{l:i.language}}}function Ou(i){return{e:du,t:i.permalink}}function Mu(i,e){let t={},n=[];return Object.assign(t,La(t,n),er(t,n)),e(t),{e:fu,l:i.level,c:n}}function Bu(i){return{e:xu,u:i.sourceUrl,c:i.contentUrl,x:i.width,y:i.height}}function Uu(){return{e:hu}}function Du(i){return{e:Fu,id:i.mediaId,...i.caption&&{c:i.caption},...i.blur&&{o:i.blur}}}function Nu(){return{e:su}}function Lu(i){return{e:au,t:i.text,u:i.url,...i.formatting&&{f:i.formatting},...i.tooltip&&{a:i.tooltip}}}function _u(i,e){let t={},n=[];return Object.assign(t,tc(t,n)),e(t),{e:ku,o:i.ordered,c:n}}function Hu(i){let e={},t=[];return Object.assign(e,Zn(e,t),Xn(e,t),Qn(e,t),cs(e,t),tr(e,t),ir(e,t),nr(e,t)),i(e),{e:vu,c:t}}function ju(i){let e={},t=[];return Object.assign(e,ms(e,t),er(e,t),Na(e,t),_a(e,t),Yn(e,t)),i(e),{e:gu,c:t}}function Vu(i){return{e:lu,t:i.permalink}}function Wu(i){return{e:ou,t:i}}function Gu(i){let e={},t=[];return Object.assign(e,ms(e,t),er(e,t),Na(e,t)),i(e),{e:pu,c:t}}function Ju(i){return{e:uu,t:i.subredditName,l:i.showPrefix}}function zu(i){let e={},t=[],n=[];return Object.assign(e,ic(e,t,n)),i(e),{e:wu,h:t,c:n}}function qu(i){let[e,t]=ec();return i(e),{c:t}}function $u(i,e){let[t,n]=ec();e(t);let o;switch(i.columnAlignment){case"left":o=Cu;break;case"right":o=Pu;break;case"center":o=Su;break}return{...o&&{a:o},...n&&{c:n}}}function Ku(i){let e={},t=[];return Object.assign(e,nc(e,t)),i(e),t}function Zu(i){return{e:ru,t:i.text,...i.formatting&&{f:i.formatting}}}function Xu(i){return{e:cu,t:i.username,l:i.showPrefix}}function Qu(i){return{e:mu,t:i.username,l:i.showPrefix}}function Yu(i){return{e:Iu,id:i.mediaId,...i.caption&&{c:i.caption},...i.blur&&{o:i.blur},...i.thumbnail&&{p:i.thumbnail},...i.convertToGif&&{gifify:i.convertToGif}}}function ec(){let i={},e=[];return Object.assign(i,ms(i,e),er(i,e),_a(i,e),Yn(i,e)),[i,e]}function Zn(i,e){return{blockQuote(t,n){return e.push(Tu(t,n)),i}}}function Xn(i,e){return{codeBlock(t,n){return e.push(Ru(t,n)),i}}}function rc(i,e){return{embed(t){return e.push(Bu(t)),i}}}function Qn(i,e){return{heading(t,n){return e.push(Mu(t,n)),i}}}function cs(i,e){return{horizontalRule(){return e.push(Uu()),i}}}function Yn(i,e){return{image(t){return e.push(Du(t)),i},animatedImage(t){return e.push(Eu(t)),i}}}function Na(i,e){return{linebreak(){return e.push(Nu()),i}}}function er(i,e){return{link(t){return e.push(Lu(t)),i},commentLink(t){return e.push(Ou(t)),i},postLink(t){return e.push(Vu(t)),i},subredditLink(t){return e.push(Ju(t)),i},userLink(t){return e.push(Xu(t)),i},userMention(t){return e.push(Qu(t)),i}}}function tr(i,e){return{list(t,n){return e.push(_u(t,n)),i}}}function tc(i,e){return{item(t){return e.push(Hu(t)),i}}}function ir(i,e){return{paragraph(t){return e.push(ju(t)),i}}}function La(i,e){return{rawText(t){return e.push(Wu(t)),i}}}function _a(i,e){return{spoiler(t){return e.push(Gu(t)),i}}}function ic(i,e,t){return{headerCell(n,o){return e.push($u(n,o)),i},row(n){return t.push(Ku(n)),i}}}function nr(i,e){return{table(t){return e.push(zu(t)),i}}}function nc(i,e){return{cell(t){return e.push(qu(t)),i}}}function ms(i,e){return{text(t){return e.push(Zu(t)),i}}}function oc(i,e){return{video(t){return e.push(Yu(t)),i}}}var qp=function(i,e,t,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?i!==e||!o:!e.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(i,t):o?o.value=t:e.set(i,t),t},$p=function(i,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?i!==e||!n:!e.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(i):n?n.value:e.get(i)},ps,jt=class{constructor(){ps.set(this,void 0);let e=[];Object.assign(this,ir(this,e),Qn(this,e),cs(this,e),Zn(this,e),Xn(this,e),rc(this,e),tr(this,e),nr(this,e),Yn(this,e),oc(this,e)),qp(this,ps,{document:e},"f")}build(){return JSON.stringify($p(this,ps,"f"))}paragraph(e){return this}heading(e,t){return this}horizontalRule(){return this}blockQuote(e,t){return this}codeBlock(e,t){return this}embed(e){return this}list(e,t){return this}table(e){return this}image(e){return this}animatedImage(e){return this}video(e){return this}};ps=new WeakMap;function Mi(i){let e;return i instanceof jt?e=i.build():typeof i=="object"?e=JSON.stringify(i):e=i,e}var sc=100,ac=1/0,Vt,Wt,ct,Bi,Ui,gs,V=class{constructor(e){l(this,Ui);l(this,Vt);l(this,Wt);l(this,ct);l(this,Bi,!1);this.pageSize=sc;this.limit=ac;this.children=[];K(this),this._fetch=e.fetch,this.pageSize=e.pageSize??sc,this.limit=e.limit??ac,d(this,Wt,e.after),d(this,Vt,e.before),d(this,ct,e.more),e.children&&(this.children=e.children)}get hasMore(){return!r(this,Bi)||!!(r(this,Wt)||r(this,Vt)||r(this,ct))}async*[Symbol.asyncIterator](){let e=0;for(;;){if(e===this.children.length)if(this.hasMore){if((await f(this,Ui,gs).call(this)).length===0)break}else break;if(yield this.children[e],e++,e===this.limit)break}}setMore(e){d(this,ct,e)}preventInitialFetch(){d(this,Bi,!0)}async all(){for(;this.hasMore&&this.children.length<this.limit;)await f(this,Ui,gs).call(this);return this.children.slice(0,this.limit)}async get(e){let t=e<=this.limit?e:this.limit;for(;this.hasMore&&this.children.length<t;)await f(this,Ui,gs).call(this);return this.children.slice(0,t)}};Vt=new WeakMap,Wt=new WeakMap,ct=new WeakMap,Bi=new WeakMap,Ui=new WeakSet,gs=async function(){if(!this.hasMore)throw new Error("This listing does not have any more items to load.");let{children:e,before:t,after:n,more:o}=await this._fetch({before:r(this,Vt),after:r(this,Wt),limit:this.pageSize,more:r(this,ct)});return this.children.push(...e),d(this,Vt,t),d(this,Wt,n),d(this,ct,o),d(this,Bi,!0),e};var rr,Ha,Se=class{constructor(){}static get(e,t){let n=u.redditAPIPlugins.ModNote;return new V({hasMore:!0,before:e.before,limit:e.limit,pageSize:e.limit,fetch:async o=>{let s=await n.GetNotes({subreddit:e.subreddit,user:e.user,filter:e.filter,before:o.before,limit:o.limit},t);return{children:s.modNotes?.map(a=>f(this,rr,Ha).call(this,a))||[],before:s.hasNextPage?s.endCursor:void 0,hasMore:s.hasNextPage}}})}static async delete(e,t){let n=u.redditAPIPlugins.ModNote,{deleted:o}=await n.DeleteNotes(e,t);return!!o}static async add(e,t){let o=await u.redditAPIPlugins.ModNote.PostNotes(e,t);if(!o?.created)throw new Error("Failed to create mod note");return f(this,rr,Ha).call(this,o.created)}static async addRemovalNote(e,t){await u.redditAPIPlugins.ModNote.PostRemovalNote(e,t)}};rr=new WeakSet,Ha=function(e){return p(e.id,"Mod note ID is null or undefined"),p(e.createdAt,"Mod note createdAt is null or undefined"),p(e.type,"Mod note type is null or undefined"),p(e.subreddit,"Mod note subreddit is null or undefined"),p(e.subredditId,"Mod note subredditId is null or undefined"),p(e.operator,"Mod note operator is null or undefined"),p(e.operatorId,"Mod note operatorId is null or undefined"),p(e.user,"Mod note user is null or undefined"),p(e.userId,"Mod note userId is null or undefined"),p(e.userNoteData,"Mod note userNote is null or undefined"),p(e.modActionData,"Mod note modAction is null or undefined"),{id:e.id,user:{id:te(e.userId??""),name:e.user},subreddit:{id:$(e.subredditId??""),name:e.subreddit},operator:{id:te(e.operatorId??""),name:e.operator},createdAt:new Date(e.createdAt*1e3),userNote:{note:e.userNoteData?.note,redditId:e.userNoteData?.redditId?ye(e.userNoteData?.redditId):void 0,label:e.userNoteData?.label},type:e.type}},l(Se,rr);var X=class{static queryWithQueryString(e,t){return u.redditAPIPlugins.GraphQL.Query({query:e},t)}static query(e,t,n,o){return u.redditAPIPlugins.GraphQL.PersistedQuery({operationName:e,id:t,variables:n},o)}};var dc=["all","wiki","posts","access","mail","config","flair","channels","chat_config","chat_operator","community_chat"];function Kp(i,e){return e.map(t=>(i.includes(t)?"+":"-")+t).join(",")}function ja(i){return Kp(i,dc)}function lc(i){return i.filter(e=>dc.includes(e))}import"@devvit/protos";var Zp=(t=>(t.User="USER_FLAIR",t.Post="LINK_FLAIR",t))(Zp||{}),Gt,Di,Ni,Li,_i,Hi,ji,Vi,Wi,Gi,Ji,fs,Ie=class Ie{constructor(e,t,n){l(this,Gt);l(this,Di);l(this,Ni);l(this,Li);l(this,_i);l(this,Hi);l(this,ji);l(this,Vi);l(this,Wi);l(this,Gi);K(this),p(e.id),p(e.text),d(this,Gt,e.id),d(this,Di,t),d(this,Ni,e.text),d(this,Li,Xp(e.textColor)),d(this,_i,Qp(e.backgroundColor)),d(this,Hi,Yp(e.allowableContent)),d(this,ji,e.modOnly),d(this,Vi,e.maxEmojis),d(this,Wi,e.textEditable),d(this,Gi,n)}get id(){return r(this,Gt)}get text(){return r(this,Ni)}get textColor(){return r(this,Li)}get backgroundColor(){return r(this,_i)}get allowableContent(){return r(this,Hi)}get modOnly(){return r(this,ji)}get maxEmojis(){return r(this,Vi)}get allowUserEdits(){return r(this,Wi)}async delete(){return Ie.deleteFlairTemplate(r(this,Gt),r(this,Di),r(this,Gi))}async edit(e){return Ie.editFlairTemplate({id:r(this,Gt),subredditName:r(this,Di),text:e.text??r(this,Ni),allowableContent:e.allowableContent??r(this,Hi),backgroundColor:e.backgroundColor??r(this,_i),maxEmojis:e.maxEmojis??r(this,Vi),modOnly:e.modOnly??r(this,ji),textColor:e.textColor??r(this,Li),allowUserEdits:e.allowUserEdits??r(this,Wi)},r(this,Gi))}static async createPostFlairTemplate(e,t){var n;return f(n=Ie,Ji,fs).call(n,{...e,flairType:"LINK_FLAIR"},t)}static async createUserFlairTemplate(e,t){var n;return f(n=Ie,Ji,fs).call(n,{...e,flairType:"USER_FLAIR"},t)}static async editFlairTemplate(e,t){var n;return f(n=Ie,Ji,fs).call(n,e,t)}static async getPostFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.LinkFlair({subreddit:e},t)).flair?.map(s=>new Ie(s,e,t))||[]}static async getUserFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.UserFlair({subreddit:e},t)).flair?.map(s=>new Ie(s,e,t))||[]}static async deleteFlairTemplate(e,t,n){await u.redditAPIPlugins.Flair.DeleteFlairTemplate({subreddit:e,flairTemplateId:t},n)}};Gt=new WeakMap,Di=new WeakMap,Ni=new WeakMap,Li=new WeakMap,_i=new WeakMap,Hi=new WeakMap,ji=new WeakMap,Vi=new WeakMap,Wi=new WeakMap,Gi=new WeakMap,Ji=new WeakSet,fs=async function(e,t){let{subredditName:n,allowableContent:o="all",backgroundColor:s="transparent",flairType:a="",maxEmojis:c=10,modOnly:m=!1,text:h,textColor:v="dark",allowUserEdits:y=!1,id:P=""}=e;if(m&&y)throw new Error("Cannot have a mod only flair that is editable by users");let A=await u.redditAPIPlugins.Flair.FlairTemplate({subreddit:n,allowableContent:o,backgroundColor:s,flairType:a,maxEmojis:c,modOnly:m,text:h,textColor:v,textEditable:y,flairTemplateId:P,cssClass:"",overrideCss:!1},t);return new Ie(A,n,t)},l(Ie,Ji);var se=Ie;function or(i){return{flairCssClass:i.flairCssClass,user:i.user,flairText:i.flairText}}var Be,Va,uc,Wa,mt=class mt{static async getUserFlairBySubreddit(e,t){return u.redditAPIPlugins.Flair.FlairList(e,t)}static setUserFlair(e,t){var n;return f(n=mt,Be,Va).call(n,e,t)}static setUserFlairBatch(e,t,n){var o;return f(o=mt,Be,uc).call(o,e,t,n)}static setPostFlair(e,t){var n;return f(n=mt,Be,Va).call(n,{...e,postId:de(e.postId)},t)}static async removePostFlair(e,t,n){var o;return f(o=mt,Be,Wa).call(o,e,t,void 0,n)}static async removeUserFlair(e,t,n){var o;return f(o=mt,Be,Wa).call(o,e,void 0,t,n)}};Be=new WeakSet,Va=async function(e,t){await u.redditAPIPlugins.Flair.SelectFlair({subreddit:e.subredditName,flairTemplateId:e.flairTemplateId??"",text:e.text??"",name:e.username,link:e.postId,backgroundColor:e.backgroundColor??"",textColor:e.textColor??"dark",cssClass:e.cssClass??"",returnRtjson:"none"},t)},uc=async function(e,t,n){if(!t.length)return[];if(t.length>100)throw new Error("Unexpected input: flairs array cannot be longer than 100 entries.");let s=",",a=t.map(h=>{for(let v in h)if(h[v]?.includes(s))throw new Error(`Unexpected input: ${v} cannot contain the "," character`);return[h.username,h.text||"",h.cssClass||""].join(s)}).join(`
|
|
4
|
+
`);return(await u.redditAPIPlugins.Flair.FlairCsv({subreddit:e,flairCsv:a},n)).result},Wa=async function(e,t,n,o){await u.redditAPIPlugins.Flair.SelectFlair({subreddit:e,name:n??"",link:t??"",flairTemplateId:"",backgroundColor:"",text:"",textColor:"",cssClass:"",returnRtjson:"none"},o)},l(mt,Be);var ce=mt;function Xp(i){if(p(i,"Flair text color is required"),i==="light"||i==="dark")return i;throw new Error(`Invalid flair text color: ${i}`)}function Qp(i){if(!i||i.length===0||i==="transparent")return"transparent";if(/^#([A-Fa-f0-9]{6})$/.test(i))return i;throw new Error(`Invalid flair background color: ${i}`)}function Yp(i){if(i==="all"||i==="text"||i==="emoji")return i;throw new Error(`Invalid allowable content: ${i}`)}import"@devvit/protos";import{Block as gc,UIResponse as dg}from"@devvit/protos";var za=id(pc(),1);var Ja=i=>"text"in i?i.text:ag(i.richtext),ag=i=>i instanceof jt?i.build():typeof i=="object"?JSON.stringify(i):i;var lg={NONE:0,BLOCKS:1,UNRECOGNIZED:-1},zi,ar,qi,dr,$i,lr,ur,cr,zt,mr,pr,gr,fr,hr,yr,pt,br,vr,qt,Ki,gt,Zi,Xi,Qi,ft,ht,yt,Yi,bt,vt,kt,Ve,kr,Cr,en,tn,B,N=class N{constructor(e,t){l(this,zi);l(this,ar);l(this,qi);l(this,dr);l(this,$i);l(this,lr);l(this,ur);l(this,cr);l(this,zt);l(this,mr);l(this,pr);l(this,gr);l(this,fr);l(this,hr);l(this,yr);l(this,pt);l(this,br);l(this,vr);l(this,qt);l(this,Ki);l(this,gt);l(this,Zi);l(this,Xi);l(this,Qi);l(this,ft);l(this,ht);l(this,yt);l(this,Yi);l(this,bt);l(this,vt);l(this,kt);l(this,Ve);l(this,kr);l(this,Cr);l(this,en);l(this,tn);l(this,B);K(this),p(e.id,"Post is missing id"),p(e.title,"Post is missing title"),p(e.createdUtc,"Post is missing created date"),p(e.author,"Post is missing author name"),p(e.subreddit,"Post is missing subreddit name"),p(e.subredditId,"Post is missing subreddit id"),p(e.url,"Post is missing url"),p(e.permalink,"Post is missing permalink"),d(this,zi,de(`t3_${e.id}`)),d(this,qi,e.author),d(this,ar,e.authorFullname?te(e.authorFullname):void 0),d(this,$i,$(e.subredditId)),d(this,lr,e.subreddit),d(this,gr,e.score??0),d(this,fr,e.numComments??0),d(this,hr,e.numReports??0);let n=new Date(0);n.setUTCSeconds(e.createdUtc),d(this,dr,n),d(this,cr,e.title),d(this,zt,e.selftext),d(this,mr,e.selftextHtml),d(this,pr,e.url),d(this,ur,e.permalink),e.thumbnail&&e.thumbnail!=="self"&&e.thumbnail!=="nsfw"&&e.thumbnailHeight!=null&&e.thumbnailWidth!=null&&d(this,yr,{url:e.thumbnail,height:e.thumbnailHeight,width:e.thumbnailWidth}),d(this,pt,e.approved??!1),d(this,br,e.approvedAtUtc??0),d(this,vr,e.bannedAtUtc??0),d(this,gt,e.removed??!1),d(this,Zi,e.removedBy),d(this,Xi,e.removedByCategory),d(this,qt,e.spam??!1),d(this,Ki,e.stickied??!1),d(this,Qi,e.archived??!1),d(this,ft,e.edited??!1),d(this,ht,e.locked??!1),d(this,yt,e.over18??!1),d(this,Yi,e.quarantine??!1),d(this,bt,e.spoiler),d(this,vt,e.hidden??!1),d(this,kt,e.ignoreReports??!1),d(this,Ve,e.distinguished),d(this,Cr,e.secureMedia),d(this,en,(e.modReports??[]).map(([o])=>o)),d(this,tn,(e.userReports??[]).map(([o])=>o)),d(this,B,t),(e.linkFlairBackgroundColor||e.linkFlairCssClass||e.linkFlairText||e.linkFlairType||e.linkFlairTemplateId||e.linkFlairRichtext||e.linkFlairTextColor)&&d(this,kr,{backgroundColor:e.linkFlairBackgroundColor,cssClass:e.linkFlairCssClass,text:e.linkFlairText,type:e.linkFlairType,templateId:e.linkFlairTemplateId,richtext:(e.linkFlairRichtext??[]).map(({e:o,t:s,a,u:c})=>({elementType:o,text:s,emojiRef:a,url:c})),textColor:e.linkFlairTextColor})}get id(){return r(this,zi)}get authorId(){return r(this,ar)}get authorName(){return r(this,qi)}get subredditId(){return r(this,$i)}get subredditName(){return r(this,lr)}get permalink(){return r(this,ur)}get title(){return r(this,cr)}get body(){return r(this,zt)}get bodyHtml(){return r(this,mr)}get url(){return r(this,pr)}get thumbnail(){return r(this,yr)}get createdAt(){return r(this,dr)}get score(){return r(this,gr)}get numberOfComments(){return r(this,fr)}get numberOfReports(){return r(this,hr)}get approved(){return r(this,pt)}get approvedAtUtc(){return r(this,br)}get bannedAtUtc(){return r(this,vr)}get spam(){return r(this,qt)}get stickied(){return r(this,Ki)}get removed(){return r(this,gt)}get removedBy(){return r(this,Zi)}get removedByCategory(){return r(this,Xi)}get archived(){return r(this,Qi)}get edited(){return r(this,ft)}get locked(){return r(this,ht)}get nsfw(){return r(this,yt)}get quarantined(){return r(this,Yi)}get spoiler(){return r(this,bt)}get hidden(){return r(this,vt)}get ignoringReports(){return r(this,kt)}get distinguishedBy(){return r(this,Ve)}get comments(){return Q.getComments({postId:this.id},r(this,B))}get flair(){return r(this,kr)}get secureMedia(){return r(this,Cr)}get userReportReasons(){return r(this,tn)}get modReportReasons(){return r(this,en)}toJSON(){return{id:this.id,authorId:this.authorId,authorName:this.authorName,subredditId:this.subredditId,subredditName:this.subredditName,permalink:this.permalink,title:this.title,body:this.body,bodyHtml:this.bodyHtml,url:this.url,thumbnail:this.thumbnail,score:this.score,numberOfComments:this.numberOfComments,numberOfReports:this.numberOfReports,createdAt:this.createdAt,approved:this.approved,spam:this.spam,stickied:this.stickied,removed:this.removed,removedBy:r(this,Zi),removedByCategory:r(this,Xi),archived:this.archived,edited:this.edited,locked:this.locked,nsfw:this.nsfw,quarantined:this.quarantined,spoiler:this.spoiler,hidden:this.hidden,ignoringReports:this.ignoringReports,distinguishedBy:this.distinguishedBy,flair:this.flair,secureMedia:this.secureMedia,modReportReasons:r(this,en),userReportReasons:r(this,tn)}}isApproved(){return r(this,pt)}isSpam(){return r(this,qt)}isStickied(){return r(this,Ki)}isRemoved(){return r(this,gt)}isArchived(){return r(this,Qi)}isEdited(){return r(this,ft)}isLocked(){return r(this,ht)}isNsfw(){return r(this,yt)}isQuarantined(){return r(this,Yi)}isSpoiler(){return r(this,bt)}isHidden(){return r(this,vt)}isIgnoringReports(){return r(this,kt)}isDistinguishedBy(){return r(this,Ve)}async edit(e){let t=await N.edit({id:this.id,...e},r(this,B));d(this,zt,t.body),d(this,ft,t.edited)}async setSuggestedCommentSort(e){await N.setSuggestedCommentSort({id:this.id,subredditId:r(this,$i),suggestedSort:e},r(this,B))}async setCustomPostPreview(e){await N.setCustomPostPreview({id:this.id,ui:e},r(this,B))}async setTextFallback(e){let t=await N.setTextFallback(e,this.id,r(this,B));d(this,zt,t.body),d(this,ft,t.edited)}async addComment(e){return Q.submit({id:this.id,...e},r(this,B))}async delete(){return N.delete(this.id,r(this,B))}async approve(){await N.approve(this.id,r(this,B)),d(this,pt,!0),d(this,gt,!1)}async remove(e=!1){await N.remove(this.id,e,r(this,B)),d(this,gt,!0),d(this,qt,e),d(this,pt,!1)}async lock(){await N.lock(this.id,r(this,B)),d(this,ht,!0)}async unlock(){await N.unlock(this.id,r(this,B)),d(this,ht,!1)}async hide(){await N.hide(this.id,r(this,B)),d(this,vt,!0)}async unhide(){await N.unhide(this.id,r(this,B)),d(this,vt,!1)}async markAsNsfw(){await N.markAsNsfw(this.id,r(this,B)),d(this,yt,!0)}async unmarkAsNsfw(){await N.unmarkAsNsfw(this.id,r(this,B)),d(this,yt,!1)}async markAsSpoiler(){await N.markAsSpoiler(this.id,r(this,B)),d(this,bt,!0)}async unmarkAsSpoiler(){await N.unmarkAsSpoiler(this.id,r(this,B)),d(this,bt,!1)}async sticky(e){await N.sticky(this.id,e,r(this,B))}async unsticky(){await N.unsticky(this.id,r(this,B))}async distinguish(){let{distinguishedBy:e}=await N.distinguish(this.id,!1,r(this,B));d(this,Ve,e)}async distinguishAsAdmin(){let{distinguishedBy:e}=await N.distinguish(this.id,!0,r(this,B));d(this,Ve,e)}async undistinguish(){let{distinguishedBy:e}=await N.undistinguish(this.id,r(this,B));d(this,Ve,e)}async ignoreReports(){await N.ignoreReports(this.id,r(this,B)),d(this,kt,!0)}async unignoreReports(){await N.unignoreReports(this.id,r(this,B)),d(this,kt,!1)}async getAuthor(){return C.getByUsername(r(this,qi),r(this,B))}async crosspost(e){return N.crosspost({...e,postId:this.id},r(this,B))}addRemovalNote(e){return Se.addRemovalNote({itemIds:[r(this,zi)],...e},r(this,B))}async getEnrichedThumbnail(){return ug({id:this.id},r(this,B))}static async getById(e,t){let n=u.redditAPIPlugins.LinksAndComments,o=At(e)?e:`t3_${e}`,s=await n.Info({subreddits:[],thingIds:[o]},t);if(!s.data?.children?.length)throw new Error("could not find post");let a=s.data.children[0];if(!a?.data)throw new Error("could not find post");return new N(a.data,t)}static async submit(e,t){let{runAs:n="APP"}=e,o=he[n],s=o===he.USER?u.userActionsPlugin:u.redditAPIPlugins.LinksAndComments,a;if("preview"in e){p(t,"Missing metadata in `SubmitPostOptions`"),o===he.USER&&p(e.userGeneratedContent,"userGeneratedContent must be set in `SubmitPostOptions` when RunAs=USER for experience posts");let h=await new _e(()=>e.preview,void 0,{},t,void 0).buildBlocksUI(),v=gc.encode(h).finish(),{textFallback:y,...P}=e,b=y?Ja(y):"",A={kind:"custom",sr:e.subredditName,richtextJson:(0,za.fromByteArray)(v),richtextFallback:b,...P,runAs:o};a=await s.SubmitCustomPost(A,t)}else a=await s.Submit({kind:"kind"in e?e.kind:"url"in e?"link":"self",sr:e.subredditName,richtextJson:"richtext"in e?Mi(e.richtext):void 0,...e,runAs:o},t);if("kind"in e&&["image","video","videogif"].includes(e.kind)&&!a.json?.data?.id){if(e.kind==="image"&&"imageUrls"in e)throw new Error(`Image post type with ${e.imageUrls} is being created asynchronously and should be updated in the subreddit soon.`);if("videoPosterUrl"in e)throw new Error(`Post of ${e.kind} type with ${e.videoPosterUrl} is being created asynchronously and should be updated in the subreddit soon.`)}if(!a.json?.data?.id||a.json?.errors?.length)throw new Error(`failed to submit post - either post ID is empty or request failed with errors: ${a.json?.errors}`);return N.getById(`t3_${a.json.data.id}`,t)}static async crosspost(e,t){let{runAs:n="APP"}=e,o=he[n],s=o===he.USER?u.userActionsPlugin:u.redditAPIPlugins.LinksAndComments,{postId:a,subredditName:c,...m}=e,h=await s.Submit({kind:"crosspost",sr:c,crosspostFullname:de(a),...m,runAs:o},t);if(!h.json?.data?.id||h.json?.errors?.length)throw new Error("failed to crosspost post");return N.getById(`t3_${h.json.data.id}`,t)}static async edit(e,t){let n=u.redditAPIPlugins.LinksAndComments,{id:o}=e,s;if("richtext"in e&&(s=Mi(e.richtext)),(await n.EditUserText({thingId:o,text:"text"in e?e.text:"",richtextJson:s,runAs:he.APP},t)).json?.errors?.length)throw new Error("Failed to edit post");return N.getById(o,t)}static async setSuggestedCommentSort(e,t){if(!(await X.query("SetSuggestedSort","cf6052acc7fefaa65b710625b81dba8041f258313aafe9730e2a3dc855e5d10d",{input:{subredditId:e.subredditId,postId:e.id,sort:e.suggestedSort}},t)).data?.setSuggestedSort?.ok)throw new Error("Failed to set suggested sort")}static async setCustomPostPreview(e,t){if(!t)throw new Error("Failed to set custom post preview. Metadata not found");let n=u.redditAPIPlugins.LinksAndComments,o=new Dt(e.ui),a=dg.fromJSON(await o.handle({events:[]},t)).blocks,c=(0,za.fromByteArray)(gc.encode(a).finish());await n.SetCustomPostPreview({thingId:e.id,bodyType:lg.BLOCKS,blocksRenderContent:c},t)}static async setTextFallback(e,t,n){if(!("text"in e)&&!("richtext"in e))throw new Error(`No text fallback provided for post ${t}.`);let o=u.redditAPIPlugins.LinksAndComments,s=Ja(e);if((await o.EditCustomPost({thingId:t,richtextFallback:s},n)).json?.errors?.length)throw new Error("Failed to set post text fallback");return N.getById(t,n)}static async delete(e,t){await u.redditAPIPlugins.LinksAndComments.Del({id:e},t)}static async approve(e,t){await u.redditAPIPlugins.Moderation.Approve({id:e},t)}static async remove(e,t=!1,n){await u.redditAPIPlugins.Moderation.Remove({id:e,spam:t},n)}static async hide(e,t){await u.redditAPIPlugins.LinksAndComments.Hide({id:e},t)}static async unhide(e,t){await u.redditAPIPlugins.LinksAndComments.Unhide({id:e},t)}static async markAsNsfw(e,t){await u.redditAPIPlugins.LinksAndComments.MarkNSFW({id:e},t)}static async unmarkAsNsfw(e,t){await u.redditAPIPlugins.LinksAndComments.UnmarkNSFW({id:e},t)}static async markAsSpoiler(e,t){await u.redditAPIPlugins.LinksAndComments.Spoiler({id:e},t)}static async unmarkAsSpoiler(e,t){await u.redditAPIPlugins.LinksAndComments.Unspoiler({id:e},t)}static async sticky(e,t,n){await u.redditAPIPlugins.LinksAndComments.SetSubredditSticky({id:e,state:!0,num:t},n)}static async unsticky(e,t){await u.redditAPIPlugins.LinksAndComments.SetSubredditSticky({id:e,state:!1},t)}static async lock(e,t){await u.redditAPIPlugins.LinksAndComments.Lock({id:e},t)}static async unlock(e,t){await u.redditAPIPlugins.LinksAndComments.Unlock({id:e},t)}static async distinguish(e,t,n){let a=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:t?"admin":"yes",sticky:!1},n)).json?.data?.things?.[0]?.data;return p(a),{distinguishedBy:a.distinguished}}static async undistinguish(e,t){let s=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:"no",sticky:!1},t)).json?.data?.things?.[0]?.data;return p(s),{distinguishedBy:s.distinguished}}static async ignoreReports(e,t){await u.redditAPIPlugins.Moderation.IgnoreReports({id:e},t)}static async unignoreReports(e,t){await u.redditAPIPlugins.Moderation.UnignoreReports({id:e},t)}static getControversialPosts(e={},t){return this.getSortedPosts({...e,sort:"controversial"},t)}static getTopPosts(e={},t){return this.getSortedPosts({...e,sort:"top"},t)}static getSortedPosts(e,t){let n=u.redditAPIPlugins.Listings;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async o=>{let s=await n.Sort({show:"all",sort:e.sort,t:e.timeframe,subreddit:e.subredditName,...o},t);return sr(s,t)}})}static getHotPosts(e={location:"GLOBAL"},t){let n=u.redditAPIPlugins.Listings;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async o=>{let s=await n.Hot({g:e.location,show:"all",subreddit:e.subredditName,...o},t);return sr(s,t)}})}static getNewPosts(e,t){let n=u.redditAPIPlugins.Listings;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async o=>{let s=await n.New({show:"all",subreddit:e.subredditName,...o},t);return sr(s,t)}})}static getRisingPosts(e,t){let n=u.redditAPIPlugins.Listings;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async o=>{let s=await n.Rising({show:"all",subreddit:e.subredditName,...o},t);return sr(s,t)}})}static getPostsByUser(e,t){let n=u.redditAPIPlugins.Users;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(o){let s=await n.UserWhere({username:e.username,where:"submitted",...o},t);return sr(s,t)}})}};zi=new WeakMap,ar=new WeakMap,qi=new WeakMap,dr=new WeakMap,$i=new WeakMap,lr=new WeakMap,ur=new WeakMap,cr=new WeakMap,zt=new WeakMap,mr=new WeakMap,pr=new WeakMap,gr=new WeakMap,fr=new WeakMap,hr=new WeakMap,yr=new WeakMap,pt=new WeakMap,br=new WeakMap,vr=new WeakMap,qt=new WeakMap,Ki=new WeakMap,gt=new WeakMap,Zi=new WeakMap,Xi=new WeakMap,Qi=new WeakMap,ft=new WeakMap,ht=new WeakMap,yt=new WeakMap,Yi=new WeakMap,bt=new WeakMap,vt=new WeakMap,kt=new WeakMap,Ve=new WeakMap,kr=new WeakMap,Cr=new WeakMap,en=new WeakMap,tn=new WeakMap,B=new WeakMap;var W=N;function sr(i,e){if(!i.data?.children)throw new Error("Listing response is missing children");return{children:i.data.children.map(n=>new W(n.data,e)),before:i.data.before,after:i.data.after}}async function ug(i,e){let s=(await X.query("GetThumbnailV2","81580ce4e23d748c5a59a1618489b559bf4518b6a73af41f345d8d074c8b2ce9",{id:i.id},e)).data?.postInfoById?.thumbnailV2;if(s){if(!s.image)return}else throw new Error("Failed to get thumbnail");return{attribution:s.attribution,image:{url:s.image.url,width:s.image.dimensions.width,height:s.image.dimensions.height},isObfuscatedDefault:s.isObfuscatedDefault,...s.obfuscatedImage&&{obfuscatedImage:{url:s.obfuscatedImage.url,width:s.obfuscatedImage.dimensions.width,height:s.obfuscatedImage.dimensions.height}}}}var cg=(_=>(_.Custom="CUSTOM",_.Reddit="REDDIT",_.Instagram="INSTAGRAM",_.Twitter="TWITTER",_.Tiktok="TIKTOK",_.Twitch="TWITCH",_.Facebook="FACEBOOK",_.Youtube="YOUTUBE",_.Tumblr="TUMBLR",_.Spotify="SPOTIFY",_.Soundcloud="SOUNDCLOUD",_.Beacons="BEACONS",_.Linktree="LINKTREE",_.Discord="DISCORD",_.Venmo="VENMO",_.CashApp="CASH_APP",_.Patreon="PATREON",_.Kofi="KOFI",_.Paypal="PAYPAL",_.Cameo="CAMEO",_.Onlyfans="ONLYFANS",_.Substack="SUBSTACK",_.Kickstarter="KICKSTARTER",_.Indiegogo="INDIEGOGO",_.BuyMeACoffee="BUY_ME_A_COFFEE",_.Shopify="SHOPIFY",_))(cg||{}),Pr,nn,Sr,wr,xr,Fr,Ar,Ct,Ir,Er,Tr,De,$t=class $t{constructor(e,t){l(this,Pr);l(this,nn);l(this,Sr);l(this,wr);l(this,xr);l(this,Fr);l(this,Ar);l(this,Ct,new Map);l(this,Ir);l(this,Er);l(this,Tr);l(this,De);K(this),p(e.id,"User ID is missing or undefined"),p(e.name,"Username is missing or undefined"),p(e.createdUtc,"User is missing created date"),d(this,Pr,te(En(e.id)?e.id:`t2_${e.id}`)),d(this,nn,e.name),d(this,Fr,e.over18??!1),d(this,Ar,e.isEmployee??!1);let n=new Date(0);if(n.setUTCSeconds(e.createdUtc),d(this,Sr,n),d(this,wr,e.linkKarma??0),d(this,xr,e.commentKarma??0),e.modPermissions)for(let[o,s]of Object.entries(e.modPermissions))r(this,Ct).set(o,lc(s));d(this,Ir,new URL(e.subreddit?.url??"","https://www.reddit.com").toString()),d(this,Er,e.subreddit?.url??""),d(this,Tr,e.hasVerifiedEmail??!1),d(this,De,t)}get id(){return r(this,Pr)}get username(){return r(this,nn)}get createdAt(){return r(this,Sr)}get linkKarma(){return r(this,wr)}get commentKarma(){return r(this,xr)}get nsfw(){return r(this,Fr)}get isAdmin(){return r(this,Ar)}get modPermissions(){return r(this,Ct)}get url(){return r(this,Ir)}get permalink(){return r(this,Er)}get hasVerifiedEmail(){return r(this,Tr)}toJSON(){return{id:this.id,username:this.username,createdAt:this.createdAt,linkKarma:this.linkKarma,commentKarma:this.commentKarma,nsfw:this.nsfw,modPermissionsBySubreddit:Object.fromEntries(this.modPermissions)}}async getModPermissionsForSubreddit(e){if(r(this,Ct).has(e))return r(this,Ct).get(e);let t=await $t.getSubredditUsersByType({subredditName:e,type:"moderators",username:this.username},r(this,De)).all();if(t.length===0)return[];let n=t[0].modPermissions.get(e)??[];return n.length>0&&r(this,Ct).set(e,n),n}getComments(e){return Q.getCommentsByUser({username:this.username,...e},r(this,De))}getPosts(e){return W.getPostsByUser({username:this.username,...e},r(this,De))}async getUserFlairBySubreddit(e){let t=await ce.getUserFlairBySubreddit({subreddit:e,name:r(this,nn)},r(this,De));return t.users[0]?or(t.users[0]):void 0}getSnoovatarUrl(){return $t.getSnoovatarUrl(this.username,r(this,De))}async getSocialLinks(){let n=await X.query("GetUserSocialLinks","2aca18ef5f4fc75fb91cdaace3e9aeeae2cb3843b5c26ad511e6f01b8521593a",{name:this.username},r(this,De));return n.data?.user?.profile?.socialLinks?n.data.user.profile.socialLinks.map(o=>({...o,handle:o.handle??void 0})):[]}static async getById(e,t){let n=await fc(e,t);return n==null?void 0:$t.getByUsername(n,t)}static async getByUsername(e,t){let n=u.redditAPIPlugins.Users;try{let o=await n.UserAbout({username:e},t);if(o.data?.id)return new $t(o.data,t)}catch(o){if(o instanceof Error&&o.message.includes("404 Not Found"))return;throw o}}static async getFromMetadata(e,t){p(t);let n=t?.[e]?.values[0];return n?$t.getById(te(n),t):Promise.resolve(void 0)}static getSubredditUsersByType(e,t){let n=u.redditAPIPlugins.Subreddits;return new V({hasMore:!0,pageSize:e.pageSize,limit:e.limit,after:e.after,before:e.before,fetch:async o=>{let s=await n.AboutWhere({where:e.type,user:e.username,subreddit:e.subredditName,show:"all",...o},t);return pg(s,e.subredditName,t)}})}static async createRelationship(e,t){let n=u.redditAPIPlugins.Users,{type:o,subredditName:s,username:a,permissions:c,...m}=e,h=await n.Friend({type:o,subreddit:s,name:a,permissions:c?ja(c):void 0,...m},t);if(h.json?.errors?.length)throw new Error(h.json.errors.join(`
|
|
5
|
+
`))}static async removeRelationship(e,t){await u.redditAPIPlugins.Users.Unfriend({type:e.type,subreddit:e.subredditName,name:e.username},t)}static async setModeratorPermissions(e,t,n,o){let a=await u.redditAPIPlugins.Users.SetPermissions({subreddit:t,name:e,type:"moderator",permissions:ja(n)},o);if(a.json?.errors?.length)throw new Error(a.json.errors.join(`
|
|
6
|
+
`))}static async getSnoovatarUrl(e,t){return(await X.query("GetSnoovatarUrlByName","c47fd42345af268616d2d8904b56856acdc05cf61d3650380f539ad7d596ac0c",{username:e},t)).data?.redditorInfoByName?.snoovatarIcon?.url}static getOverview(e,t){let n=u.redditAPIPlugins.Users;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(o){let s=await n.UserWhere({username:e.username,where:"overview",...o},t);return mg(s,t)}})}};Pr=new WeakMap,nn=new WeakMap,Sr=new WeakMap,wr=new WeakMap,xr=new WeakMap,Fr=new WeakMap,Ar=new WeakMap,Ct=new WeakMap,Ir=new WeakMap,Er=new WeakMap,Tr=new WeakMap,De=new WeakMap;var C=$t;function mg(i,e){if(!i.data?.children)throw new Error("Listing response is missing children");return{children:i.data.children.map(n=>{if(n.kind==="t3")return new W(n.data,e);if(n.kind==="t1")return new Q(n.data,e);throw new Error(`Type ${n.kind} is not supported`)}),before:i.data.before,after:i.data.after}}async function pg(i,e,t){let n=u.redditAPIPlugins.Users;if(!i.data?.children)throw new Error("Listing response is missing children");let o=i.data.children.map(v=>(p(v.data?.id,"User id is still from listing data"),v.data.id)),s=100,a=[];for(let v=0;v<o.length;v+=s)a.push(o.slice(v,v+s));let m=(await Promise.all(a.map(v=>n.UserDataByAccountIds({ids:v.join(",")},t)))).reduce((v,y)=>({...v,...y.users}),{});return{children:i.data.children.map(v=>{let y=v.data?.id;p(y,"User id is missing from listing");let P=m[y];return p(P,"User data is missing from response"),new C({id:y,name:P.name,linkKarma:P.linkKarma,commentKarma:P.commentKarma,createdUtc:P.createdUtc,over18:P.profileOver18,snoovatarSize:[],modPermissions:{[e]:v.data?.modPermissions??[]}},t)}),before:i.data.before,after:i.data.after}}async function fc(i,e){return(await u.redditAPIPlugins.Users.UserDataByAccountIds({ids:i},e))?.users?.[i]?.name}async function hc(i){p(i);let e=i?.[S.Username]?.values[0];if(e)return e;let t=i?.[S.User]?.values[0];if(t)return fc(t,i)}async function yc(i){p(i);let e=i?.[S.Username]?.values[0];if(e)return C.getByUsername(e,i);let t=i?.[S.User]?.values[0];if(!t&&En(t))return C.getById(t,i)}var Kt,Rr,rn,on,Or,Mr,sn,Br,Ur,an,Pt,Dr,Nr,Zt,St,wt,We,Xt,Ge,Lr,_r,Hr,jr,Vr,Wr,Gr,xt,Z,Ne,ys,bs,j=class j{constructor(e,t){l(this,Kt);l(this,Rr);l(this,rn);l(this,on);l(this,Or);l(this,Mr);l(this,sn);l(this,Br);l(this,Ur);l(this,an);l(this,Pt);l(this,Dr);l(this,Nr);l(this,Zt);l(this,St);l(this,wt);l(this,We);l(this,Xt);l(this,Ge);l(this,Lr);l(this,_r);l(this,Hr);l(this,jr);l(this,Vr);l(this,Wr);l(this,Gr);l(this,xt);l(this,Z);var o;K(this),p(e.id,"Comment id is null or undefined"),p(e.body,"Comment body is null or undefined"),p(e.createdUtc,"Comment is missing created date"),p(e.author,"Comment author is null or undefined"),p(e.parentId,"Comment parentId is null or undefined"),p(e.linkId,"Comment linkId is null or undefined"),p(e.permalink,"Comment permalink is null or undefined"),p(e.subreddit,"Comment is missing subreddit name"),p(e.subredditId,"Comment is missing subreddit id"),d(this,Kt,ti(`t1_${e.id}`)),d(this,Rr,e.authorFullname?te(e.authorFullname):void 0),d(this,rn,e.author),d(this,on,e.body),d(this,Br,$(e.subredditId)),d(this,Ur,e.subreddit),d(this,Mr,Ls(e.parentId)?ti(e.parentId):de(e.parentId)),d(this,sn,de(e.linkId)),d(this,Zt,e.edited??!1),d(this,St,e.locked??!1),d(this,wt,e.removed??!1),d(this,We,e.stickied??!1),d(this,Pt,e.approved??!1),d(this,Dr,e.approvedAtUtc??0),d(this,Nr,e.bannedAtUtc??0),d(this,Xt,e.spam??!1),d(this,Ge,e.distinguished),d(this,Lr,e.numReports??0),d(this,_r,e.collapsedBecauseCrowdControl??!1),d(this,Hr,e.score??0),d(this,jr,e.permalink),d(this,Gr,new URL(e.permalink??"","https://www.reddit.com/").toString()),d(this,xt,e.ignoreReports??!1),d(this,Vr,(e.modReports??[]).map(([s])=>s)),d(this,Wr,(e.userReports??[]).map(([s])=>s));let n=new Date(0);n.setUTCSeconds(e.createdUtc),d(this,Or,n),d(this,an,f(o=j,Ne,ys).call(o,{postId:r(this,sn),commentId:r(this,Kt)},t)),d(this,Z,t)}get id(){return r(this,Kt)}get authorId(){return r(this,Rr)}get authorName(){return r(this,rn)}get subredditId(){return r(this,Br)}get subredditName(){return r(this,Ur)}get body(){return r(this,on)}get createdAt(){return r(this,Or)}get parentId(){return r(this,Mr)}get postId(){return r(this,sn)}get replies(){return r(this,an)}get distinguishedBy(){return r(this,Ge)}get locked(){return r(this,St)}get stickied(){return r(this,We)}get removed(){return r(this,wt)}get approved(){return r(this,Pt)}get approvedAtUtc(){return r(this,Dr)}get bannedAtUtc(){return r(this,Nr)}get spam(){return r(this,Xt)}get edited(){return r(this,Zt)}get numReports(){return r(this,Lr)}get collapsedBecauseCrowdControl(){return r(this,_r)}get score(){return r(this,Hr)}get permalink(){return r(this,jr)}get userReportReasons(){return r(this,Wr)}get modReportReasons(){return r(this,Vr)}get url(){return r(this,Gr)}get ignoringReports(){return r(this,xt)}toJSON(){return{id:this.id,authorName:this.authorName,subredditId:this.subredditId,subredditName:this.subredditName,body:this.body,createdAt:this.createdAt,parentId:this.parentId,postId:this.postId,replies:this.replies,approved:this.approved,locked:this.locked,removed:this.removed,stickied:this.stickied,spam:this.spam,edited:this.edited,distinguishedBy:this.distinguishedBy,numReports:this.numReports,collapsedBecauseCrowdControl:this.collapsedBecauseCrowdControl,score:this.score,permalink:this.permalink,modReportReasons:this.modReportReasons,userReportReasons:this.userReportReasons,url:this.url,ignoringReports:this.ignoringReports}}isLocked(){return r(this,St)}isApproved(){return r(this,Pt)}isRemoved(){return r(this,wt)}isSpam(){return r(this,Xt)}isStickied(){return r(this,We)}isDistinguished(){return!!r(this,Ge)}isEdited(){return r(this,Zt)}isIgnoringReports(){return r(this,xt)}async delete(){return j.delete(this.id,r(this,Z))}async edit(e){let t=await j.edit({id:this.id,...e},r(this,Z));return d(this,on,t.body),d(this,Zt,t.edited),this}async approve(){await j.approve(this.id,r(this,Z)),d(this,Pt,!0),d(this,wt,!1)}async remove(e=!1){await j.remove(this.id,e,r(this,Z)),d(this,wt,!0),d(this,Xt,e),d(this,Pt,!1)}async lock(){await j.lock(this.id,r(this,Z)),d(this,St,!0)}async unlock(){await j.unlock(this.id,r(this,Z)),d(this,St,!1)}async reply(e){return j.submit({id:this.id,...e},r(this,Z))}async getAuthor(){return C.getByUsername(r(this,rn),r(this,Z))}async distinguish(e=!1){let{distinguishedBy:t,stickied:n}=await j.distinguish(this.id,e,!1,r(this,Z));d(this,Ge,t),d(this,We,n)}async distinguishAsAdmin(e=!1){let{distinguishedBy:t,stickied:n}=await j.distinguish(this.id,e,!0,r(this,Z));d(this,Ge,t),d(this,We,n)}async undistinguish(){let{distinguishedBy:e,stickied:t}=await j.undistinguish(this.id,r(this,Z));d(this,Ge,e),d(this,We,t)}async ignoreReports(){await j.ignoreReports(this.id,r(this,Z)),d(this,xt,!0)}async unignoreReports(){await j.unignoreReports(this.id,r(this,Z)),d(this,xt,!1)}addRemovalNote(e){return Se.addRemovalNote({itemIds:[r(this,Kt)],...e},r(this,Z))}static async getById(e,t){let n=u.redditAPIPlugins.LinksAndComments,o=Je(e)?e:`t1_${e}`,s=await n.Info({subreddits:[],thingIds:[o]},t);if(!s.data?.children?.[0]?.data)throw new Error("not found");return new j(s.data.children[0].data,t)}static getComments(e,t){var a;let{postId:n,commentId:o,...s}=e;return f(a=j,Ne,ys).call(a,{postId:de(n),commentId:o?ti(o):void 0,...s},t)}static async edit(e,t){let n=u.redditAPIPlugins.LinksAndComments,{id:o}=e,s;"richtext"in e&&(s=Mi(e.richtext));let a=await n.EditUserText({thingId:o,text:"text"in e?e.text:"",richtextJson:s,runAs:he.APP},t);if(a.json?.errors?.length)throw new Error("Failed to edit comment");let c=a.json?.data?.things?.[0]?.data;return p(c),new j(c,t)}static async delete(e,t){await u.redditAPIPlugins.LinksAndComments.Del({id:e},t)}static async approve(e,t){await u.redditAPIPlugins.Moderation.Approve({id:e},t)}static async remove(e,t=!1,n){await u.redditAPIPlugins.Moderation.Remove({id:e,spam:t},n)}static async lock(e,t){await u.redditAPIPlugins.LinksAndComments.Lock({id:e},t)}static async unlock(e,t){await u.redditAPIPlugins.LinksAndComments.Unlock({id:e},t)}static async submit(e,t){let{runAs:n="APP"}=e,o=he[n],s=o===he.USER?u.userActionsPlugin:u.redditAPIPlugins.LinksAndComments,{id:a}=e,c;"richtext"in e&&(c=Mi(e.richtext));let m=await s.Comment({thingId:a,text:"text"in e?e.text:"",richtextJson:c,runAs:o},t);if(m.json?.errors?.length)throw new Error("failed to reply to comment");let h=m.json?.data?.things?.[0]?.data;return p(h),new j(h,t)}static async distinguish(e,t,n,o){let c=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:n?"admin":"yes",sticky:t},o)).json?.data?.things?.[0]?.data;return p(c),{distinguishedBy:c.distinguished,stickied:!!c.stickied}}static async undistinguish(e,t){let s=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:"no",sticky:!1},t)).json?.data?.things?.[0]?.data;return p(s),{distinguishedBy:s.distinguished,stickied:!!s.stickied}}static getCommentsByUser(e,t){let n=u.redditAPIPlugins.Users;return new V({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(o){let s=await n.UserWhere({username:e.username,where:"comments",...o},t);return p(s.data,"Failed to get comments for user"),{children:s.data.children?.map(c=>new j(c.data,t))||[],before:s.data.before,after:s.data.after}}})}static async ignoreReports(e,t){await u.redditAPIPlugins.Moderation.IgnoreReports({id:e},t)}static async unignoreReports(e,t){await u.redditAPIPlugins.Moderation.UnignoreReports({id:e},t)}};Kt=new WeakMap,Rr=new WeakMap,rn=new WeakMap,on=new WeakMap,Or=new WeakMap,Mr=new WeakMap,sn=new WeakMap,Br=new WeakMap,Ur=new WeakMap,an=new WeakMap,Pt=new WeakMap,Dr=new WeakMap,Nr=new WeakMap,Zt=new WeakMap,St=new WeakMap,wt=new WeakMap,We=new WeakMap,Xt=new WeakMap,Ge=new WeakMap,Lr=new WeakMap,_r=new WeakMap,Hr=new WeakMap,jr=new WeakMap,Vr=new WeakMap,Wr=new WeakMap,Gr=new WeakMap,xt=new WeakMap,Z=new WeakMap,Ne=new WeakSet,ys=function(e,t,n=0){return new V({limit:e.limit,pageSize:e.pageSize,fetch:async o=>{var P,b;let s=o.limit,a=u.redditAPIPlugins.Listings,c=u.redditAPIPlugins.LinksAndComments,m=e.commentId;if(o.more)if(o.more.children.length){let A=o.more;(!s||s>100)&&(s=100);let U=A.children.splice(0,s),M=await c.MoreChildren({linkId:e.postId,children:U,sort:e.sort},t);if(!M.json?.data?.things?.length)return{children:[]};let{children:Y}=f(P=j,Ne,bs).call(P,M.json.data.things,e.postId,e,t);return{children:Y,more:A.children.length?A:void 0}}else m=o.more.parentId,n=n+o.more.depth;let v=(await a.Comments({article:e.postId.substring(3),comment:m?.substring(3),limit:s,depth:e.depth,sort:e.sort},t)).listings?.[1]?.data?.children??[],y=v[0];return m&&y?.data?.replyList?.data&&(v=y.data.replyList.data.children),f(b=j,Ne,bs).call(b,v,m??e.postId,e,t,n)}})},bs=function(e,t,n,o,s=0){var h,v;let a=[],c,m={};for(let y of e){if(!y.data||(y.data.depth!=null&&(y.data.depth=y.data.depth+s),y.data.depth!=null&&n.depth!=null&&y.data.depth>=n.depth))continue;let P=y.data.parentId?m[y.data.parentId]:void 0;if(y.kind==="t1"){if(y.data.name===t)continue;let b=new j(y.data,o);if(m[b.id]=b,d(b,an,f(h=j,Ne,ys).call(h,{...n,postId:b.postId,commentId:b.id},o,s)),"replyList"in y.data&&y.data.replyList?.data){let{children:A,more:U}=f(v=j,Ne,bs).call(v,y.data.replyList.data.children,b.id,n,o,s);A.length&&b.replies.children.push(...A),U&&b.replies.setMore(U)}b.replies.preventInitialFetch(),P?P.replies.children.push(b):a.push(b)}else if(y.kind==="more"&&y.data.parentId&&y.data.depth!=null){let b={parentId:Ls(y.data.parentId)?ti(y.data.parentId):de(y.data.parentId),children:y.data.children??[],depth:y.data.depth};P?P.replies.setMore(b):b.parentId===t&&(c=b)}}return{children:a,more:c}},l(j,Ne);var Q=j;function vs(i,e){let t=u.redditAPIPlugins.Moderation;return new V({hasMore:!0,after:i.after,before:i.before,limit:i.limit,pageSize:i.pageSize,fetch:async n=>{let o=await t.AboutLog({subreddit:i.subredditName,mod:i.moderatorUsernames?i.moderatorUsernames.join(","):void 0,type:i.type,...n},e);return gg(o)}})}function gg(i){if(!i.data?.children)throw new Error("AboutLogResponse is missing children");return{children:i.data.children.map(t=>{if(!t.data)throw new Error("ModAction from AboutLogResponse is missing or invalid");let{id:n,mod:o,modId36:s,createdUtc:a,subreddit:c,subredditNamePrefixed:m,action:h,srId36:v,description:y,details:P,targetAuthor:b,targetBody:A,targetFullname:U,targetPermalink:M,targetTitle:Y}=t.data;p(n,"ModAction from AboutLogResponse is missing id"),p(o,"ModAction from AboutLogResponse is missing mod"),p(s,"ModAction from AboutLogResponse is missing modId36"),p(a,"ModAction from AboutLogResponse is missing createdUtc"),p(c,"ModAction from AboutLogResponse is missing subreddit"),p(m,"ModAction from AboutLogResponse is missing subredditNamePrefixed"),p(h,"ModAction from AboutLogResponse is missing action"),p(v,"ModAction from AboutLogResponse is missing srId36");let Oo=new Date(0);return Oo.setUTCSeconds(a),{id:n,type:h,moderatorName:o,moderatorId:`t2_${s}`,createdAt:Oo,subredditName:c,subredditId:`t5_${v}`,description:y,details:P,target:U?{id:U,author:b,body:A,permalink:M,title:Y}:void 0}}),after:i.data.after,before:i.data.before}}import"@devvit/protos";var fg=(a=>(a.New="New",a.InProgress="InProgress",a.Archived="Archived",a.Appeals="Appeals",a.JoinRequests="JoinRequests",a.Filtered="Filtered",a))(fg||{}),hg={0:"New",1:"InProgress",2:"Archived",3:"Appeals",4:"JoinRequests",5:"Filtered"},yg=(b=>(b.Highlighted="Highlighted",b.Unhighlighted="Unhighlighted",b.Archived="Archived",b.Unarchived="Unarchived",b.ReportedToAdmins="ReportedToAdmins",b.Muted="Muted",b.Unmuted="Unmuted",b.Banned="Banned",b.Unbanned="Unbanned",b.Approved="Approved",b.Disapproved="Disapproved",b.Filtered="Filtered",b.Unfiltered="Unfiltered",b))(yg||{}),bg={0:"Highlighted",1:"Unhighlighted",2:"Archived",3:"Unarchived",4:"ReportedToAdmins",5:"Muted",6:"Unmuted",7:"Banned",8:"Unbanned",9:"Approved",10:"Disapproved",11:"Filtered",12:"Unfiltered"},L,G,ie,bc,vc,ks=class{constructor(e){l(this,G);l(this,L);this.notificationSubjectPrefix="[notification]";d(this,L,e)}async bulkReadConversations(e,t){let n=u.redditAPIPlugins.NewModmail,{conversationIds:o}=await n.BulkReadConversations({entity:e.join(","),state:t},r(this,L));return o}async getConversations(e){let n=await u.redditAPIPlugins.NewModmail.GetConversations({after:e.after,entity:e.subreddits?e.subreddits.join(","):void 0,limit:e.limit,sort:e.sort,state:e.state},r(this,L)),o={};for(let s in n.conversations)o[s]=f(this,G,ie).call(this,{protoConversation:n.conversations[s],protoMessages:n.messages,protoModActions:{}});return{conversations:o,viewerId:n.viewerId,conversationIds:n.conversationIds}}async getConversation(e){let n=await u.redditAPIPlugins.NewModmail.GetConversation({...e,markRead:!!e.markRead},r(this,L));return{participantSubreddit:n.participantSubreddit,conversation:f(this,G,ie).call(this,{protoConversation:n.conversation,protoMessages:n.messages,protoModActions:n.modActions}),user:n.user}}async getSubreddits(){let e=u.redditAPIPlugins.NewModmail,{subreddits:t}=await e.Subreddits({},r(this,L));return t}async createConversation(e){let n=await u.redditAPIPlugins.NewModmail.CreateConversation({body:e.body,isAuthorHidden:e.isAuthorHidden??!1,srName:e.subredditName,subject:e.subject,to:e.to?e.to:void 0},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversation,protoMessages:n.messages,protoModActions:n.modActions}),user:n.user}}async createModDiscussionConversation(e){return qa({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:$(e.subredditId),isInternal:!0,participantType:"MODERATOR",conversationType:"INTERNAL"},r(this,L))}async createModInboxConversation(e){return qa({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:$(e.subredditId),isInternal:!1,participantType:"PARTICIPANT_USER",conversationType:"SR_USER"},r(this,L))}async createModNotification(e){let t=e.subject;return e.subject.startsWith(this.notificationSubjectPrefix)||(t=`${this.notificationSubjectPrefix} ${e.subject}`),qa({subject:t,bodyMarkdown:e.bodyMarkdown,subredditId:$(e.subredditId),isInternal:!1,participantType:"PARTICIPANT_USER",conversationType:"SR_USER"},r(this,L))}async reply(e){let n=await u.redditAPIPlugins.NewModmail.CreateConversationMessage({body:e.body,conversationId:e.conversationId,isAuthorHidden:e.isAuthorHidden??!1,isInternal:e.isInternal??!1},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversation,protoMessages:n.messages,protoModActions:{}}),user:n.user}}async highlightConversation(e){let n=await u.redditAPIPlugins.NewModmail.HighlightConversation({conversationId:e},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversation,protoMessages:n.messages,protoModActions:n.modActions})}}async unhighlightConversation(e){let n=await u.redditAPIPlugins.NewModmail.UnhighlightConversation({conversationId:e},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversation,protoMessages:n.messages,protoModActions:n.modActions})}}async archiveConversation(e){let n=await u.redditAPIPlugins.NewModmail.ArchiveConversation({conversationId:e},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversation,protoMessages:n.messages,protoModActions:n.modActions})}}async unarchiveConversation(e){let n=await u.redditAPIPlugins.NewModmail.UnarchiveConversation({conversationId:e},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversation,protoMessages:n.messages,protoModActions:n.modActions})}}async muteConversation(e){let n=await u.redditAPIPlugins.NewModmail.MuteConversation({conversationId:e.conversationId,numHours:e.numHours},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversations,protoMessages:n.messages,protoModActions:n.modActions}),user:n.user}}async unmuteConversation(e){let n=await u.redditAPIPlugins.NewModmail.UnmuteConversation({conversationId:e},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversations,protoMessages:n.messages,protoModActions:n.modActions}),user:n.user}}async readConversations(e){await u.redditAPIPlugins.NewModmail.Read({conversationIds:e.join(",")},r(this,L))}async unreadConversations(e){await u.redditAPIPlugins.NewModmail.Unread({conversationIds:e.join(",")},r(this,L))}async approveConversation(e){let n=await u.redditAPIPlugins.NewModmail.ApproveConversation({conversationId:e},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversations,protoMessages:n.messages,protoModActions:n.modActions}),user:n.user}}async disapproveConversation(e){let n=await u.redditAPIPlugins.NewModmail.DisapproveConversation({conversationId:e},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversations,protoMessages:n.messages,protoModActions:n.modActions}),user:n.user}}async tempBanConversation(e){let n=await u.redditAPIPlugins.NewModmail.TempBan({...e},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversations,protoMessages:n.messages,protoModActions:n.modActions}),user:n.user}}async unbanConversation(e){let n=await u.redditAPIPlugins.NewModmail.Unban({conversationId:e},r(this,L));return{conversation:f(this,G,ie).call(this,{protoConversation:n.conversations,protoMessages:n.messages,protoModActions:n.modActions}),user:n.user}}async getUnreadCount(){return await u.redditAPIPlugins.NewModmail.UnreadCount({},r(this,L))}async getUserConversations(e){return await u.redditAPIPlugins.NewModmail.UserConversations({conversationId:e},r(this,L))}};L=new WeakMap,G=new WeakSet,ie=function({protoConversation:e,protoMessages:t,protoModActions:n}){return{...e,state:hg[e.state],messages:f(this,G,bc).call(this,e,t),modActions:f(this,G,vc).call(this,e,n)}},bc=function(e,t){let n={},o=e.objIds.filter(s=>s.key==="messages").map(({id:s})=>s);for(let s of o){let a=t[s];a&&(n[s]=a)}return n},vc=function(e,t){let n={},o=e.objIds.filter(s=>s.key==="modActions").map(({id:s})=>s);for(let s of o){let a=t[s];a&&(n[s]={...a,actionType:bg[a.actionTypeId]})}return n};async function qa(i,e){let t=e[S.AppUser]?.values[0],s=await X.query("CreateModmailConversation","5f9ae20b0c7bdffcafb80241728a72e67cd4239bc09f67284b79d4aa706ee0e5",{subject:i.subject,bodyMarkdown:i.bodyMarkdown,subredditId:i.subredditId,authorId:t,isInternal:i.isInternal,participantType:i.participantType,conversationType:i.conversationType},e);if(s.data?.createModmailConversationV2?.ok)return s.data?.createModmailConversationV2?.conversationId;throw new Error("modmail conversation creation failed; ${response.data?.createModmailConversationV2?.errors[0].message}")}var dn,ln,Jr,zr,qr,$r,$a=class $a{constructor(e,t){l(this,dn);l(this,ln);l(this,Jr);l(this,zr);l(this,qr);l(this,$r);if(K(this),p(e.id,"PrivateMessage: Invalid data, no id"),p(e.name,"PrivateMessage: Invalid data, no name"),p(e.created,"PrivateMessage: Invalid data, no created date"),d(this,dn,ye(e.name)),e.author!=null)d(this,ln,{type:"user",username:e.author,id:e.authorFullname?te(e.authorFullname):void 0});else if(e.subreddit!=null)d(this,ln,{type:"subreddit",name:e.subreddit,id:e.subredditId?$(e.subredditId):void 0});else throw new Error("PrivateMessage: Invalid data, no author or subreddit");d(this,Jr,e.body??""),d(this,zr,e.bodyHtml??"");let n=new Date(0);n.setUTCSeconds(e.createdUtc),d(this,qr,n),d(this,$r,t)}static async getMessages(e,t){let n=u.redditAPIPlugins.PrivateMessages;return new V({...e,fetch:async o=>{let s=await n.MessageWhere({...o,where:e.type??"inbox"},t);return{after:s.data?.after,before:s.data?.before,children:s.data?.children?.map(a=>new $a(a.data,t)).filter(Boolean)||[]}}})}static async send({to:e,subject:t,text:n},o){await u.redditAPIPlugins.PrivateMessages.Compose({to:e,subject:t,text:n,fromSr:""},o)}static async sendAsSubreddit({to:e,fromSubredditName:t,subject:n,text:o},s){await u.redditAPIPlugins.PrivateMessages.Compose({to:e,fromSr:t,subject:n,text:o},s)}static async markAllAsRead(e){await u.redditAPIPlugins.PrivateMessages.ReadAllMessages({filterTypes:""},e)}get id(){return r(this,dn)}get from(){return r(this,ln)}get body(){return r(this,Jr)}get bodyHtml(){return r(this,zr)}get created(){return r(this,qr)}async markAsRead(){await u.redditAPIPlugins.PrivateMessages.ReadMessage({id:r(this,dn)},r(this,$r))}};dn=new WeakMap,ln=new WeakMap,Jr=new WeakMap,zr=new WeakMap,qr=new WeakMap,$r=new WeakMap;var Qt=$a;var xc=(s=>(s.Reports="reports",s.Spam="spam",s.Modqueue="modqueue",s.Unmoderated="unmoderated",s.Edited="edited",s))(xc||{}),kc=class{},Cc=class{},Pc=class{},Sc=class{},un,F,Kr,Zr,Xr,Qr,Yr,eo,to,io,no,cn,R,Ee=class Ee{constructor(e,t){l(this,un);l(this,F);l(this,Kr);l(this,Zr);l(this,Xr);l(this,Qr);l(this,Yr);l(this,eo);l(this,to);l(this,io);l(this,no);l(this,cn);l(this,R);K(this),p(e.id,"Subreddit id is missing or undefined"),p(e.displayName,"Subreddit name is missing or undefined"),d(this,un,$(`t5_${e.id}`)),d(this,F,e.displayName),p(e.createdUtc,"Subreddit is missing created date");let n=new Date(0);n.setUTCSeconds(e.createdUtc),d(this,Kr,n),d(this,Zr,vg(e.subredditType)),d(this,Xr,e.title),d(this,Qr,e.description),p(e.lang,"Subreddit is missing language"),d(this,Yr,e.lang),d(this,eo,e.subscribers??0),d(this,to,e.activeUserCount??0),d(this,io,e.over18??!1),d(this,cn,e.url??""),d(this,no,{acceptFollowers:e.acceptFollowers??!1,allOriginalContent:e.allOriginalContent??!1,allowChatPostCreation:e.allowChatPostCreation??!1,allowDiscovery:e.allowDiscovery??!1,allowGalleries:e.allowGalleries??!1,allowImages:e.allowImages??!1,allowPolls:e.allowPolls??!1,allowPredictionContributors:e.allowPredictionContributors??!1,allowPredictions:e.allowPredictions??!1,allowPredictionsTournament:e.allowPredictionsTournament??!1,allowTalks:e.allowTalks??!1,allowVideoGifs:e.allowVideogifs??!1,allowVideos:e.allowVideos??!1,chatPostEnabled:e.isChatPostFeatureEnabled??!1,collectionsEnabled:e.collectionsEnabled??!1,crosspostable:e.isCrosspostableSubreddit??!1,emojisEnabled:e.emojisEnabled??!1,eventPostsEnabled:e.eventPostsEnabled??!1,linkFlairEnabled:e.linkFlairEnabled??!1,originalContentTagEnabled:e.originalContentTagEnabled??!1,restrictCommenting:e.restrictCommenting??!1,restrictPosting:e.restrictPosting??!1,shouldArchivePosts:e.shouldArchivePosts??!1,spoilersEnabled:e.spoilersEnabled??!1,wikiEnabled:e.wikiEnabled??!1,allowedPostType:kg(e.submissionType),allowedMediaInComments:(e.allowedMediaInComments??[]).map(Cg),bannerBackgroundColor:e.bannerBackgroundColor,bannerBackgroundImage:e.bannerBackgroundImage,bannerImage:e.bannerImg,communityIcon:e.communityIcon,headerTitle:e.headerTitle,keyColor:e.keyColor,mobileBannerImage:e.mobileBannerImage,primaryColor:e.primaryColor,userFlairs:{enabled:e.userFlairEnabledInSr??!1,usersCanAssign:e.canAssignUserFlair??!1,userFlairBackgroundColor:e.userFlairBackgroundColor,userFlairTextColor:e.userFlairTextColor},postFlairs:{enabled:e.linkFlairEnabled??!1,usersCanAssign:e.canAssignLinkFlair??!1},url:new URL(r(this,cn),"https://www.reddit.com").toString()}),d(this,R,t)}get id(){return r(this,un)}get name(){return r(this,F)}get createdAt(){return r(this,Kr)}get type(){return r(this,Zr)}get title(){return r(this,Xr)}get description(){return r(this,Qr)}get language(){return r(this,Yr)}get numberOfSubscribers(){return r(this,eo)}get numberOfActiveUsers(){return r(this,to)}get nsfw(){return r(this,io)}get settings(){return r(this,no)}get userFlairsEnabled(){return this.settings.userFlairs.enabled}get postFlairsEnabled(){return this.settings.postFlairs.enabled}get usersCanAssignUserFlairs(){return this.settings.userFlairs.usersCanAssign}get usersCanAssignPostFlairs(){return this.settings.postFlairs.usersCanAssign}get url(){return this.settings.url}get permalink(){return r(this,cn)}toJSON(){return{id:this.id,name:this.name,createdAt:this.createdAt,type:this.type,title:this.title,description:this.description,language:this.language,nsfw:this.nsfw,numberOfSubscribers:this.numberOfSubscribers,numberOfActiveUsers:this.numberOfActiveUsers,settings:this.settings}}async submitPost(e){let t={...e,subredditName:r(this,F)};return W.submit(t,r(this,R))}getControversialPosts(e={}){if(!r(this,F))throw new Error("subreddit missing displayName - it might not have been fetched");return W.getControversialPosts({...e,subredditName:r(this,F)},r(this,R))}getTopPosts(e={}){if(!r(this,F))throw new Error("subreddit missing displayName - it might not have been fetched");return W.getTopPosts({...e,subredditName:r(this,F)},r(this,R))}getApprovedUsers(e={}){return C.getSubredditUsersByType({type:"contributors",subredditName:r(this,F),...e},r(this,R))}approveUser(e){return C.createRelationship({username:e,subredditName:r(this,F),type:"contributor"},r(this,R))}removeUser(e){return C.removeRelationship({username:e,subredditName:r(this,F),type:"contributor"},r(this,R))}getWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikicontributors",subredditName:r(this,F),...e},r(this,R))}addWikiContributor(e){return C.createRelationship({username:e,subredditName:r(this,F),type:"wikicontributor"},r(this,R))}removeWikiContributor(e){return C.removeRelationship({username:e,subredditName:r(this,F),type:"wikicontributor"},r(this,R))}getBannedUsers(e={}){return C.getSubredditUsersByType({type:"banned",subredditName:r(this,F),...e},r(this,R))}banUser(e){return C.createRelationship({username:e.username,subredditName:r(this,F),type:"banned",banReason:e.reason,banMessage:e.message,note:e.note,duration:e.duration,banContext:e.context},r(this,R))}unbanUser(e){return C.removeRelationship({username:e,subredditName:r(this,F),type:"banned"},r(this,R))}getBannedWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikibanned",subredditName:r(this,F),...e},r(this,R))}banWikiContributor(e){return C.createRelationship({username:e.username,subredditName:r(this,F),type:"wikibanned",banReason:e.reason,note:e.note,duration:e.duration},r(this,R))}unbanWikiContributor(e){return C.removeRelationship({username:e,subredditName:r(this,F),type:"wikibanned"},r(this,R))}getModerators(e={}){return C.getSubredditUsersByType({type:"moderators",subredditName:r(this,F),...e},r(this,R))}inviteModerator(e,t){return C.createRelationship({type:"moderator_invite",subredditName:r(this,F),username:e,permissions:t??[]},r(this,R))}revokeModeratorInvite(e){return C.removeRelationship({username:e,subredditName:r(this,F),type:"moderator_invite"},r(this,R))}removeModerator(e){return C.removeRelationship({type:"moderator",subredditName:r(this,F),username:e},r(this,R))}setModeratorPermissions(e,t){return C.setModeratorPermissions(e,r(this,F),t,r(this,R))}getMutedUsers(e={}){return C.getSubredditUsersByType({type:"muted",subredditName:r(this,F),...e},r(this,R))}muteUser(e,t){return C.createRelationship({username:e,subredditName:r(this,F),type:"muted",note:t},r(this,R))}unmuteUser(e){return C.removeRelationship({username:e,subredditName:r(this,F),type:"muted"},r(this,R))}getModerationLog(e){return vs({subredditName:r(this,F),...e},r(this,R))}getUserFlairTemplates(){return se.getUserFlairTemplates(r(this,F),r(this,R))}getPostFlairTemplates(){return se.getPostFlairTemplates(r(this,F),r(this,R))}createPostFlairTemplate(e){return se.createPostFlairTemplate({subredditName:r(this,F),...e},r(this,R))}createUserFlairTemplate(e){return se.createUserFlairTemplate({subredditName:r(this,F),...e},r(this,R))}async getUserFlair(e){if(e?.usernames!==void 0)return{users:await Promise.all(e.usernames.map(async n=>{let o=await ce.getUserFlairBySubreddit({subreddit:r(this,F),name:n},r(this,R));return or(o.users[0])}))};{let t=await ce.getUserFlairBySubreddit({...e,subreddit:r(this,F)},r(this,R));return{next:t.next,prev:t.prev,users:t.users.map(n=>or(n))}}}getModQueue(e={type:"all"}){return Ee.aboutLocation({...e,location:"modqueue",subreddit:r(this,F)},r(this,R))}getReports(e={type:"all"}){return Ee.aboutLocation({...e,location:"reports",subreddit:r(this,F)},r(this,R))}getSpam(e={type:"all"}){return Ee.aboutLocation({...e,location:"spam",subreddit:r(this,F)},r(this,R))}getUnmoderated(e={type:"all"}){return Ee.aboutLocation({...e,location:"unmoderated",subreddit:r(this,F)},r(this,R))}getEdited(e={type:"all"}){return Ee.aboutLocation({...e,location:"edited",subreddit:r(this,F)},r(this,R))}static aboutLocation(e,t){let n=u.redditAPIPlugins.Moderation,o;switch(e.type){case"post":o="links";break;case"comment":o="comments";break;default:o=void 0}return new V({...e,fetch:async s=>{let a=await n.AboutLocation({...s,...e,only:o},t);return wc(a,t)}})}getCommentsAndPostsByIds(e){let t=u.redditAPIPlugins.LinksAndComments;return new V({fetch:async()=>{let n=await t.Info({thingIds:e,subreddits:[r(this,un)]},r(this,R));return wc(n,r(this,R))}})}static async addRemovalReason(e,t,n,o){return(await u.redditAPIPlugins.Subreddits.SubredditAddRemovalReason({title:t,message:n,subreddit:e},o)).id}static async getRemovalReasons(e,t){let o=await u.redditAPIPlugins.Subreddits.SubredditGetRemovalReasons({subreddit:e},t);return o.order.map(s=>({...o.data[s]}))}static async getFromMetadata(e){p(e);let t=e?.[S.SubredditName]?.values[0];if(t)return Ee.getByName(t,e);let n=e?.[S.Subreddit]?.values[0];return p(n),Ee.getById($(n),e)}static async getById(e,t){let n=await Ka(e,t);if(n)return Ee.getByName(n,t)}static async getByName(e,t){let o=await u.redditAPIPlugins.Subreddits.SubredditAbout({subreddit:e},t);if(!o?.data)throw new Error("not found");return new Ee(o.data,t)}};un=new WeakMap,F=new WeakMap,Kr=new WeakMap,Zr=new WeakMap,Xr=new WeakMap,Qr=new WeakMap,Yr=new WeakMap,eo=new WeakMap,to=new WeakMap,io=new WeakMap,no=new WeakMap,cn=new WeakMap,R=new WeakMap;var me=Ee;async function Fc(i,e){let s=(await X.query("GetSubredditInfoById","315a9b75c22a017d526afdf2d274616946156451aacfd56dfb91e7ad3f7a2fde",{id:i},e)).data?.subredditInfoById;if(!s)throw new Error("subreddit info not found");return s}async function Ac(i,e){let s=(await X.query("GetSubredditInfoByName","4aa69726c7e3f5d33ab2bee22b3d74fce645824fddd5ea3ec6dfe30bdb4295cb",{name:i},e)).data?.subredditInfoByName;if(!s)throw new Error("subreddit info not found");return s}async function Ic(i,e){let s=(await X.query("GetSubredditLeaderboard","18ead70c46b6446d45ecd8b679b16d9a929a933d6ef25d8262a459cb18b72848",{id:i},e)).data?.subredditInfoById?.leaderboard;if(!s)throw new Error("subreddit leaderboard not found");if(!s.summary)throw new Error("subreddit leaderboard summary not found");return{id:s.id,summary:s.summary}}async function Ec(i,e){let s=(await X.query("GetSubredditStyles","d491d17ea8858f563ea578b26b9595d64adecf4bf34557d567c7e53c470f5f22",{id:i},e)).data?.subredditInfoById?.styles;if(!s)throw new Error("subreddit styles not found");return s}function vg(i){if(i==="public"||i==="private"||i==="restricted"||i==="employees_only"||i==="gold_only"||i==="gold_restricted"||i==="archived"||i==="user")return i;throw new Error(`invalid subreddit type: ${i}`)}function kg(i){if(i==="any"||i==="link"||i==="self")return i;throw new Error(`invalid allowed post type: ${i}`)}function Cg(i){if(i==="animated"||i==="giphy"||i==="static"||i==="expression")return i;throw new Error(`invalid comment media type: ${i}`)}function wc(i,e){let n=(i.data?.children??[]).map(a=>{let c=o(a);if(c!=null)return c;let m=s(a);return m??null}).filter(Boolean);return{after:i.data?.after,before:i.data?.before,children:n};function o(a){try{return new W(a.data,e)}catch{return null}}function s(a){try{return new Q(a.data,e)}catch{return null}}}async function Ka(i,e){return(await u.redditAPIPlugins.LinksAndComments.Info({thingIds:[i],subreddits:[]},e)).data?.children[0]?.data?.displayName}import{CommunityListWidget_CommunityData as Pg,GetWidgetsResponse_WidgetItem as ae}from"@devvit/protos";var ro,oo,so,ao,Xa=class Xa{constructor(e,t,n){l(this,ro);l(this,oo);l(this,so);l(this,ao);K(this),d(this,ro,e.id),d(this,oo,e.shortName),d(this,so,t),d(this,ao,n)}get id(){return r(this,ro)}get name(){return r(this,oo)}get subredditName(){return r(this,so)}toJSON(){return{id:this.id,name:this.name,subredditName:this.subredditName}}delete(){return Xa.delete(this.subredditName,this.id,r(this,ao))}static async getWidgets(e,t){let o=await u.redditAPIPlugins.Widgets.GetWidgets({subreddit:e},t);p(o.layout,"Failed to load widgets for subreddit");let s=o.items,a=[];for(let c of o.layout.sidebar?.order??[]){let m=s[c];switch(m?.kind){case"image":a.push(new Cs(m,e,t));break;case"calendar":a.push(new Ps(m,e,t));break;case"textarea":a.push(new Ss(m,e,t));break;case"button":a.push(new ws(m,e,t));break;case"community-list":a.push(new xs(m,e,t));break;case"post-flair":a.push(new Fs(m,e,t));break;case"custom":a.push(new As(m,e,t));break;case"subreddit-rules":{let h=await u.redditAPIPlugins.Subreddits.SubredditAboutRules({subreddit:e},t);a.push(new Za(h,m,e,t));break}default:throw new Error(`Unknown widget type: ${m.kind}`)}}return a}static async delete(e,t,n){await u.redditAPIPlugins.Widgets.DeleteWidget({subreddit:e,id:t},n)}static async reorder(e,t,n){await u.redditAPIPlugins.Widgets.OrderWidgets({subreddit:e,order:t},n)}static async add(e,t){switch(e?.type){case"image":return Cs.create(e,t);case"calendar":return Ps.create(e,t);case"textarea":return Ss.create(e,t);case"button":return ws.create(e,t);case"community-list":return xs.create(e,t);case"post-flair":return Fs.create(e,t);case"custom":return As.create(e,t);default:throw new Error("Unknown widget type")}}};ro=new WeakMap,oo=new WeakMap,so=new WeakMap,ao=new WeakMap;var ne=Xa,lo,Is=class Is extends ne{constructor(t,n,o){super(t,n,o);l(this,lo);d(this,lo,t.data.map(s=>(p(s.url,"Image widget data is missing url"),p(s.height,"Image widget data is missing height"),p(s.width,"Image widget data is missing width"),p(s.linkUrl,"Image widget data is missing linkUrl"),{url:s.url,height:s.height,width:s.width,linkUrl:s.linkUrl})))}get images(){return r(this,lo)}toJSON(){return{...super.toJSON(),images:this.images}}static async create(t,n){let s=await u.redditAPIPlugins.Widgets.AddImageWidget(t,n);return new Is(ae.fromJSON(s),t.subreddit,n)}static async update(t,n){let s=await u.redditAPIPlugins.Widgets.UpdateImageWidget(t,n);return new Is(ae.fromJSON(s),t.subreddit,n)}};lo=new WeakMap;var Cs=Is,uo,co,mo,Es=class Es extends ne{constructor(t,n,o){super(t,n,o);l(this,uo);l(this,co);l(this,mo);p(t.googleCalendarId,"Calendar widget data is missing googleCalendarId"),p(t.configuration,"Calendar widget data is missing configuration"),p(t.styles,"Calendar widget data is missing styles"),d(this,uo,t.googleCalendarId),d(this,co,t.configuration),d(this,mo,t.styles)}get googleCalendarId(){return r(this,uo)}get configuration(){return r(this,co)}get styles(){return r(this,mo)}toJSON(){return{...super.toJSON(),googleCalendarId:this.googleCalendarId,configuration:this.configuration,styles:this.styles}}static async create(t,n){let s=await u.redditAPIPlugins.Widgets.AddCalendarWidget(t,n);return new Es(ae.fromJSON(s),t.subreddit,n)}static async update(t,n){let s=await u.redditAPIPlugins.Widgets.UpdateCalendarWidget(t,n);return new Es(ae.fromJSON(s),t.subreddit,n)}};uo=new WeakMap,co=new WeakMap,mo=new WeakMap;var Ps=Es,po,go,Ts=class Ts extends ne{constructor(t,n,o){super(t,n,o);l(this,po);l(this,go);p(t.text,"Textarea widget data is missing text"),p(t.styles,"Textarea widget data is missing styles"),d(this,po,t.text),d(this,go,t.styles)}get text(){return r(this,po)}get styles(){return r(this,go)}toJSON(){return{...super.toJSON(),text:this.text,styles:this.styles}}static async create(t,n){let s=await u.redditAPIPlugins.Widgets.AddTextAreaWidget(t,n);return new Ts(ae.fromJSON(s),t.subreddit,n)}static async update(t,n){let s=await u.redditAPIPlugins.Widgets.UpdateTextAreaWidget(t,n);return new Ts(ae.fromJSON(s),t.subreddit,n)}};po=new WeakMap,go=new WeakMap;var Ss=Ts,fo,ho,yo,Rs=class Rs extends ne{constructor(t,n,o){super(t,n,o);l(this,fo);l(this,ho);l(this,yo);p(t.styles,"Button widget data is missing styles"),d(this,fo,t.buttons),d(this,ho,t.description??""),d(this,yo,t.styles)}get buttons(){return r(this,fo)}get description(){return r(this,ho)}get styles(){return r(this,yo)}toJSON(){return{...super.toJSON(),buttons:this.buttons,description:this.description,styles:this.styles}}static async create(t,n){let s=await u.redditAPIPlugins.Widgets.AddButtonWidget(t,n);return new Rs(ae.fromJSON(s),t.subreddit,n)}static async update(t,n){let s=await u.redditAPIPlugins.Widgets.UpdateButtonWidget(t,n);return new Rs(ae.fromJSON(s),t.subreddit,n)}};fo=new WeakMap,ho=new WeakMap,yo=new WeakMap;var ws=Rs,bo,vo,Os=class Os extends ne{constructor(t,n,o){super(t,n,o);l(this,bo);l(this,vo);d(this,bo,t.data.map(s=>Pg.fromJSON(s))),p(t.styles,"Community list widget data is missing styles"),d(this,vo,t.styles)}get communities(){return r(this,bo)}get styles(){return r(this,vo)}toJSON(){return{...super.toJSON(),communities:this.communities,styles:this.styles}}static async create(t,n){let s=await u.redditAPIPlugins.Widgets.AddCommunityListWidget(t,n);return new Os(ae.fromJSON(s),t.subreddit,n)}static async update(t,n){let s=await u.redditAPIPlugins.Widgets.UpdateCommunityListWidget(t,n);return new Os(ae.fromJSON(s),t.subreddit,n)}};bo=new WeakMap,vo=new WeakMap;var xs=Os,ko,Co,Po,Ms=class Ms extends ne{constructor(t,n,o){super(t,n,o);l(this,ko);l(this,Co);l(this,Po);if(p(t.styles,"Post flair widget data is missing styles"),d(this,ko,t.styles),d(this,Co,t.order.map(s=>t.templates[s])),!(t.display&&t.display==="list"||t.display==="cloud"))throw new Error("Post flair widget data is missing display type");d(this,Po,t.display)}get styles(){return r(this,ko)}get templates(){return r(this,Co)}get display(){return r(this,Po)}toJSON(){return{...super.toJSON(),styles:this.styles,templates:this.templates,display:this.display}}static async create(t,n){let s=await u.redditAPIPlugins.Widgets.AddPostFlairWidget(t,n);return new Ms(ae.fromJSON(s),t.subreddit,n)}static async update(t,n){let s=await u.redditAPIPlugins.Widgets.UpdatePostFlairWidget(t,n);return new Ms(ae.fromJSON(s),t.subreddit,n)}};ko=new WeakMap,Co=new WeakMap,Po=new WeakMap;var Fs=Ms,So,wo,xo,Fo,Ao,Bs=class Bs extends ne{constructor(t,n,o){super(t,n,o);l(this,So);l(this,wo);l(this,xo);l(this,Fo);l(this,Ao);p(t.stylesheetUrl,"Custom widget data is missing stylesheetUrl"),p(t.height,"Custom widget data is missing height"),p(t.css,"Custom widget data is missing css"),d(this,So,t.imageData??[]),d(this,wo,t.text??""),d(this,xo,t.stylesheetUrl),d(this,Fo,t.height),d(this,Ao,t.css)}get images(){return r(this,So)}get text(){return r(this,wo)}get stylesheetUrl(){return r(this,xo)}get height(){return r(this,Fo)}get css(){return r(this,Ao)}toJSON(){return{...super.toJSON(),images:this.images,text:this.text,stylesheetUrl:this.stylesheetUrl,height:this.height,css:this.css}}static async create(t,n){let s=await u.redditAPIPlugins.Widgets.AddCustomWidget(t,n);return new Bs(ae.fromJSON(s),t.subreddit,n)}static async update(t,n){let s=await u.redditAPIPlugins.Widgets.UpdateCustomWidget(t,n);return new Bs(ae.fromJSON(s),t.subreddit,n)}};So=new WeakMap,wo=new WeakMap,xo=new WeakMap,Fo=new WeakMap,Ao=new WeakMap;var As=Bs,Io,Za=class extends ne{constructor(t,n,o,s){super(n,o,s);l(this,Io);let a=t.rules.map(({description:c,priority:m,shortName:h,violationReason:v})=>(p(c,"Subreddit rule is missing description"),p(m,"Subreddit rule is missing priority"),p(h,"Subreddit rule is missing shortName"),p(v,"Subreddit rule is missing violationReason"),{description:c,priority:m,shortName:h,violationReason:v}));d(this,Io,a)}get rules(){return r(this,Io)}toJSON(){return{...super.toJSON(),rules:this.rules}}};Io=new WeakMap;var Sg=(n=>(n[n.SUBREDDIT_PERMISSIONS=0]="SUBREDDIT_PERMISSIONS",n[n.APPROVED_CONTRIBUTORS_ONLY=1]="APPROVED_CONTRIBUTORS_ONLY",n[n.MODS_ONLY=2]="MODS_ONLY",n))(Sg||{}),pe,ge,mn,pn,gn,fn,hn,yn,Te,xe=class xe{constructor(e,t,n,o){l(this,pe);l(this,ge);l(this,mn);l(this,pn);l(this,gn);l(this,fn);l(this,hn);l(this,yn);l(this,Te);K(this),d(this,pe,e),d(this,ge,t),d(this,mn,n.contentMd),d(this,pn,n.contentHtml),d(this,gn,n.revisionId),d(this,fn,new Date(n.revisionDate*1e3)),d(this,hn,n.reason??""),d(this,yn,n.revisionBy?.data?new C(n.revisionBy.data,o):void 0),d(this,Te,o)}get name(){return r(this,pe)}get subredditName(){return r(this,ge)}get content(){return r(this,mn)}get contentHtml(){return r(this,pn)}get revisionId(){return r(this,gn)}get revisionDate(){return r(this,fn)}get revisionReason(){return r(this,hn)}get revisionAuthor(){return r(this,yn)}toJSON(){return{name:r(this,pe),subredditName:r(this,ge),content:r(this,mn),contentHtml:r(this,pn),revisionId:r(this,gn),revisionDate:r(this,fn),revisionReason:r(this,hn),revisionAuthor:r(this,yn)?.toJSON()}}async update(e,t){return xe.updatePage({subredditName:r(this,ge),page:r(this,pe),content:e,reason:t},r(this,Te))}async getRevisions(e){return xe.getPageRevisions({subredditName:r(this,ge),page:r(this,pe),...e},r(this,Te))}async revertTo(e){return xe.revertPage(r(this,ge),r(this,pe),e,r(this,Te))}async getSettings(){return xe.getPageSettings(r(this,ge),r(this,pe),r(this,Te))}async updateSettings(e){return xe.updatePageSettings({subredditName:r(this,ge),page:r(this,pe),listed:e.listed,permLevel:e.permLevel},r(this,Te))}async addEditor(e){return xe.addEditor(r(this,ge),r(this,pe),e,r(this,Te))}async removeEditor(e){return xe.removeEditor(r(this,ge),r(this,pe),e,r(this,Te))}static async getPage(e,t,n){let s=await u.redditAPIPlugins.Wiki.GetWikiPage({subreddit:e,page:t},n);return p(s.data,"Failed to get wiki page"),new xe(t,e,s.data,n)}static async getPages(e,t){return(await u.redditAPIPlugins.Wiki.GetWikiPages({subreddit:e},t)).data||[]}static async createPage(e,t){return xe.updatePage(e,t)}static async updatePage(e,t){return await u.redditAPIPlugins.Wiki.EditWikiPage({subreddit:e.subredditName,page:e.page,content:e.content,reason:e.reason??""},t),xe.getPage(e.subredditName,e.page,t)}static getPageRevisions(e,t){let n=u.redditAPIPlugins.Wiki;return new V({hasMore:!0,after:e.after,limit:e.limit,pageSize:e.pageSize,async fetch(o){let s=await n.GetWikiPageRevisions({subreddit:e.subredditName,page:e.page,limit:o.limit,after:o.after,before:o.before},t);return wg(s,t)}})}static async revertPage(e,t,n,o){await u.redditAPIPlugins.Wiki.RevertWikiPage({subreddit:e,page:t,revision:n},o)}static async getPageSettings(e,t,n){let s=await u.redditAPIPlugins.Wiki.GetWikiPageSettings({subreddit:e,page:t},n);return p(s.data,"Failed to get wiki page settings"),new Us(s.data,n)}static async updatePageSettings(e,t){let o=await u.redditAPIPlugins.Wiki.UpdateWikiPageSettings({subreddit:e.subredditName,page:e.page,listed:e.listed?"on":"",permlevel:e.permLevel},t);return p(o.data,"Failed to update wiki page settings"),new Us(o.data,t)}static async addEditor(e,t,n,o){await u.redditAPIPlugins.Wiki.AllowEditor({act:"add",subreddit:e,page:t,username:n},o)}static async removeEditor(e,t,n,o){await u.redditAPIPlugins.Wiki.AllowEditor({act:"del",subreddit:e,page:t,username:n},o)}};pe=new WeakMap,ge=new WeakMap,mn=new WeakMap,pn=new WeakMap,gn=new WeakMap,fn=new WeakMap,hn=new WeakMap,yn=new WeakMap,Te=new WeakMap;var fe=xe,bn,vn,kn,Cn,Pn,Sn,Qa=class{constructor(e,t){l(this,bn);l(this,vn);l(this,kn);l(this,Cn);l(this,Pn);l(this,Sn);d(this,bn,e.id),d(this,vn,e.page),d(this,kn,new Date(e.timestamp)),p(e.author?.data,"Wiki page revision author details are missing"),d(this,Cn,new C(e.author.data,t)),d(this,Pn,e.reason??""),d(this,Sn,e.revisionHidden??!1)}get id(){return r(this,bn)}get page(){return r(this,vn)}get date(){return r(this,kn)}get author(){return r(this,Cn)}get reason(){return r(this,Pn)}get hidden(){return r(this,Sn)}toJSON(){return{id:r(this,bn),page:r(this,vn),date:r(this,kn),author:r(this,Cn).toJSON(),reason:r(this,Pn),hidden:r(this,Sn)}}};bn=new WeakMap,vn=new WeakMap,kn=new WeakMap,Cn=new WeakMap,Pn=new WeakMap,Sn=new WeakMap;var wn,xn,Fn,Us=class{constructor(e,t){l(this,wn);l(this,xn);l(this,Fn);d(this,wn,e.listed),d(this,xn,e.permLevel),d(this,Fn,e.editors.map(n=>(p(n.data,"Wiki page editor details are missing"),new C(n.data,t))))}get listed(){return r(this,wn)}get permLevel(){return r(this,xn)}get editors(){return r(this,Fn)}toJSON(){return{listed:r(this,wn),permLevel:r(this,xn),editors:r(this,Fn).map(e=>e.toJSON())}}};wn=new WeakMap,xn=new WeakMap,Fn=new WeakMap;function wg(i,e){return p(i.data?.children,"Wiki page revision listing is missing children"),{children:i.data.children.map(n=>new Qa(n,e)),before:i.data.before,after:i.data.after}}async function Tc(i,e){return Oc("GetVaultContactByAddress","3e2f7966a5c120e64fd2795d06a46595c52d988185be98d3ed71c3f81ae80d2e",{provider:"ethereum",address:i},e)}async function Rc(i,e){return Oc("GetVaultContactByUserId","a854ddc19d0e22c4f36ed917fdbd568f299f3571427e393aee5e2972080fffe9",{provider:"ethereum",userId:i},e)}async function Oc(i,e,t,n){let s=(await X.query(i,e,t,n))?.data?.vault?.contact;return{provider:s?.provider,userId:te(s?.userId),address:s?.address,createdAt:s?.createdAt,isActive:s?.isActive}}function eS(){let i=g();return new ks(i)}function tS(i){let e=g();return me.getById(ye(i),e)}function rl(i){let e=g();return Fc(i,e)}function iS(i){let e=g();return me.getByName(i,e)}function nS(i){let e=g();return Ac(i,e)}function rS(i,e){let t=g();return me.addRemovalReason(i,e.title,e.message,t)}function oS(i){let e=g();return me.getRemovalReasons(i,e)}async function sS(){let i=g(),e=i?.[S.SubredditName]?.values[0];if(e)return e;let t=i?.[S.Subreddit]?.values[0],n=await Ka($(t),i);if(!n)throw new Error("Couldn't get current subreddit's name");return n}async function Mc(){let i=g(),e=await me.getFromMetadata(i);if(!e)throw new Error("Couldn't get current subreddit");return e}function ol(i){let e=g();return W.getById(ye(i),e)}function aS(i){let e=g();return W.submit(i,e)}function dS(i){let e=g();return W.crosspost(i,e)}function lS(i){let e=g();return C.getById(ye(i),e)}function uS(i){let e=g();return C.getByUsername(i,e)}async function cS(){let i=g();return hc(i)}async function mS(){let i=g();return yc(i)}function pS(){let i=g();return C.getFromMetadata(S.AppUser,i)}function gS(i){let e=g();return C.getSnoovatarUrl(i,e)}function sl(i){let e=g();return Q.getById(ye(i),e)}function fS(i){let e=g();return Q.getComments(i,e)}function hS(i){let e=g();return Q.getCommentsByUser(i,e)}function yS(i){let e=g();return Q.submit({...i,id:ye(i.id)},e)}function bS(i){let e=g();return W.getControversialPosts(i,e)}function vS(i){let e=g();return W.getTopPosts(i,e)}function kS(i){let e=g();return W.getHotPosts(i,e)}function CS(i){let e=g();return W.getNewPosts(i,e)}function PS(i){let e=g();return W.getRisingPosts(i,e)}function SS(i){let e=g();return W.getPostsByUser(i,e)}function wS(i){let e=g();return C.getOverview(i,e)}function xS(i){let e=g();return vs(i,e)}function FS(i){let e=g();return C.getSubredditUsersByType({type:"contributors",...i},e)}function AS(i,e){let t=g();return C.createRelationship({username:i,subredditName:e,type:"contributor"},t)}function IS(i,e){let t=g();return C.removeRelationship({username:i,subredditName:e,type:"contributor"},t)}function ES(i){let e=g();return C.getSubredditUsersByType({type:"wikicontributors",...i},e)}function TS(i,e){let t=g();return C.createRelationship({username:i,subredditName:e,type:"wikicontributor"},t)}function RS(i,e){let t=g();return C.removeRelationship({username:i,subredditName:e,type:"wikicontributor"},t)}function OS(i){let e=g();return C.getSubredditUsersByType({type:"banned",...i},e)}function MS(i){let e=g();return C.createRelationship({username:i.username,subredditName:i.subredditName,type:"banned",banReason:i.reason,banMessage:i.message,note:i.note,duration:i.duration,banContext:i.context},e)}function BS(i,e){let t=g();return C.removeRelationship({username:i,subredditName:e,type:"banned"},t)}function US(i){let e=g();return C.getSubredditUsersByType({type:"wikibanned",...i},e)}function DS(i){let e=g();return C.createRelationship({...i,type:"wikibanned"},e)}function NS(i,e){let t=g();return C.removeRelationship({username:i,subredditName:e,type:"wikibanned"},t)}function al(i){let e=g();return C.getSubredditUsersByType({type:"moderators",...i},e)}function LS(i){let e=g();return C.createRelationship({type:"moderator_invite",subredditName:i.subredditName,username:i.username,permissions:i.permissions??[]},e)}function _S(i,e){let t=g();return C.removeRelationship({username:i,subredditName:e,type:"moderator_invite"},t)}function HS(i,e){let t=g();return C.removeRelationship({type:"moderator",subredditName:e,username:i},t)}function jS(i,e,t){let n=g();return C.setModeratorPermissions(i,e,t,n)}function VS(i){let e=g();return C.getSubredditUsersByType({type:"muted",...i},e)}function WS(i){let e=g();return C.createRelationship({...i,type:"muted"},e)}function GS(i,e){let t=g();return C.removeRelationship({username:i,subredditName:e,type:"muted"},t)}function JS(i){let e=g();return Se.get(i,e)}function zS(i){let e=g();return Se.delete(i,e)}function qS(i){let e=g(),t={...i,redditId:i.redditId?ye(i.redditId):void 0};return Se.add(t,e)}function $S(i){let e=g();return Se.addRemovalNote(i,e)}async function KS(i){let e=g();return Qt.send(i,e)}async function ZS(i){let e=g();return Qt.sendAsSubreddit(i,e)}async function XS(i){let e=g();if(Je(i))return Q.approve(i,e);if(At(i))return W.approve(i,e);throw new Error("id must start with either t1_ or t3_")}async function QS(i,e){let t=g();if(Je(i))return Q.remove(i,e,t);if(At(i))return W.remove(i,e,t);throw new Error("id must start with either t1_ or t3_")}async function YS(i){let e=g();return se.getPostFlairTemplates(i,e)}async function ew(i){let e=g();return se.getUserFlairTemplates(i,e)}async function tw(i){let e=g();return se.createPostFlairTemplate(i,e)}async function iw(i){let e=g();return se.createUserFlairTemplate(i,e)}async function nw(i){let e=g();return se.editFlairTemplate(i,e)}async function rw(i,e){let t=g();return se.deleteFlairTemplate(i,e,t)}async function ow(i){let e=g();return ce.setUserFlair(i,e)}async function sw(i,e){let t=g();return ce.setUserFlairBatch(i,e,t)}async function aw(i,e){let t=g();return ce.removeUserFlair(i,e,t)}async function dw(i){let e=g();return ce.setPostFlair(i,e)}async function lw(i,e){let t=g();return ce.removePostFlair(i,de(e),t)}async function uw(i){let e=g();return ne.getWidgets(i,e)}async function cw(i,e){let t=g();return ne.delete(i,e,t)}async function mw(i){let e=g();return ne.add(i,e)}async function pw(i,e){let t=g();return ne.reorder(i,e,t)}async function gw(i,e){let t=g();return fe.getPage(i,e,t)}async function fw(i){let e=g();return fe.getPages(i,e)}async function hw(i){let e=g();return fe.createPage(i,e)}async function yw(i){let e=g();return fe.updatePage(i,e)}function bw(i){let e=g();return fe.getPageRevisions(i,e)}async function vw(i,e,t){let n=g();return fe.revertPage(i,e,t,n)}async function kw(i,e){let t=g();return fe.getPageSettings(i,e,t)}async function Cw(i){let e=g();return fe.updatePageSettings(i,e)}async function Pw(i,e,t){let n=g();return fe.addEditor(i,e,t,n)}async function Sw(i,e,t){let n=g();return fe.removeEditor(i,e,t,n)}function ww(i){let e=g();return Qt.getMessages(i,e)}function xw(){let i=g();return Qt.markAllAsRead(i)}function Fw(i,e){let t=g();return u.redditAPIPlugins.LinksAndComments.Report({reason:e.reason,thingId:i.id,srName:i.subredditName,usernames:i.authorName},t)}function Aw(i){let e=g();return me.aboutLocation({...i,location:"modqueue"},e)}function Iw(i){let e=g();return me.aboutLocation({...i,location:"reports"},e)}function Ew(i){let e=g();return me.aboutLocation({...i,location:"spam"},e)}function Tw(i){let e=g();return me.aboutLocation({...i,location:"unmoderated"},e)}function Rw(i){let e=g();return me.aboutLocation({...i,location:"edited"},e)}function Ow(i){let e=g();return Tc(i,e)}function Mw(i){let e=g();return Rc(ye(i),e)}function Bw(i){let e=g();return Ic(i,e)}function Uw(i){let e=g();return Ec(i,e)}async function Dw(){let i=g(),e=await Mc();await u.redditAPIPlugins.Subreddits.Subscribe({action:"sub",actionSource:"",srName:e.name,sr:"",skipInitialDefaults:!0},i)}async function Nw(){let i=g(),e=await Mc();await u.redditAPIPlugins.Subreddits.Subscribe({action:"unsub",actionSource:"",srName:e.name,sr:"",skipInitialDefaults:!1},i)}var xg=["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"],Fg=["border-image","border-image-source","behavior","expression","list-style-image","cursor","content"],Ag=["onload","onerror","onclick","onmouseover"];function Ig(i){return/xmlns=["']http:\/\/www\.w3\.org\/2000\/svg["']/.test(i)?i:i.replace(/<svg\b/,'<svg xmlns="http://www.w3.org/2000/svg"')}function Bc(i){if(i){if(!i.trim().startsWith("<svg")){console.log("The provided string is not a valid SVG.");return}try{let e=new RegExp(`<\\s*(${xg.join("|")})\\b`,"gi"),t=new RegExp(`(${Fg.join("|")})\\s*:\\s*url\\s*\\((['"]?)(.*?)\\2\\)`,"gi"),n=new RegExp(`(${Ag.join("|")})\\s*(=\\s*(['"]?)(.*?)\\3)?`,"gi");i=i.trim().replace(/\s+/g," "),i=Ig(i);let o=i.match(e)||[],s=i.match(t)||[],a=i.match(n)||[],c=!1;return o.length>0&&(c=!0,console.warn(`Disallowed elements detected in SVG: ${o.map(m=>m.replace("<","")).join(", ")}`)),s.length>0&&(c=!0,console.warn(`Disallowed styles detected in SVG: ${s.map(m=>m.split(":")[0]).join(", ")}`)),a.length>0&&(c=!0,console.warn(`Disallowed attributes detected in SVG: ${a.map(m=>m.split("=")[0]).join(", ")}`)),c?void 0:i}catch{return}}}function jw(i,...e){let t="";return i.forEach((n,o)=>{t+=n;let s=e[o];s!==void 0&&(t+=`${s}`)}),t=Bc(t),t===void 0?"":`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(t)}`}import{EffectType as Dc}from"@devvit/protos";import{WebViewVisibility as Eg}from"@devvit/protos";var Uc=i=>i===null||typeof i!="object"?!1:"scope"in i&&i.scope===0&&"type"in i&&i.type==="devvit-internal";var An,Eo,To,In,Yt,Ro,Ya=class{constructor(e,t){this.state={messageCount:0};l(this,An);l(this,Eo);l(this,To);l(this,In);l(this,Yt);this.postMessage=e=>{try{let t=JSON.stringify(e);r(this,Yt).emitEffect(`postMessage${this.state.messageCount++}`,{type:Dc.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:r(this,An),app:{message:e,jsonString:t}}}})}catch(t){throw console.error(et.caughtToString(t)),Error("Something went wrong. Please check the contents of your postMessage.")}};this.mount=()=>{let t=(r(this,Yt)?.devvitContext?.assets).getURL(r(this,Eo),{webView:!0});if(!t)throw Error("useWebView fullscreen request failed; web view asset could not be found");r(this,Ro).call(this,!0,t)};this.unmount=()=>{r(this,Ro).call(this,!1,"")};l(this,Ro,(e,t)=>{r(this,Yt).emitEffect("fullscreen",{type:Dc.EFFECT_WEB_VIEW,webView:{fullscreen:{id:r(this,An),show:e,url:t}}})});d(this,Eo,t.url??"index.html"),d(this,An,e.hookId),d(this,To,t.onMessage),d(this,In,t.onUnmount),d(this,Yt,e.context)}async onUIEvent(e){if(e.webView?.fullScreen)!(e.webView.fullScreen.visibility===Eg.WEBVIEW_VISIBLE)&&r(this,In)&&await r(this,In).call(this,this);else if(e.webView?.postMessage){let t=e.webView.postMessage.jsonString?JSON.parse(e.webView.postMessage.jsonString):e.webView.postMessage.message;if(Uc(t))return;await r(this,To).call(this,t,this)}}};An=new WeakMap,Eo=new WeakMap,To=new WeakMap,In=new WeakMap,Yt=new WeakMap,Ro=new WeakMap;function Tg(i){let e=le({namespace:"useWebView",initializer:t=>new Ya(t,i)});return{postMessage:e.postMessage,mount:e.mount,unmount:e.unmount}}export{Vg as ALL_ICON_NAMES,xc as AboutLocations,Pc as AuthorFlairSettings,ws as ButtonWidget,Ps as CalendarWidget,Q as Comment,xs as CommunityListWidget,As as CustomWidget,zg as DeletionReason,u as Devvit,qg as EventSource,ce as Flair,se as FlairTemplate,Zp as FlairType,ze as Hook,Cs as ImageWidget,V as Listing,yg as ModMailActionType,fg as ModMailConversationState,ks as ModMailService,Se as ModNote,W as Post,Sc as PostFlairSettings,Fs as PostFlairWidget,Qt as PrivateMessage,jt as RichTextBuilder,he as RunAs,_s as SettingScope,cg as SocialLinkType,me as Subreddit,kc as SubredditDescription,Za as SubredditRulesWidget,Cc as SubredditWikiSettings,Ss as TextAreaWidget,C as User,ne as Widget,fe as WikiPage,Sg as WikiPagePermissionLevel,Qa as WikiPageRevision,Us as WikiPageSettings,vs as _getModerationLog,Fc as _getSubredditInfoById,Ac as _getSubredditInfoByName,Ic as _getSubredditLeaderboard,Ka as _getSubredditNameById,Ec as _getSubredditStyles,Pw as addEditorToWikiPage,qS as addModNote,$S as addRemovalNote,rS as addSubredditRemovalReason,mw as addWidget,TS as addWikiContributor,XS as approve,AS as approveUser,MS as banUser,DS as banWikiContributor,or as convertUserFlairProtoToAPI,tw as createPostFlairTemplate,iw as createUserFlairTemplate,hw as createWikiPage,dS as crosspost,rw as deleteFlairTemplate,zS as deleteModNote,cw as deleteWidget,nw as editFlairTemplate,pS as getAppUser,FS as getApprovedUsers,OS as getBannedUsers,US as getBannedWikiContributors,sl as getCommentById,fS as getComments,wS as getCommentsAndPostsByUser,hS as getCommentsByUser,bS as getControversialPosts,Mc as getCurrentSubreddit,sS as getCurrentSubredditName,mS as getCurrentUser,yc as getCurrentUserFromMetadata,cS as getCurrentUsername,hc as getCurrentUsernameFromMetadata,Rw as getEdited,kS as getHotPosts,ww as getMessages,JS as getModNotes,Aw as getModQueue,xS as getModerationLog,al as getModerators,VS as getMutedUsers,CS as getNewPosts,ol as getPostById,YS as getPostFlairTemplates,SS as getPostsByUser,Iw as getReports,PS as getRisingPosts,gS as getSnoovatarUrl,Ew as getSpam,tS as getSubredditById,iS as getSubredditByName,rl as getSubredditInfoById,nS as getSubredditInfoByName,Bw as getSubredditLeaderboard,oS as getSubredditRemovalReasons,Uw as getSubredditStyles,vS as getTopPosts,Tw as getUnmoderated,lS as getUserById,uS as getUserByUsername,ew as getUserFlairTemplates,Ow as getVaultByAddress,Mw as getVaultByUserId,uw as getWidgets,ES as getWikiContributors,gw as getWikiPage,bw as getWikiPageRevisions,kw as getWikiPageSettings,fw as getWikiPages,LS as inviteModerator,xw as markAllMessagesAsRead,eS as modMail,WS as muteUser,QS as remove,Sw as removeEditorFromWikiPage,HS as removeModerator,lw as removePostFlair,IS as removeUser,aw as removeUserFlair,RS as removeWikiContributor,pw as reorderWidgets,Fw as report,vw as revertWikiPage,_S as revokeModeratorInvite,KS as sendPrivateMessage,ZS as sendPrivateMessageAsSubreddit,jS as setModeratorPermissions,dw as setPostFlair,ow as setUserFlair,sw as setUserFlairBatch,yS as submitComment,aS as submitPost,Dw as subscribeToCurrentSubreddit,jw as svg,BS as unbanUser,NS as unbanWikiContributor,GS as unmuteUser,Nw as unsubscribeFromCurrentSubreddit,yw as updateWikiPage,Cw as updateWikiPageSettings,Dp as useAsync,wa as useChannel,Ca as useForm,Aa as useInterval,Ra as useState,Tg as useWebView};
|
|
7
7
|
/*! Bundled license information:
|
|
8
8
|
|
|
9
9
|
shallow-clone/index.js:
|