Skip to content

Commit 97e1e0b

Browse files
committed
Fix: Force cache bypass for TWA compatibility
1 parent a4fd273 commit 97e1e0b

File tree

1 file changed

+192
-0
lines changed

1 file changed

+192
-0
lines changed

src/parts/github-helper.html

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
<!--
2+
Sune: GitHub Commit & Delete Helper
3+
Version: 3.3
4+
-->
5+
<div id="sune_github_helper" x-data="{v:'3.3'}" class="hidden"></div>
6+
<script>
7+
(()=>{
8+
const suneEl=document.getElementById('sune_github_helper');
9+
if(!suneEl){console.error("Sune container not found.");return}
10+
const SUNE_NAME='[Sune: GitHub Helper]', SUNE_V=suneEl.getAttribute('x-data').match(/v:'(.*?)'/)[1];
11+
console.log(`${SUNE_NAME} Initializing v${SUNE_V}`);
12+
13+
const defaultClasses=['bg-slate-100','text-slate-700','hover:bg-slate-200'],
14+
successClasses=['bg-green-100','text-green-800'],
15+
errorClasses=['bg-red-100','text-red-800'];
16+
17+
const safeJson=async(res)=>{
18+
const txt=await res.text();
19+
try{return JSON.parse(txt)}
20+
catch(e){
21+
// If we got raw content instead of JSON, we show a snippet to help debug
22+
const snippet = txt.substring(0, 50).replace(/\n/g, ' ');
23+
return{_isRaw:true, message:`Expected JSON but got raw text: "${snippet}..."`};
24+
}
25+
};
26+
27+
const deleteFile=async(btn,owner,repo,branch,path,commitMsg)=>{
28+
const token=window.USER?.githubToken;
29+
if(!token){alert('GitHub token not set in Account Settings > API.');return}
30+
31+
btn.disabled=true;
32+
btn.innerHTML='<span class="relative flex h-3 w-3"><span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-sky-400 opacity-75"></span><span class="relative inline-flex rounded-full h-3 w-3 bg-sky-500"></span></span> Checking...';
33+
34+
const H={'Authorization':`Bearer ${token}`,'Accept':'application/vnd.github.v3+json'};
35+
try{
36+
const safePath=path.split('/').map(encodeURIComponent).join('/');
37+
// Add timestamp to bypass TWA/ServiceWorker cache
38+
const CONTENTS_URL=`https://api.github.com/repos/${owner}/${repo}/contents/${safePath}?t=${Date.now()}`;
39+
40+
const fileCheckRes=await fetch(`${CONTENTS_URL}&ref=${branch}`,{headers:H, cache:'no-store'});
41+
if(fileCheckRes.status===404)throw new Error('File not found. Nothing to delete.');
42+
43+
const fileData=await safeJson(fileCheckRes);
44+
if(!fileCheckRes.ok || fileData._isRaw)throw new Error(fileData.message || 'Failed to get file info');
45+
if(!fileData.sha)throw new Error('API returned content without SHA.');
46+
47+
btn.innerHTML='<span class="relative flex h-3 w-3"><span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-sky-400 opacity-75"></span><span class="relative inline-flex rounded-full h-3 w-3 bg-sky-500"></span></span> Deleting...';
48+
49+
const msg=commitMsg?.trim()||`Chore: Delete ${path.split('/').pop()}`;
50+
const body={message:msg,sha:fileData.sha,branch};
51+
52+
// DELETE requests also need the cache buster in some environments
53+
const deleteRes=await fetch(CONTENTS_URL,{method:'DELETE',headers:H,body:JSON.stringify(body), cache:'no-store'});
54+
if(!deleteRes.ok)throw new Error(`DELETE file failed: ${(await safeJson(deleteRes)).message}`);
55+
56+
btn.classList.remove(...defaultClasses);btn.classList.add(...successClasses);
57+
btn.innerHTML='<i data-lucide="check" class="h-3.5 w-3.5"></i> Deleted';
58+
}catch(err){
59+
alert(`${SUNE_NAME} Deletion Failed:\n\n${err.message}`);
60+
btn.classList.remove(...defaultClasses);btn.classList.add(...errorClasses);
61+
btn.innerHTML='<i data-lucide="x" class="h-3.5 w-3.5"></i> Failed';
62+
setTimeout(()=>{
63+
btn.disabled=false;
64+
btn.classList.remove(...errorClasses);btn.classList.add(...defaultClasses);
65+
btn.innerHTML='<i data-lucide="trash-2" class="h-3.5 w-3.5"></i> Delete';
66+
window.lucide?.createIcons();
67+
},4e3);
68+
}finally{window.lucide?.createIcons()}
69+
};
70+
71+
const commitFile=async(btn,owner,repo,branch,path,content,commitMsg)=>{
72+
const token=window.USER?.githubToken;
73+
if(!token){alert('GitHub token not set in Account Settings > API.');return}
74+
75+
btn.disabled=true;
76+
btn.innerHTML='<span class="relative flex h-3 w-3"><span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-sky-400 opacity-75"></span><span class="relative inline-flex rounded-full h-3 w-3 bg-sky-500"></span></span> Authenticating...';
77+
78+
const H={'Authorization':`Bearer ${token}`,'Accept':'application/vnd.github.v3+json'};
79+
try{
80+
const userRes=await fetch(`https://api.github.com/user?t=${Date.now()}`,{headers:H, cache:'no-store'});
81+
if(!userRes.ok)throw new Error('GitHub token invalid or lacks user:read scope.');
82+
const userData = await safeJson(userRes);
83+
const username=userData.login;
84+
85+
btn.innerHTML='<span class="relative flex h-3 w-3"><span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-sky-400 opacity-75"></span><span class="relative inline-flex rounded-full h-3 w-3 bg-sky-500"></span></span> Committing...';
86+
87+
const repoCheckRes=await fetch(`https://api.github.com/repos/${owner}/${repo}?t=${Date.now()}`,{headers:H, cache:'no-store'});
88+
if(repoCheckRes.status===404){
89+
const isOrg=owner.toLowerCase()!==username.toLowerCase(),createRepoUrl=isOrg?`https://api.github.com/orgs/${owner}/repos`:'https://api.github.com/user/repos';
90+
const createRepoRes=await fetch(createRepoUrl,{method:'POST',headers:H,body:JSON.stringify({name:repo,private:false})});
91+
if(!createRepoRes.ok){
92+
let data=await safeJson(createRepoRes);
93+
throw new Error(`Repo creation failed: ${data.message}`);
94+
}
95+
}
96+
97+
const safePath=path.split('/').map(encodeURIComponent).join('/');
98+
const CONTENTS_URL=`https://api.github.com/repos/${owner}/${repo}/contents/${safePath}?t=${Date.now()}`;
99+
let sha;
100+
101+
const fileCheckRes=await fetch(`${CONTENTS_URL}&ref=${branch}`,{headers:H, cache:'no-store'});
102+
if(fileCheckRes.ok){
103+
const fileData=await safeJson(fileCheckRes);
104+
if(fileData._isRaw) throw new Error('TWA Cache Error: Received raw file instead of API response.');
105+
sha=fileData.sha;
106+
}
107+
108+
const msg=commitMsg?.trim()||(sha?`Revert: Update ${path.split('/').pop()}`:`Feat: Add ${path.split('/').pop()}`);
109+
const b64c=btoa(unescape(encodeURIComponent(content)));
110+
const body={message:msg,content:b64c,sha,branch};
111+
112+
const putRes=await fetch(CONTENTS_URL,{method:'PUT',headers:H,body:JSON.stringify(body), cache:'no-store'});
113+
if(!putRes.ok)throw new Error(`PUT file failed: ${(await safeJson(putRes)).message}`);
114+
115+
btn.classList.remove(...defaultClasses);btn.classList.add(...successClasses);
116+
btn.innerHTML='<i data-lucide="check" class="h-3.5 w-3.5"></i> Success';
117+
}catch(err){
118+
alert(`${SUNE_NAME} Commit Failed:\n\n${err.message}`);
119+
btn.classList.remove(...defaultClasses);btn.classList.add(...errorClasses);
120+
btn.innerHTML='<i data-lucide="x" class="h-3.5 w-3.5"></i> Failed';
121+
setTimeout(()=>{
122+
btn.disabled=false;
123+
btn.classList.remove(...errorClasses);btn.classList.add(...defaultClasses);
124+
btn.innerHTML='<i data-lucide="github" class="h-3.5 w-3.5"></i> Commit';
125+
window.lucide?.createIcons();
126+
},4e3);
127+
}finally{window.lucide?.createIcons()}
128+
};
129+
130+
const processBubble=bubble=>{
131+
if(!bubble||bubble.dataset.suneGchProcessed)return;
132+
let buttonAdded=false;
133+
bubble.querySelectorAll('p:not(:has(button.commit-btn))').forEach(p=>{
134+
const link=p.querySelector('a');
135+
if(!link)return;
136+
const m=link.textContent.trim().match(/^([^\/]+)\/([^\/]+)@([^\/]+)\/(.+)$/);
137+
if(!m)return;
138+
139+
const[_,owner,repo,branch,path]=m,commitMsg=link.title,isDelete=(commitMsg||'').toLowerCase().startsWith('delete:');
140+
const btn=document.createElement('button');
141+
btn.className='commit-btn ml-2 inline-flex items-center gap-1.5 rounded-md bg-slate-100 px-2 py-1 text-xs font-medium text-slate-700 hover:bg-slate-200 transition-colors';
142+
143+
if(isDelete){
144+
btn.innerHTML='<i data-lucide="trash-2" class="h-3.5 w-3.5"></i> Delete';
145+
btn.onclick=()=>deleteFile(btn,owner,repo,branch,path.trim(),commitMsg);
146+
p.append(btn);
147+
buttonAdded=true;
148+
}else{
149+
const preEl=p.nextElementSibling;
150+
if(preEl?.tagName!=='PRE')return;
151+
const code=preEl.querySelector('code')?.innerText;
152+
if(code==null)return;
153+
btn.innerHTML='<i data-lucide="github" class="h-3.5 w-3.5"></i> Commit';
154+
btn.onclick=()=>commitFile(btn,owner,repo,branch,path.trim(),code,commitMsg);
155+
p.append(btn);
156+
buttonAdded=true;
157+
}
158+
});
159+
if(buttonAdded){bubble.dataset.suneGchProcessed='true';window.lucide?.createIcons()}
160+
return buttonAdded;
161+
};
162+
163+
const scanExisting=()=>document.querySelectorAll('#messages .msg-bubble').forEach(processBubble);
164+
const observer=new MutationObserver(mutations=>{for(const m of mutations)for(const node of m.addedNodes)if(node.nodeType===1){const b=node.matches?.('.msg-bubble')?[node]:node.querySelectorAll?.('.msg-bubble');b?.forEach(processBubble)}});
165+
166+
const newResponseListener=e=>{
167+
const id=e?.detail?.message?.id; if(!id)return;
168+
let attempts=0,maxAttempts=8,interval=300;
169+
const tryProcess=()=>{
170+
attempts++;
171+
const bubble=window.getBubbleById(id);
172+
if(bubble&&processBubble(bubble))return;
173+
if(attempts<maxAttempts)setTimeout(tryProcess,interval);
174+
};
175+
setTimeout(tryProcess,150);
176+
};
177+
178+
const composerEl=window.el?.composer,chatContainer=window.el?.messages;
179+
if(chatContainer&&composerEl){
180+
observer.observe(chatContainer,{childList:true,subtree:true});
181+
composerEl.addEventListener('sune:newSuneResponse',newResponseListener);
182+
scanExisting();
183+
console.log(`${SUNE_NAME} Observer and event listener attached. Initial scan complete.`);
184+
}
185+
186+
suneEl.addEventListener('sune:unmount',()=>{
187+
observer.disconnect();
188+
if(composerEl)composerEl.removeEventListener('sune:newSuneResponse',newResponseListener);
189+
console.log(`${SUNE_NAME} Unmounted.`);
190+
});
191+
})();
192+
</script>

0 commit comments

Comments
 (0)