8,037 Matching Annotations
  1. Jun 2023
    1. ```js FastMutex.prototype.runInLock = function (callback, opt_context) { this._setX()

      if (!this._isLockAvailable()) { this._retry(callback, opt_context) return }

      this._setY()

      if (this._getX() != this._clientId) { window.setTimeout(function () { if (this.hasLock()) this._execute(callback, opt_context) else this._retry(callback, opt_context) }.bind(this), Math.round(Math.random() * 100))

      } else { this._execute(callback, opt_context) } }

      FastMutex.prototype._execute = function (callback, opt_context) { var rv try { rv = callback.call(opt_context) } finally { if (rv instanceof goog.async.Deferred) { rv.addFinally(this._clearLock, this) } else { this._clearLock() } } } ```

    1. A Retry-After header might be included to this response indicating how long to wait before making a new request.

      http HTTP/1.1 429 Too Many Requests Content-Type: text/html Retry-After: 3600

    1. ```python def split_user(userid): """ Return the user and domain parts from the given user id as a dict.

      For example if userid is u'acct:seanh@hypothes.is' then return
      {'username': u'seanh', 'domain': u'hypothes.is'}'
      
      :raises InvalidUserId: if the given userid isn't a valid userid
      
      """
      match = re.match(r"^acct:([^@]+)@(.*)$", userid)
      if match:
          return {"username": match.groups()[0], "domain": match.groups()[1]}
      raise InvalidUserId(userid)
      

      ```

    1. ```html

      <body> <div> {% for chat in chats %} <div>{{ chat.contents }}</div> <button id={{chat.id}} ✅ onClick=getId(id) ✅ > print this chat_id out </button> {% endfor %} </div> ... <script> function getId(id){ console.log(id) } </script> </body>

      ```

    1. ```js const authChannel = new BroadcastChannel('authChannel');

      authChannel.addEventListener('message', () => { logout(); })

      export function logout() { // logout logic }

      logoutButton.addEventListener('click', () => { authChannel.postMessage('logout'); logout(); }); ```

      ```js import { render } from 'solid-js/web'; import { createSignal, For, onCleanup } from 'solid-js';

      const todosChannel = new BroadcastChannel('todos');

      function Todos() { const listener = todosChannel.addEventListener('message', e => { setTodos(e.data) });

      const [todos, setTodos] = createSignal(['One']);

      const addTodo = () => { setTodos(todos => [...todos, Math.random().toString()]); todosChannel.postMessage(todos()); }

      onCleanup(() => { todosChannel.removeEventListener('message', listener); })

      return ( <> <button onClick={addTodo}>Add Todo</button>

        <For each={todos()}>
          {(item) => <div>{item}</div>}
        </For>
      

      ) }

      render(() => <Todos />, document.getElementById('root')); ```

    1. ```js 'use strict';

      // --------------------------------------------------------------------

      class Cache extends Map { constructor(key) { super() this._key = key this.load() }

      set(k, v) { if (!this.has(k) || v !== this.get(k)) { super.set(k, v) this.save() } }

      delete(k) { if (super.has(k)) { super.delete(k) this.save() } }

      clear() { if (super.size() > 0) { super.clear() this.save() } }

      json() { let obj = Object.create(null)

      for (let k of this.keys()) {
        obj[k] = this.get(k)
      }
      
      return obj
      

      }

      save() { const data = this.json() this._save(this._key, data) this.dump({ data, event: 'SAVE' }) }

      load(s) { const data = this._load(this._key)

      if (typeof data !== 'object') {
        return
      }
      
      super.clear()
      
      for (let k of Object.keys(data)) {
        super.set(k, data[k])
      }
      
      this.dump({ data, event: 'LOAD' })
      

      }

      _save(key, data) {} _load(key) {}

      edit() { let res = window.prompt('Edit cached package URLs', JSON.stringify(this.json(), null, 2))

      if (res !== null) {
        try {
          const data = JSON.parse(res)
      
          super.clear()
      
          for (let k of Object.keys(data)) {
            super.set(k, data[k])
          }
      
          this.save()
        }
        catch (ex) {
          console.warn('Failed to update cache data: %s %o', ex.toString(), ex)
        }
      }
      

      }

      toString() { return ${this.constructor.name}<${this._key}>: keys=[ ${this.keys().sort().join(', ')} ] }

      dump({ data, event }) { console.group(${this.constructor.name}<${this._key}>: ${event || 'STATE'}:) console.info(JSON.stringify(data || this.json(), null, 2)) console.groupEnd() } }

      // --------------------------------------------------------------------

      class GMCache extends Cache { _save(key, data) { GM_setValue(key, JSON.stringify(data || {})) }

      _load(key) { return JSON.parse(GM_getValue(key) || '{}') } }

      // --------------------------------------------------------------------

      class StorageCache extends Cache { constructor(key, session) { super(key)

      this.storage = session ? window.sessionStorage : window.localStorage
      this.load()
      

      }

      _save(key, data) { this.storage.setItem(key, JSON.stringify(data || {})) }

      _load(key) { if (this.storage) { return JSON.parse(this.storage.getItem(key) || '{}') } } }

      // --------------------------------------------------------------------

      let c = new StorageCache('test-data') // c.set('jshint-summary', { name: 'jshint-summary', homepage: 'https://github.com/spiralx/jshint-summary' }) ```

    1. ```js /* * Response from cache / self.addEventListener('fetch', event => { const response = self.caches.open('example') .then(caches => caches.match(event.request)) .then(response => response || fetch(event.request));

      event.respondWith(response); });

      /* * Response to SSE by text / self.addEventListener('fetch', event => { const { headers } = event.request; const isSSERequest = headers.get('Accept') === 'text/event-stream';

      if (!isSSERequest) { return; }

      event.respondWith(new Response('Hello!')); });

      /* * Response to SSE by stream / self.addEventListener('fetch', event => { const { headers } = event.request; const isSSERequest = headers.get('Accept') === 'text/event-stream';

      if (!isSSERequest) { return; }

      const responseText = 'Hello!'; const responseData = Uint8Array.from(responseText, x => x.charCodeAt(0)); const stream = new ReadableStream({ start: controller => controller.enqueue(responseData) }); const response = new Response(stream);

      event.respondWith(response); });

      /* * SSE chunk data / const sseChunkData = (data, event, retry, id) => Object.entries({ event, id, data, retry }) .filter(([, value]) => ![undefined, null].includes(value)) .map(([key, value]) => ${key}: ${value}) .join('\n') + '\n\n';

      /* * Success response to SSE from SW / self.addEventListener('fetch', event => { const { headers } = event.request; const isSSERequest = headers.get('Accept') === 'text/event-stream';

      if (!isSSERequest) { return; }

      const sseChunkData = (data, event, retry, id) => Object.entries({ event, id, data, retry }) .filter(([, value]) => ![undefined, null].includes(value)) .map(([key, value]) => ${key}: ${value}) .join('\n') + '\n\n';

      const sseHeaders = { 'content-type': 'text/event-stream', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', };

      const responseText = sseChunkData('Hello!'); const responseData = Uint8Array.from(responseText, x => x.charCodeAt(0)); const stream = new ReadableStream({ start: controller => controller.enqueue(responseData) }); const response = new Response(stream, { headers: sseHeaders });

      event.respondWith(response); });

      /* * Result / self.addEventListener('fetch', event => { const { headers, url } = event.request; const isSSERequest = headers.get('Accept') === 'text/event-stream';

      // Process only SSE connections if (!isSSERequest) { return; }

      // Headers for SSE response const sseHeaders = { 'content-type': 'text/event-stream', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', }; // Function for formatting message to SSE response const sseChunkData = (data, event, retry, id) => Object.entries({ event, id, data, retry }) .filter(([, value]) => ![undefined, null].includes(value)) .map(([key, value]) => ${key}: ${value}) .join('\n') + '\n\n';

      // Map with server connections, where key - url, value - EventSource const serverConnections = {}; // For each request opens only one server connection and use it for next requests with the same url const getServerConnection = url => { if (!serverConnections[url]) { serverConnections[url] = new EventSource(url); }

      return serverConnections[url];
      

      }; // On message from server forward it to browser const onServerMessage = (controller, { data, type, retry, lastEventId }) => { const responseText = sseChunkData(data, type, retry, lastEventId); const responseData = Uint8Array.from(responseText, x => x.charCodeAt(0)); controller.enqueue(responseData); }; const stream = new ReadableStream({ start: controller => getServerConnection(url).onmessage = onServerMessage.bind(null, controller) }); const response = new Response(stream, { headers: sseHeaders });

      event.respondWith(response); }); ```

    1. ```js self.addEventListener('fetch', event => { const { headers, url } = event.request; const isSSERequest = headers.get('Accept') === 'text/event-stream';

      // We process only SSE connections if (!isSSERequest) { return; }

      // Response Headers for SSE const sseHeaders = { 'content-type': 'text/event-stream', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', }; // Function formatting data for SSE const sseChunkData = (data, event, retry, id) => Object.entries({ event, id, data, retry }) .filter(([, value]) => ![undefined, null].includes(value)) .map(([key, value]) => ${key}: ${value}) .join('\n') + '\n\n'; // Table with server connections, where key is url, value is EventSource const serverConnections = {}; // For each url, we open only one connection to the server and use it for subsequent requests const getServerConnection = url => { if (!serverConnections[url]) serverConnections[url] = new EventSource(url);

      return serverConnections[url];
      

      }; // When we receive a message from the server, we forward it to the browser const onServerMessage = (controller, { data, type, retry, lastEventId }) => { const responseText = sseChunkData(data, type, retry, lastEventId); const responseData = Uint8Array.from(responseText, x => x.charCodeAt(0)); controller.enqueue(responseData); }; const stream = new ReadableStream({ start: controller => getServerConnection(url).onmessage = onServerMessage.bind(null, controller) }); const response = new Response(stream, { headers: sseHeaders });

      event.respondWith(response); }); ```