File size: 1,317 Bytes
fb88864
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Cookieless session: a stable localStorage token sent as a header on every
// /api fetch, and appended as ?sid= on <img> sprite URLs. Works inside HF
// Spaces' cross-site iframe regardless of third-party-cookie policy.
(function () {
    let sid = localStorage.getItem('weedsim_sid');
    if (!sid) {
        sid = (window.crypto && crypto.randomUUID)
            ? crypto.randomUUID()
            : 'sid-' + Date.now() + '-' + Math.random().toString(36).slice(2);
        localStorage.setItem('weedsim_sid', sid);
    }
    window.WEEDSIM_SID = sid;

    // Append the session id to a sprite URL (for <img src>, which can't send headers).
    window.withSid = function (url) {
        return url + (url.indexOf('?') >= 0 ? '&' : '?') + 'sid=' + encodeURIComponent(sid);
    };

    // Inject the header on all same-origin /api requests.
    const _fetch = window.fetch.bind(window);
    window.fetch = function (url, opts) {
        opts = opts || {};
        try {
            if (typeof url === 'string' && url.indexOf('/api') === 0) {
                const h = new Headers(opts.headers || {});
                h.set('X-WeedSim-Session', sid);
                opts.headers = h;
            }
        } catch (e) { /* never block a request over session wiring */ }
        return _fetch(url, opts);
    };
})();