├── .gitattributes ├── encoder.js ├── icon128.png ├── komple.js ├── lodashish.js ├── manifest.json ├── mod.js ├── popup.html ├── popup.js ├── readme.md ├── scrape.js ├── settings.js ├── ui.js ├── vocab.bpe.js ├── vue.js └── vue.min.js /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /icon128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vzakharov/komple/1843eff14eace5970b65b118483e30ac2b5c11b7/icon128.png -------------------------------------------------------------------------------- /komple.js: -------------------------------------------------------------------------------- 1 | // Komple: A chrome extension that displays an autocomplete suggestion in the currently active element, taking the suggestion from an external API. 2 | 3 | let logMode = '' 4 | 5 | const log = (mode, ...what) => ( 6 | mode.split(',').includes(logMode) && console.log(...what), 7 | what[what.length - 1] 8 | ) 9 | 10 | let autocompleteTimer = null 11 | let autocompleteInProgress = null 12 | let modifierPressed = null 13 | 14 | function isHotkey(keydownEvent, hotkeyName) { 15 | const { key, modifier } = settings.hotkeys[hotkeyName] 16 | // console.log(key, modifier, modifierPressed) 17 | return key === keydownEvent.key && modifierPressed === modifier 18 | } 19 | 20 | const modifierListener = ['keydown', e => { 21 | if ( ['Control', 'Alt', 'Shift', 'Meta'].includes(e.key) ) { 22 | // console.log('Modifier pressed:', e.key) 23 | modifierPressed = e.key 24 | } 25 | }] 26 | 27 | const clearModifierListener = ['keyup', e => { 28 | if ( ['Control', 'Alt', 'Shift', 'Meta'].includes(e.key) ) { 29 | // console.log('Modifier released:', modifierPressed) 30 | modifierPressed = null 31 | } 32 | }] 33 | 34 | // Clear modifier if the user navigates away from the tab 35 | document.addEventListener('visibilitychange', () => { 36 | if (document.visibilityState === 'hidden') { 37 | modifierPressed = null 38 | } 39 | }) 40 | 41 | const autocompleteListener = ( e ) => { 42 | // if the hotkey is pressed, autocomplete 43 | if ( e.key == settings.hotkeys.autocomplete.key && settings.hotkeys.autocomplete.modifier && modifierPressed === settings.hotkeys.autocomplete.modifier ) { 44 | autocomplete() 45 | } 46 | 47 | // if the activateOnHangingChar setting is on, autocomplete after a hanging character is typed 48 | else if ( settings.activateOnHangingChar ) { 49 | // if a hanging character is typed, start the autocomplete timer 50 | if ( e.key.match(/^[\[\(\{\s“,]$/) ) { 51 | autocompleteTimer = setTimeout( 52 | () => autocomplete(), 53 | 500) 54 | // console.log('Autocomplete timer started') 55 | // if a non-hanging character is typed, cancel the autocomplete timer 56 | } else { 57 | if ( autocompleteTimer || autocompleteInProgress ) 58 | cancelAutocomplete() 59 | } 60 | } 61 | } 62 | 63 | function cancelAutocomplete() { 64 | 65 | if ( autocompleteTimer || autocompleteInProgress ) { 66 | clearTimeout(autocompleteTimer), 67 | autocompleteTimer = null, 68 | autocompleteInProgress = null, 69 | document.getElementById('komple-thinking')?.remove() 70 | } 71 | 72 | } 73 | 74 | function toggleConfigModal() { 75 | let 76 | modal = document.getElementById('komple-config') 77 | 78 | if ( modal ) 79 | modal.style.display = modal.style.display === 'none' ? 'block' : 'none' 80 | else 81 | createConfigModal() 82 | } 83 | 84 | const pickerListener = ( e ) => { 85 | if ( isHotkey(e, 'apiPicker') ) { 86 | 87 | let apiPicker = document.getElementById('komple-api-picker') 88 | let configModal = document.getElementById('komple-config') 89 | let configVisible = configModal && configModal.style.display !== 'none' 90 | 91 | if ( apiPicker || configVisible ) { 92 | apiPicker?.remove() 93 | // console.log({ configVisible }) 94 | if ( configVisible ) 95 | configModal.style.display = 'none' 96 | } else { 97 | // If current element is not contenteditable or an input/textarea, return. 98 | let currentElement = getCurrentElement() 99 | if ( !currentElement.isContentEditable && !currentElement.matches('input, textarea') ) 100 | return 101 | 102 | apiPicker = createDivUnderCurrentElement({ id: 'komple-api-picker' }, div => { 103 | 104 | let index = 0 105 | 106 | // 'Choose an API' 107 | div.appendChild(document.createElement('div')).innerHTML = 'Choose an API' 108 | let { modifier } = settings.hotkeys.apiPicker 109 | 110 | const kbd = key => `${key}` 111 | 112 | for ( let api of settings.apis ) { 113 | 114 | index++ 115 | let apiDiv = document.createElement('div') 116 | apiDiv.innerHTML = `${kbd(index)} ${api.name}` 117 | apiDiv.className = 'komple-api-picker-item' 118 | apiDiv.style['font-weight'] = api === settings.api ? 'bold' : 'normal' 119 | apiDiv.style['margin-bottom'] = '5px' 120 | 121 | div.appendChild(apiDiv) 122 | } 123 | 124 | // Add listener for alt+numeric keys that will select the corresponding API 125 | let nextListener = ['keydown', event => { 126 | let { key } = event 127 | // console.log('Picker listener:', key) 128 | // If no API picker exists, delete the listener and return 129 | if ( !document.getElementById('komple-api-picker') ) 130 | return document.removeEventListener(...nextListener) 131 | 132 | if ( key.match(/^[1-9]$/) ) { 133 | settings.currentApiName = settings.apis[key - 1].name 134 | saveSettings() 135 | autocomplete() 136 | } 137 | 138 | if ( key === 'c' ) { 139 | navigator.clipboard.writeText(getPrompt().prompt) 140 | } 141 | 142 | removeApiPicker() 143 | event.preventDefault() 144 | }] 145 | 146 | let copyDiv = document.createElement('div') 147 | copyDiv.innerHTML = `${kbd('C')} Copy current prompt` 148 | div.appendChild(copyDiv) 149 | 150 | let keyupListener = ['keyup', e => { 151 | if ( e.key === modifier ) 152 | removeApiPicker() 153 | }] 154 | 155 | function removeApiPicker() { 156 | apiPicker.remove() 157 | document.removeEventListener(...nextListener) 158 | document.removeEventListener('click', removeApiPicker) 159 | document.removeEventListener(...keyupListener) 160 | } 161 | 162 | 163 | document.addEventListener(...nextListener) 164 | 165 | 166 | // Remove the API picker when the user clicks anywhere in the document 167 | document.addEventListener('click', removeApiPicker) 168 | document.addEventListener(...keyupListener) 169 | 170 | }) 171 | } 172 | } 173 | } 174 | 175 | const escapeListener = ({ key }) => { 176 | if ( key === 'Escape' ) { 177 | // Remove picker and modal, if either exists 178 | document.getElementById('komple-api-picker')?.remove() 179 | document.getElementById('komple-config')?.remove() 180 | } 181 | } 182 | 183 | function enable() { 184 | 185 | document.addEventListener('keydown', autocompleteListener) 186 | document.addEventListener('keydown', pickerListener) 187 | // cancel autocomplete on mouse click 188 | document.addEventListener('click', cancelAutocomplete) 189 | document.addEventListener('keydown', escapeListener) 190 | 191 | document.addEventListener(...modifierListener) 192 | document.addEventListener(...clearModifierListener) 193 | 194 | // Load extension config from chrome storage 195 | chrome.storage.sync.get('settings', data => { 196 | // console.log('Loaded config from chrome storage:', data.settings) 197 | if ( data.settings ) 198 | for ( let key in settings ) 199 | settings[key] = data.settings[key] 200 | // console.log('Loaded settings:', settings) 201 | }) 202 | 203 | // Listen to chrome storage to update settings 204 | chrome.storage.onChanged.addListener(event => { 205 | let { newValue } = event.settings 206 | Object.assign(settings, newValue) 207 | console.log('Settings changed:', settings) 208 | }) 209 | } 210 | 211 | function disable() { 212 | 213 | document.removeEventListener('keydown', autocompleteListener) 214 | document.removeEventListener('keydown', pickerListener) 215 | document.removeEventListener('click', cancelAutocomplete) 216 | document.removeEventListener('keydown', escapeListener) 217 | document.removeEventListener(...modifierListener) 218 | document.removeEventListener(...clearModifierListener) 219 | 220 | } 221 | 222 | // Recursively go through children of an element to the deepest child whose textContent ends with a double backslash. 223 | function deepestMatchingChild(element) { 224 | 225 | if ( element.textContent/*.includes('\\')*/ ) { 226 | // Scan children. If none, return the element. 227 | if ( !element.children.length ) 228 | return element 229 | // If there are children, recurse. 230 | else 231 | for ( let child of element.children ) { 232 | let result = deepestMatchingChild(child) 233 | if ( result ) 234 | return result 235 | } 236 | } 237 | 238 | } 239 | 240 | function getCurrentElement() { 241 | // If active element is a textarea or input, return that element 242 | if ( ['INPUT', 'TEXTAREA'].includes(document.activeElement.tagName) ) 243 | return document.activeElement 244 | 245 | let { parentElement } = document.getSelection()?.focusNode 246 | return parentElement 247 | } 248 | 249 | function createDivUnderCurrentElement(attributes, callback) { 250 | 251 | let div = document.createElement('div') 252 | Object.assign(div, attributes) 253 | 254 | div.style.position = 'fixed' 255 | div.style.color = 'rgba(0,0,0,0.7)' 256 | 257 | let currentElement = getCurrentElement() 258 | // console.log('currentElement:', currentElement) 259 | let { bottom, left } = currentElement.getBoundingClientRect() 260 | div.style.top = bottom + 'px' 261 | div.style.left = left + 'px' 262 | div.style.zIndex = '9999' 263 | div.style.backgroundColor = '#fff' 264 | div.style['border-radius'] = '5px' 265 | div.style.padding = '5px' 266 | div.style['font-family'] = 'sans-serif' 267 | div.style['font-size'] = '0.8em' 268 | 269 | // Cool shadow 270 | div.style.boxShadow = '0px 2px 5px -1px rgba(50, 50, 93, 0.25), 0px 1px 3px -1px rgba(0, 0, 0, 0.3) ' 271 | 272 | callback?.(div) 273 | 274 | document.body.appendChild(div) 275 | 276 | // console.log('Created div:', div) 277 | 278 | return div 279 | 280 | } 281 | 282 | async function autocomplete() { 283 | 284 | if ( autocompleteInProgress ) 285 | cancelAutocomplete() 286 | 287 | // Assign a random id to this autocomplete 288 | let id = Math.random().toString(36).substring(2, 15) 289 | autocompleteInProgress = id 290 | // console.log('Autocomplete started, id = ' + id) 291 | 292 | // // Get the deepest matching child. 293 | // let element = deepestMatchingChild(document.activeElement) 294 | let element = document.activeElement 295 | 296 | // console.log('Enclosing element:', element) 297 | 298 | if ( element ) { 299 | 300 | let { prompt, feeder, suffix } = getPrompt(element) 301 | prompt ||= '' 302 | 303 | try { 304 | startThinking( suffix ? 'Inserting' : 'Completing' ) 305 | let completion = await getSuggestion(prompt.trimRight(), { feeder, suffix }) 306 | if ( feeder ) completion = feeder + completion 307 | 308 | if ( autocompleteInProgress === id ) { 309 | // If the prompt's last character isn't alphanumeric, remove the leading space from the completion 310 | prompt.match(/\W$/) && completion.replace(/^\s+/, '') 311 | 312 | // // Remove any leading and trailing newlines 313 | // completion = completion.replace(/^\n+/, '').replace(/\n+$/, '') 314 | // 315 | // Replace any newlines (in any quantity) with a space, if settings.removeNewlines is true 316 | completion = completion.replace(/\n+/g, settings.removeNewlines ? ' ' : '\n') 317 | // 318 | // // Remove everything after and including the first newline 319 | // completion = completion.replace(/\n.*/g, '') 320 | 321 | console.log('Completion:', completion) 322 | 323 | simulateTextInput(completion) 324 | 325 | cancelAutocomplete() 326 | } 327 | 328 | } catch (e) { 329 | console.log('Error:', e) 330 | cancelAutocomplete() 331 | } 332 | 333 | } 334 | 335 | } 336 | 337 | function startThinking(action = 'Completing') { 338 | let thinking = document.getElementById('komple-thinking') 339 | 340 | thinking = createDivUnderCurrentElement({ 341 | id: 'komple-thinking', 342 | innerHTML: `${action} with ${settings.currentApiName}...` 343 | }) 344 | 345 | // Add another thinking emoji to the end of the thinking element every second 346 | let thinkingInterval = setInterval(() => { 347 | document.getElementById('komple-thinking') ? 348 | thinking.innerHTML += '.' 349 | : clearInterval(thinkingInterval) 350 | }, 1000) 351 | } 352 | 353 | function getPrompt(element = getCurrentElement()) { 354 | let builders = { 355 | 'twitter.com': getTwitterPrompt, 356 | 'reddit.com': { 357 | scraperVersion: 'v1', 358 | pieces: { 359 | author: { 360 | selector: '[data-click-id="user"]', 361 | last: true 362 | }, 363 | title: { 364 | selector: 'title' 365 | }, 366 | post: { 367 | selector: '[data-click-id="text"]', 368 | last: true 369 | }, 370 | comments: { 371 | many: true, 372 | crawl: true, 373 | stop: { 374 | // stop at the first comment in *this* thread, its padding-left is 16px 375 | style: { 376 | 'padding-left': '16px' 377 | } 378 | }, 379 | extract: { 380 | author: { 381 | test: { 382 | attributes: { 383 | 'data-testid': { 384 | value: 'comment_author_link' 385 | } 386 | } 387 | } 388 | }, 389 | comment: { 390 | test: { 391 | attributes: { 392 | 'data-testid': { 393 | value: 'comment' 394 | } 395 | } 396 | } 397 | } 398 | }, 399 | output: ` 400 | u/%author%: %comment% 401 | ` 402 | }, 403 | self: { 404 | // First element that is a descendant of an element with style="max-width:100%" 405 | selector: '[class="header-user-dropdown"] > button > span > span > span > span' 406 | } 407 | }, 408 | output: ` 409 | %title% 410 | Posted by %author% 411 | 412 | %post% 413 | 414 | Comments: 415 | %comments% 416 | u/%self%:` 417 | }, 418 | 'mail.google.com': { 419 | scraperVersion: 'v2', 420 | stop: { 421 | selector: 'h2' // Stop at conversation title 422 | }, 423 | whatIsScraped: 'conversation', 424 | whatIsInputed: 'user reply', 425 | }, 426 | 'quora.com': { 427 | scraperVersion: 'v2', 428 | whatIsScraped: 'question', 429 | whatIsInputed: 'insightful answer', 430 | instruction: 'Here is an insightful answer on Quora', 431 | } 432 | } 433 | 434 | let host = document.location.hostname.replace(/^(www\.)?/, '') 435 | let builder = builders[host] 436 | // console.log('Builder:', builder) 437 | let prompt, input, feeder, suffix 438 | if ( element.textContent ) { 439 | // Get the selection 440 | let selection = window.getSelection() 441 | // Get the caret position for the beginning and end of the selection 442 | let { 443 | anchorOffset, focusOffset, 444 | anchorNode, focusNode, 445 | } = selection 446 | // Split the selection before and after the caret, assigning the values to input and suffix, respectively 447 | input = anchorNode.textContent.slice(0, anchorOffset).trimEnd() 448 | suffix = focusNode.textContent.slice(focusOffset).trimStart() 449 | } else if ( element.tagName === 'TEXTAREA' || element.tagName === 'INPUT' ) { 450 | input = element.value.slice(0, element.selectionStart).trimEnd() 451 | suffix = element.value.slice(element.selectionEnd).trimStart() 452 | } else { 453 | feeder = input = builder?.feeder || '' 454 | } 455 | 456 | if ( suffix ) suffix = ' ' + suffix 457 | 458 | try { 459 | 460 | prompt = typeof builder === 'function' ? 461 | builder({ input, feeder, suffix }) 462 | : ( 463 | scrape[builder?.scraperVersion || 'default'](builder) 464 | ) 465 | 466 | // If it's an object, it will return { prompt, suffix }, which we need to reassign 467 | if ( typeof prompt === 'object' ) { 468 | ({ prompt, suffix } = prompt) 469 | suffix = suffix.trimRight() 470 | prompt = prompt.trim() 471 | } else { 472 | prompt += input 473 | } 474 | } catch (e) { 475 | console.log('Error:', e) 476 | ;( { prompt, suffix } = scrape.default() ) 477 | } 478 | 479 | process = text => { 480 | if (!text) return 481 | // Remove all {{...}} bits, unless the {{ is directly followed by "...". In that case, keep the ... bit. 482 | text = text.replace(/\{\{(\.\.\.)?[\s\S]*?\}\}/g, "$1") 483 | // Remove all bits within "/*-...*/" 484 | text = text.replace(/\/\*-[\s\S]+?\*\//g, '') 485 | // For all bits formatted as "/*!...*/", remove the enclosing "/*!" and "*/" and trim the inner text 486 | text = text.replace(/\/\*!\s*([\s\S]+?)\s*\*\//g, '$1') 487 | // Replace any number of newlines with 2 488 | text = text.replace(/\n+/g, '\n\n') 489 | text = text.trimRight() 490 | return text 491 | } 492 | 493 | // Remove everything in the prompt before and including '//start' 494 | prompt = prompt.split('\n//start').pop() 495 | 496 | // Remove everything in the suffix after and including '//stop' 497 | if ( suffix) suffix = suffix.split('\n//stop').shift() 498 | 499 | prompt = process(prompt) 500 | suffix = process(suffix) 501 | 502 | 503 | console.log('Prompt:', prompt) 504 | console.log('Suffix:', suffix) 505 | 506 | return { prompt, feeder, suffix } 507 | } 508 | 509 | function getTwitterPrompt({ input }) { 510 | 511 | // function to extract Twitter handle from href 512 | const getHandle = href => href.replace(/^.*?(\w+)$/, '@$1') 513 | 514 | // Find element with aria-label "Profile" and extract the Twitter handle from its href 515 | let myHandle = getHandle( document.querySelector('[aria-label="Profile"]').href ) 516 | 517 | // Find element with aria-label of Timeline: Conversation 518 | let conversation = document.querySelector('[aria-label="Timeline: Conversation"]') 519 | 520 | let output = `Here is a conversation with an insightful reply by ${myHandle}:\n\n` 521 | 522 | // Scan through all its decendants, adding items if it's an
element 523 | for ( let element of conversation.querySelectorAll('*') ) { 524 | 525 | // If it's the current active element, exit the loop 526 | if ( element === document.activeElement ) 527 | break 528 | 529 | // If it's an
element, add it to the list of messages 530 | if ( element.tagName === 'ARTICLE' ) { 531 | let handle = getHandle( element.querySelector('a[role="link"]').href ) 532 | let content = element.querySelector('[lang]')?.textContent || '[image]' 533 | 534 | output += `${handle}: ${content}\n\n` 535 | 536 | } 537 | 538 | } 539 | 540 | // Add my handle to the end of the list, plus any existing content of the active element 541 | output += `${myHandle}: ` 542 | 543 | return output 544 | 545 | } 546 | 547 | function getText(element, { property, replace } = {}) { 548 | if (!element) return '' 549 | 550 | let text = element[property || 'textContent'] 551 | if ( replace ) 552 | text = text.replace(new RegExp(replace[0], 'g'), replace[1]) 553 | 554 | return text 555 | } 556 | 557 | function testObject(object, test) { 558 | for ( let property in test ) { 559 | // If Object, recurse; otherwise, test the value 560 | let 561 | value = object?.[property], 562 | testValue = test[property], 563 | passed = 564 | ( typeof testValue === 'object' ) ? 565 | testObject(value, testValue) 566 | : value === testValue 567 | if ( !passed ) 568 | return false 569 | } 570 | return true 571 | } 572 | 573 | function setCaretPosition(element, position) { 574 | 575 | let range = document.createRange() 576 | let sel = window.getSelection() 577 | range.setStart(element.firstChild, position) 578 | range.collapse(true) 579 | sel.removeAllRanges() 580 | sel.addRange(range) 581 | 582 | } 583 | 584 | async function simulateTextInput(text) { 585 | 586 | document.execCommand('insertText', false, text) 587 | // // Split by newlines, exec insertText for each line, plus insertParagraph between each 588 | // let lines = text.split(/\n+/) 589 | // // console.log('Lines:', lines) 590 | // while ( lines.length ) { 591 | // document.execCommand('insertText', false, lines.shift()) 592 | // if ( lines.length ) 593 | // // document.insertHTML('
') 594 | // document.insertText(' / ') 595 | // } 596 | 597 | } 598 | let tokensByEndpoint = {} 599 | 600 | async function getSuggestion(prompt, { suffix }) { 601 | 602 | let { 603 | endpoint, auth, promptKey, otherBodyParams, arrayKey, resultKey, suffixKey 604 | } = settings.api 605 | 606 | // console.log({suffixKey, suffix}) 607 | // Get the suggestion from the external API. 608 | let json = await( 609 | await fetch( 610 | endpoint, 611 | { 612 | method: 'POST', 613 | headers: { 614 | 'Content-Type': 'application/json', 615 | 'Authorization': `${auth}` 616 | }, 617 | body: JSON.stringify({ 618 | [promptKey]: prompt, 619 | ...( suffixKey && suffix ) ? { [suffixKey]: suffix } : {}, 620 | ...otherBodyParams 621 | }) 622 | } 623 | ) 624 | ).json() 625 | 626 | let completion = get(arrayKey ? json[arrayKey][0] : json, resultKey) 627 | 628 | // Log token stats via encode(...).length 629 | console.log('Token stats:') 630 | console.log('Prompt:', encode(prompt).length) 631 | suffix && console.log('Suffix:', encode(suffix).length) 632 | console.log('Completion:', encode(completion).length) 633 | 634 | let totalTokens = [prompt, suffix, completion].map(encode).map(s => s.length).reduce((a, b) => a + b) 635 | 636 | console.log('Total tokens:', totalTokens) 637 | 638 | tokensByEndpoint[endpoint] = ( tokensByEndpoint[endpoint] || 0 ) + totalTokens 639 | 640 | console.log('Tokens by endpoint:', tokensByEndpoint) 641 | 642 | return completion 643 | 644 | } 645 | 646 | function saveSettings() { 647 | // Save to chrome storage 648 | chrome.storage.sync.set({ settings }, () => { 649 | // console.log('Saved config to chrome storage:', settings) 650 | }) 651 | } 652 | 653 | 654 | enable() -------------------------------------------------------------------------------- /lodashish.js: -------------------------------------------------------------------------------- 1 | // Various lodash-like functions 2 | 3 | // Get value by path in an object 4 | function get(obj, path) { 5 | return path.split('.').reduce((acc, part) => acc && acc[part], obj) 6 | } 7 | 8 | // Set value by path in an object 9 | function set(obj, path, value) { 10 | const parts = path.split('.') 11 | const last = parts.pop() 12 | const parent = parts.reduce((acc, part) => acc && acc[part], obj) 13 | parent[last] = value 14 | } 15 | 16 | // Escape regex characters in a string 17 | function escapeRegExp(str) { 18 | return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') 19 | } -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Komple", 3 | "description": "Autocomplete with large language models on (almost) any web page", 4 | "version": "0.1", 5 | "icons": { 6 | "128": "icon128.png" 7 | }, 8 | "permissions": [ 9 | "tabs","","webRequest","storage" 10 | ], 11 | "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'", 12 | "content_scripts": [ 13 | { 14 | "matches": [ 15 | "http://*/*", 16 | "https://*/*" 17 | ], 18 | "js": [ 19 | "encoder.js", "vocab.bpe.js", "mod.js", 20 | "lodashish.js", "settings.js", "scrape.js", "ui.js", "komple.js" 21 | ], 22 | "run_at": "document_end" 23 | } 24 | ], 25 | "browser_action": { 26 | "default_popup": "popup.html", 27 | "default_icon": "icon128.png" 28 | }, 29 | "manifest_version": 2 30 | } -------------------------------------------------------------------------------- /mod.js: -------------------------------------------------------------------------------- 1 | const range = (x, y) => { 2 | const res = Array.from(Array(y).keys()).slice(x) 3 | return res 4 | } 5 | 6 | const ord = x => { 7 | return x.charCodeAt(0) 8 | } 9 | 10 | const chr = x => { 11 | return String.fromCharCode(x) 12 | } 13 | 14 | const textEncoder = new TextEncoder("utf-8") 15 | const encodeStr = str => { 16 | return Array.from(textEncoder.encode(str)).map(x => x.toString()) 17 | } 18 | 19 | const textDecoder = new TextDecoder("utf-8") 20 | const decodeStr = arr => { 21 | return textDecoder.decode(new Uint8Array(arr)); 22 | } 23 | 24 | const dictZip = (x, y) => { 25 | const result = {} 26 | x.map((_, i) => { result[x[i]] = y[i] }) 27 | return result 28 | } 29 | 30 | function bytes_to_unicode() { 31 | const bs = range(ord('!'), ord('~') + 1).concat(range(ord('¡'), ord('¬') + 1), range(ord('®'), ord('ÿ') + 1)) 32 | 33 | let cs = bs.slice() 34 | let n = 0 35 | for (let b = 0; b < 2 ** 8; b++) { 36 | if (!bs.includes(b)) { 37 | bs.push(b) 38 | cs.push(2 ** 8 + n) 39 | n = n + 1 40 | } 41 | } 42 | 43 | cs = cs.map(x => chr(x)) 44 | 45 | const result = {} 46 | bs.map((_, i) => { result[bs[i]] = cs[i] }) 47 | return result 48 | } 49 | 50 | function get_pairs(word) { 51 | const pairs = new Set() 52 | let prev_char = word[0] 53 | for (let i = 1; i < word.length; i++) { 54 | const char = word[i] 55 | pairs.add([prev_char, char]) 56 | prev_char = char 57 | } 58 | return pairs 59 | } 60 | 61 | const pat = /'s|'t|'re|'ve|'m|'l l|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu 62 | 63 | const decoder = {} 64 | Object.keys(encoder).map(x => { decoder[encoder[x]] = x }) 65 | 66 | const lines = bpe_file.split('\n') 67 | 68 | // bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split("\n")[1:-1]] 69 | const bpe_merges = lines.slice(1, lines.length - 1).map(x => { 70 | return x.split(/(\s+)/).filter(function(e) { return e.trim().length > 0 }) 71 | }) 72 | 73 | const byte_encoder = bytes_to_unicode() 74 | const byte_decoder = {} 75 | Object.keys(byte_encoder).map(x => { byte_decoder[byte_encoder[x]] = x }) 76 | 77 | const bpe_ranks = dictZip(bpe_merges, range(0, bpe_merges.length)) 78 | const cache = {} 79 | 80 | function bpe(token) { 81 | if (token in cache) { 82 | return cache[token] 83 | } 84 | 85 | let word = token.split('') 86 | 87 | let pairs = get_pairs(word) 88 | 89 | if (!pairs) { 90 | return token 91 | } 92 | 93 | while (true) { 94 | const minPairs = {} 95 | Array.from(pairs).map(pair => { 96 | const rank = bpe_ranks[pair] 97 | minPairs[(isNaN(rank) ? 10e10 : rank)] = pair 98 | }) 99 | 100 | 101 | 102 | const bigram = minPairs[Math.min(...Object.keys(minPairs).map(x => { 103 | return parseInt(x) 104 | } 105 | ))] 106 | 107 | if (!(bigram in bpe_ranks)) { 108 | break 109 | } 110 | 111 | const first = bigram[0] 112 | const second = bigram[1] 113 | let new_word = [] 114 | let i = 0 115 | 116 | while (i < word.length) { 117 | const j = word.indexOf(first, i) 118 | if (j === -1) { 119 | new_word = new_word.concat(word.slice(i)) 120 | break 121 | } 122 | new_word = new_word.concat(word.slice(i, j)) 123 | i = j 124 | 125 | if (word[i] === first && i < word.length - 1 && word[i + 1] === second) { 126 | new_word.push(first + second) 127 | i = i + 2 128 | } else { 129 | new_word.push(word[i]) 130 | i = i + 1 131 | } 132 | } 133 | 134 | word = new_word 135 | if (word.length === 1) { 136 | break 137 | } else { 138 | pairs = get_pairs(word) 139 | } 140 | } 141 | 142 | word = word.join(' ') 143 | cache[token] = word 144 | 145 | return word 146 | } 147 | 148 | function encode(text) { 149 | if ( !text ) 150 | return [] 151 | let bpe_tokens = [] 152 | const matches = Array.from(text.matchAll(pat)).map(x => x[0]) 153 | for (let token of matches) { 154 | token = encodeStr(token).map(x => { 155 | return byte_encoder[x] 156 | }).join('') 157 | 158 | const new_tokens = bpe(token).split(' ').map(x => encoder[x]) 159 | bpe_tokens = bpe_tokens.concat(new_tokens) 160 | } 161 | return bpe_tokens 162 | } 163 | 164 | function decode(tokens) { 165 | let text = tokens.map(x => decoder[x]).join('') 166 | text = decodeStr(text.split('').map(x => byte_decoder[x])) 167 | return text 168 | } -------------------------------------------------------------------------------- /popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Komple settings 7 | 8 | 9 | 10 | 11 | 12 | 32 | 33 | 34 | 35 |
39 | 430 |
431 | 432 | 433 | 434 | -------------------------------------------------------------------------------- /popup.js: -------------------------------------------------------------------------------- 1 | new Vue({ 2 | el: '#app', 3 | 4 | data() { 5 | return { 6 | settings: {}, 7 | vm: this, 8 | window, 9 | console, 10 | apiTemplates, 11 | settingsLoaded: false, 12 | } 13 | }, 14 | 15 | mounted() { 16 | chrome.storage.sync.get('settings', ({ settings }) => { 17 | console.log('Settings:', settings) 18 | this.settings = settings || {} 19 | // If the settings don't have at least one of the keys of defaultSettings, set them to the default 20 | for ( let key in defaultSettings || {} ) 21 | if ( !this.settings[key] || key == 'apis' && !this.settings[key].length ) 22 | this.$set(this.settings, key, defaultSettings[key]) 23 | 24 | window.settings = this.settings 25 | this.settingsLoaded = true 26 | }) 27 | Object.assign(window, { 28 | chrome, 29 | vm: this, 30 | }) 31 | setTimeout(() => { 32 | document.getElementById('api-list')?.focus() 33 | }, 0) 34 | }, 35 | 36 | computed: { 37 | 38 | activeTab() { 39 | // window.alert(`activeTab: ${this.settings.activeTab}`) 40 | return this.settings.activeTab || 'api' 41 | }, 42 | 43 | subTab() { 44 | return this.settings.subTab || 'general' 45 | }, 46 | 47 | allRequiredApiSettingsSet() { 48 | return [ 'endpoint', 'auth', 'promptKey', 'resultKey' ].every(key => this.api[key]) 49 | }, 50 | 51 | hideAllButBody() { 52 | // Check if all required api settings are set. If yes, return settings.hideAllButBody 53 | if ( 54 | this.settings.hideAllButBody && 55 | this.allRequiredApiSettingsSet 56 | ) 57 | return true 58 | else 59 | return false 60 | }, 61 | 62 | api: { 63 | get() { 64 | console.log('Getting API') 65 | console.log(this.settings) 66 | return this.settings?.apis?.find(api => api.name === this.settings.currentApiName) || this.settings.apis?.[0] 67 | }, 68 | set(api) { 69 | this.settings.currentApiName = api.name 70 | } 71 | }, 72 | 73 | stringifiedApiParams: { 74 | get() { 75 | return JSON.stringify(this.api.otherBodyParams, null, 2) 76 | }, 77 | set(text) { 78 | try { 79 | this.api.otherBodyParams = JSON.parse(text) 80 | } catch (e) { 81 | this.$bvToast.toast('Invalid JSON', { 82 | title: 'Error', 83 | variant: 'danger', 84 | solid: true 85 | }) 86 | } 87 | } 88 | }, 89 | 90 | }, 91 | 92 | watch: { 93 | 94 | settings: { 95 | handler(settings) { 96 | // Store in chrome.storage.sync and send to all tabs' content scripts 97 | chrome.storage.sync.set({ settings }) 98 | chrome.tabs.query({}, tabs => { 99 | tabs.forEach(tab => { 100 | chrome.tabs.sendMessage(tab.id, { settings }) 101 | }) 102 | }) 103 | console.log('Settings updated:', settings) 104 | }, 105 | deep: true, 106 | }, 107 | 108 | 'api.auth'(auth) { 109 | // If auth doesn't start with a "Bearer" or "Basic" or "JWT", add it after confirming 110 | if ( 111 | auth && !auth.match(/^(Bearer|Basic|JWT) /) && 112 | confirm(`Seems like you entered just the API key, not the entire auth header.\n\nDo you want to set to 'Bearer ${auth}'?`) 113 | ) 114 | this.api.auth = `Bearer ${auth}` 115 | } 116 | }, 117 | 118 | methods: { 119 | 120 | currentApiIndex() { 121 | return this.settings?.apis?.indexOf(this.api) 122 | }, 123 | 124 | changeApiName(name) { 125 | this.api.name = name 126 | this.settings.currentApiName = name 127 | }, 128 | 129 | nudge(direction) { 130 | // Reorder the APIs array, moving the current API either up or down depending on the direction (1 or -1) 131 | let { settings: { apis }, api } = this 132 | let currentApiIndex = apis.indexOf(api) 133 | let newIndex = currentApiIndex + direction 134 | if ( newIndex >= 0 && newIndex < apis.length ) { 135 | apis.splice(currentApiIndex, 1) 136 | apis.splice(newIndex, 0, api) 137 | this.api = api 138 | } 139 | }, 140 | 141 | pickName(baseName) { 142 | // If there's already an API with that name, add a number to the name until there's no conflict 143 | let name = baseName 144 | for ( let i = 2; this.settings.apis.find(api => api.name === name); i++ ) { 145 | name = `${baseName} (${i})` 146 | } 147 | return name 148 | }, 149 | 150 | addApi() { 151 | // Add a new API to the list 152 | let newApiName = this.pickName('New API') 153 | 154 | this.settings.apis = [...this.settings.apis, 155 | { 156 | ...JSON.parse(JSON.stringify(defaultApi)), 157 | name: newApiName, 158 | empty: true, 159 | } 160 | ] 161 | 162 | this.api = this.settings.apis[this.settings.apis.length - 1] 163 | 164 | }, 165 | 166 | deleteApi({ doNotPrompt } = {}) { 167 | // Prompt first if doNotPrompt is not set 168 | if ( !doNotPrompt && !confirm(`Are you sure you want to delete the API "${this.api.name}"? There is no undo!`) ) 169 | return 170 | // Delete the current API 171 | let { settings: { apis }, api } = this 172 | let currentApiIndex = apis.indexOf(api) 173 | apis.splice(currentApiIndex, 1) 174 | // If none left, create a new one 175 | if ( apis.length === 0 ) 176 | this.addApi() 177 | this.api = apis[currentApiIndex - 1] || apis[0] 178 | }, 179 | 180 | cloneApi() { 181 | // Clone the current API 182 | let { settings: { apis }, api } = this 183 | let currentApiIndex = apis.indexOf(api) 184 | let newApi = JSON.parse(JSON.stringify(api)) 185 | newApi.name = this.pickName(newApi.name) 186 | for ( let i = 2; this.settings.apis.find(api => api.name === newApi.name); i++ ) { 187 | newApi.name = `${api.name} (copy ${i})` 188 | } 189 | apis.splice(currentApiIndex + 1, 0, newApi) 190 | this.api = apis[currentApiIndex + 1] 191 | }, 192 | 193 | downloadSettings() { 194 | // Download the settings as a JSON file 195 | let data = JSON.stringify(this.settings, null, 2) 196 | let blob = new Blob([data], { type: 'application/json' }) 197 | let link = document.createElement('a') 198 | link.id = 'download-settings' 199 | link.href = URL.createObjectURL(blob) 200 | link.download = 'settings.json' 201 | link.click() 202 | 203 | // Clean up 204 | setTimeout(() => { 205 | document.getElementById('download-settings').remove() 206 | }, 0) 207 | 208 | }, 209 | 210 | resetSettings() { 211 | // Prompt first 212 | if ( !confirm(`Are you sure you want to reset all settings? There is no undo!`) ) 213 | return 214 | 215 | // Reset the settings 216 | this.settings = JSON.parse(JSON.stringify(defaultSettings)) 217 | this.api = this.settings.apis[0] 218 | 219 | } 220 | 221 | } 222 | 223 | }) 224 | 225 | console.log('popup.js loaded') -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | Chrome extension that displays an autocomplete suggestion in the currently active element, taking the suggestion from an external API. 2 | 3 | - [Load unpacked](https://stackoverflow.com/questions/24577024/install-chrome-extension-form-outside-the-chrome-web-store) (for now) 4 | - Press `Alt+K` (`Cmd+K` on a Mac) to [configure endpoint, api key](https://gyazo.com/28debc2dee5d767cecfd0b6585ba6bca),and other settings if you want. 5 | - You can add as many endpoints as you want, with different parameters such as temperature, number of tokens, etc., according to the specific API’s requirements. 6 | - While typing, press `Ctrl+Space` to generate the autocomplete suggestion. Undo using standard keyboard shortcuts. 7 | - If you press `Alt+K` while in a text field, a [helper popover](https://gyazo.com/61a6bf6e98c50f337fe94c8cac4789b7) will appear, where you can quickly switch between different endpoints using keyboard shortcuts, open the configuration modal, or copy the prompt that is used behind the scenes to clipboard. 8 | 9 | It’s work in progress, so don’t expect it to work perfectly. 10 | -------------------------------------------------------------------------------- /scrape.js: -------------------------------------------------------------------------------- 1 | const scrape = { 2 | 3 | v1(crawlRules) { 4 | 5 | let finalOutput = crawlRules.output 6 | 7 | for ( let key in crawlRules.pieces ) { 8 | let piece = crawlRules.pieces[key] 9 | let { selector, last, property, many, crawl, stop, extract, replace, output } = piece 10 | 11 | let text = '' 12 | 13 | if ( !crawl ) { 14 | 15 | let elements = document.querySelectorAll(selector) 16 | let element = last ? elements[elements.length - 1] : elements[0] 17 | text = getText(element, piece) 18 | 19 | } else { 20 | 21 | let items = many && [{}] 22 | let item = items?.[0] || {} 23 | 24 | let element = getCurrentElement() 25 | 26 | while ( true ) { 27 | 28 | // Go to previous sibling 29 | let { previousElementSibling, parentElement } = element 30 | 31 | if ( previousElementSibling ) { 32 | element = previousElementSibling 33 | // Go to the deepest last descendant of the element 34 | while ( element.lastElementChild ) { 35 | element = element.lastElementChild 36 | } 37 | } else // Go to parent 38 | element = parentElement 39 | 40 | // If we've reached the stop element or the top of the document, stop 41 | if ( testObject(element, stop) || !element ) 42 | break 43 | 44 | // Check if the element matches any of the test attributes 45 | for ( let key in extract ) { 46 | 47 | if ( testObject(element, extract[key].test) ) 48 | item[key] = getText(element, extract[key]) 49 | 50 | } 51 | 52 | // If all extract selectors have been found: if many, add a new item to the array, else break out 53 | if ( Object.keys(item).length === Object.keys(extract).length ) { 54 | if ( many ) 55 | items.push(item = {}) 56 | else 57 | break 58 | } 59 | 60 | } 61 | 62 | // Reverse items 63 | items = items.reverse() 64 | 65 | // If the first item is incomplete, remove it 66 | if ( Object.keys(items[0]).length !== Object.keys(extract).length ) 67 | items.shift() 68 | 69 | // Convert items to text 70 | text = ( 71 | many ? items : [ item ] 72 | ).map(item => { 73 | let text = output 74 | for ( let key in item ) { 75 | text = text.replace(`%${key}%`, item[key]) 76 | } 77 | return text 78 | }).join('') 79 | 80 | } 81 | 82 | finalOutput = finalOutput.replace(`%${key}%`, text) 83 | } 84 | 85 | // console.log(finalOutput) 86 | 87 | return finalOutput 88 | }, 89 | 90 | v2({ 91 | stop = { selector: 'body'}, 92 | whatIsScraped = 'text', 93 | whatIsInputed = 'user input predicted' , 94 | instruction = 'Predict user input based on scraped text' 95 | } = {} ) { 96 | let 97 | node = getCurrentElement(), 98 | text = '', 99 | lastAddedNode = null 100 | 101 | const isStopElement = element => element.matches?.(stop.selector) || element == document.body 102 | 103 | while ( true ) { 104 | 105 | log('full', 'starting node', node) 106 | 107 | // Go to previous sibling 108 | let { previousSibling, parentElement } = node 109 | 110 | if ( previousSibling ) { 111 | 112 | node = previousSibling 113 | log('full', 'previous sibling', node) 114 | 115 | // Go to the deepest last descendant of the node 116 | while ( node.lastChild ) { 117 | log('full', 'descendant', node.lastChild) 118 | node = node.lastChild 119 | } 120 | 121 | // Add the node's textContent to the text with a new line, at the beginning. Skip if there's no text, if the parent element is not visible, or if it' a comment. 122 | if ( 123 | node.nodeName === 'BR' || 124 | node.textContent 125 | && node.parentElement.offsetParent 126 | && node.nodeType !== Node.COMMENT_NODE 127 | ) { 128 | log('full,mid', 'adding text', node.textContent, node.offsetTop) 129 | 130 | // Let's see if we need to add a new line. 131 | let 132 | { parentElement } = node, 133 | lastParentElement = lastAddedNode?.parentElement 134 | 135 | let addNewLine = parentElement.offsetTop + parentElement.offsetHeight <= lastParentElement?.offsetTop 136 | log('full,mid', 'add new line', addNewLine, parentElement, lastParentElement) 137 | text = node.textContent + ( addNewLine ? '\n' : ' ' ) + text 138 | lastAddedNode = node 139 | } 140 | 141 | } else { 142 | // Go to parent 143 | node = parentElement 144 | log('full', 'parent', node) 145 | } 146 | 147 | // If we've reached the stop element or the body, stop 148 | if ( isStopElement(node) || node === document.body ) { 149 | log('full', 'stopping', node) 150 | break 151 | } 152 | 153 | } 154 | 155 | text = `${instruction}.\n\n== ${whatIsScraped} from ${window.location.href} ==\n\n${text}` 156 | // Trim text and replace any more than 2 consecutive new lines with a double new line. 157 | text = text.trim().replace(/(\n\s*){2,}/g, '\n\n') 158 | 159 | text = `${text}\n\n== ${whatIsInputed} based on the ${whatIsScraped} above ==\n\n` 160 | 161 | log('full', 'text', text) 162 | return text 163 | 164 | }, 165 | 166 | v3(up) { 167 | 168 | let element = document.activeElement 169 | 170 | if ( element.tagName === 'TEXTAREA' || element.tagName === 'INPUT' ) { 171 | let prompt = element.value.slice(0, element.selectionStart).trimEnd() 172 | let suffix = element.value.slice(element.selectionEnd).trimStart() 173 | return { prompt, suffix } 174 | } 175 | 176 | let 177 | selection = getSelection(), 178 | node = selection.anchorNode, 179 | text = up ? 180 | node.textContent.substring(0, selection.anchorOffset) : 181 | node.textContent.substring(selection.focusOffset) 182 | 183 | // console.log({ selection, element: node, up }) 184 | 185 | if ( typeof up !== 'undefined' ) { 186 | 187 | const sibling = element => element[`${up ? 'previous' : 'next'}Sibling`] 188 | const addTextFromNode = node => { 189 | let newLineIfNeeded = [ 'BR', 'P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ].includes(node.nodeName) ? '\n' : '' 190 | text = 191 | up ? 192 | `${newLineIfNeeded}${node.textContent}${text}` : 193 | `${text}${newLineIfNeeded}${node.textContent}` 194 | } 195 | 196 | outerLoop: while (true) { 197 | 198 | while (sibling(node)) { 199 | 200 | node = sibling(node) 201 | 202 | // If the element is a text node or contenteditable or a descendant of one, insert its textContent in the beginning of the text. 203 | if ( node.nodeType === Node.TEXT_NODE || node.matches?.('[contenteditable="true"], [contenteditable="true"] *') ) { 204 | // console.log(element, element.textContent) 205 | addTextFromNode(node) 206 | } 207 | 208 | 209 | // If it is not, but any of its descendants are, add the first descendant's textContent to the text. 210 | else { 211 | let editableDescendant = node.querySelector('[contenteditable="true"]') 212 | if (editableDescendant) { 213 | addTextFromNode(editableDescendant) 214 | } else { 215 | // If no descendants are contenteditable, stop the outer loop. 216 | break outerLoop 217 | } 218 | } 219 | 220 | } 221 | 222 | // Go to the deepest parent that has a previous sibling 223 | while (!sibling(node)) { 224 | node = node.parentElement 225 | if (!node) 226 | break outerLoop 227 | } 228 | 229 | } 230 | 231 | return text 232 | } else { 233 | 234 | let [ prompt, suffix ] = [ 1, 0 ].map(scrape.v3) 235 | return { prompt, suffix } 236 | 237 | } 238 | 239 | } 240 | 241 | } 242 | 243 | scrape.default = scrape.v3 -------------------------------------------------------------------------------- /settings.js: -------------------------------------------------------------------------------- 1 | // Extension settings 2 | 3 | const defaultApi = { 4 | name: 'Default API', // Arbitrary name for the API 5 | // endpoint: 'https://...', // The endpoint to use for autocompletion 6 | // auth: 'Bearer ...', // The authorization token to use for the API. Don't forget to add the Bearer prefix! 7 | // censor: false, // Whether to hide the above fields in the configuration modal 8 | // promptKey: 'prompt', // The key to use for the prompt in the API request body 9 | // suffixKey: 'suffix', // The key to use for the suffix. Leave empty if the model doesn't support it. 10 | // otherBodyParams: { // Other parameters to add to the request body (number of tokens, temperature, etc.) 11 | // max_tokens: 50, 12 | // temperature: 0.6, 13 | // stop: '\n' 14 | // }, 15 | // arrayKey: 'choices', // Where is the array of suggestions in the response? Empty if no array is returned. 16 | // resultKey: 'text' // Where is the result text in the response? 17 | empty: true, // Whether the API is empty. If true, templates will be suggested. 18 | } 19 | 20 | const settings = { 21 | 22 | // APIs: the endpoints you will use to get autocompletion suggestions. You can use as many by adding more objects to the array. 23 | // You will be also able to modify the settings via a configuration modal. 24 | apis: [ defaultApi ], 25 | 26 | currentApiName: 'Default API', // The name of the current API to use 27 | 28 | hotkeys: { // Hotkeys to use for the extension 29 | 30 | autocomplete: { // Hotkey to manually trigger autocompletion 31 | key: ' ', 32 | modifier: 'Control' 33 | }, 34 | 35 | apiPicker: { // Hotkey that shows a small div with all the APIs to choose from (via hotkeys) 36 | key: 'k', 37 | modifier: 'Alt' 38 | } 39 | 40 | }, 41 | 42 | activateOnHangingChar: false, // If true, autocomplete will be triggered whenever there's a hanging space after a word, 43 | // after waiting for 0.5 seconds. Note that this can result in higher spend of API tokens: 44 | // Even if you cancel the autocomplete after the timer lapses, the API will still be called. 45 | 46 | activeTab: 'api', // The tab to show when opening the extension popup 47 | subTab: 'general', // The subtab to show when opening the extension popup (where applicable) 48 | removeNewlines: false, // If true, newlines will be removed from the result text 49 | } 50 | 51 | const defaultSettings = JSON.parse(JSON.stringify(settings)) 52 | 53 | const apiTemplates = [ 54 | { name: 'GPT-3', settings: { 55 | endpoint: "https://api.openai.com/v1/engines/text-davinci-002/completions", 56 | promptKey: "prompt", 57 | arrayKey: "choices", 58 | resultKey: "text", 59 | suffixKey: "suffix", 60 | otherBodyParams: { 61 | frequency_penalty: 1, 62 | max_tokens: 50, 63 | n: 1, 64 | presence_penalty: 1, 65 | temperature: 0.6 66 | }, 67 | } }, 68 | { name: 'AI21', settings: { 69 | endpoint: "https://api.ai21.com/studio/v1/j1-jumbo/complete", 70 | promptKey: "prompt", 71 | resultKey: "data.text", 72 | otherBodyParams: { 73 | maxTokens: 50, 74 | numResults: 1, 75 | temperature: 0.6 76 | } 77 | } }, 78 | { name: 'Cohere', settings: { 79 | endpoint: "https://api.cohere.ai/large/generate", 80 | promptKey: "prompt", 81 | arrayKey: "generations", 82 | resultKey: "text", 83 | otherBodyParams: { 84 | max_tokens: 50, 85 | temperature: 0.6 86 | } 87 | } }, 88 | { name: 'Custom', settings: { 89 | } } 90 | ] 91 | 92 | // Getter for the current API -- do not modify 93 | Object.defineProperty(settings, 'api', { 94 | get: () => settings.apis.find(api => api.name === settings.currentApiName) || settings.apis[0] 95 | }) -------------------------------------------------------------------------------- /ui.js: -------------------------------------------------------------------------------- 1 | function addStyleToButton(button) { 2 | button.style.cssText = 'border: 1px solid #ccc; border-radius: 4px; padding: 5px 10px; margin-right: 5px; margin-bottom: 5px;' 3 | button.onmouseover = () => button.style.backgroundColor = '#eee' 4 | button.onmouseout = () => button.style.backgroundColor = '#fff' 5 | } 6 | 7 | function createConfigModal() { 8 | // Creates and displays a modal dialog to configure the completion API. 9 | let modalBackground = document.createElement('div') 10 | modalBackground.id = 'komple-config' 11 | modalBackground.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 9999; display: none;' 12 | 13 | // Clicking on the background sets display to none. 14 | modalBackground.addEventListener('click', ({ target }) => { 15 | target === modalBackground && ( modalBackground.style.display = 'none' ) 16 | }) 17 | 18 | let modal = document.createElement('div') 19 | // Center-align the modal vertically and horizontally. 20 | modal.style.cssText = 'position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: white; border-radius: 10px; z-index: 100000; padding: 20px; font-family: sans-serif;' 21 | modalBackground.appendChild(modal) 22 | 23 | 24 | let modalContent = document.createElement('div') 25 | modalContent.classList.add('komple-config-content') 26 | modal.appendChild(modalContent) 27 | 28 | let modalHeader = document.createElement('div') 29 | modalHeader.classList.add('komple-config-header') 30 | modalContent.appendChild(modalHeader) 31 | 32 | let modalTitle = document.createElement('h2') 33 | modalTitle.textContent = 'Configure completion API' 34 | modalHeader.appendChild(modalTitle) 35 | 36 | 37 | // Create a button to copy settings to the clipboard. 38 | let copyButton = document.createElement('button') 39 | copyButton.textContent = 'Copy settings to clipboard' 40 | copyButton.onclick = () => { 41 | navigator.clipboard.writeText(JSON.stringify(settings, null, 2)) 42 | let oldText = copyButton.textContent 43 | copyButton.textContent = 'Copied!' 44 | setTimeout(() => copyButton.textContent = oldText, 1000) 45 | } 46 | addStyleToButton(copyButton) 47 | modalHeader.appendChild(copyButton) 48 | 49 | // Create a button to input settings from a window.prompt. 50 | let inputButton = document.createElement('button') 51 | inputButton.textContent = 'Input settings' 52 | inputButton.onclick = () => { 53 | let input = window.prompt('Paste settings (JSON) here:') 54 | try { 55 | Object.assign(settings, JSON.parse(input)) 56 | saveSettings() 57 | createOptions() 58 | createInputs() 59 | inputButton.textContent = 'Input successful!' 60 | setTimeout(() => inputButton.textContent = 'Input settings', 1000) 61 | } catch (e) { 62 | console.error(e) 63 | inputButton.textContent = 'Input failed!' 64 | setTimeout(() => inputButton.textContent = 'Input settings', 1000) 65 | } 66 | } 67 | addStyleToButton(inputButton) 68 | modalHeader.appendChild(inputButton) 69 | 70 | let modalBody = document.createElement('div') 71 | modalBody.classList.add('komple-config-body') 72 | modalContent.appendChild(modalBody) 73 | 74 | 75 | // Create a dropdown to select the api in settings.apis 76 | let endpointSelect = document.createElement('select') 77 | endpointSelect.id = 'komple-select-api' 78 | endpointSelect.style.cssText = 'width: 100%;' 79 | modalBody.appendChild(endpointSelect) 80 | 81 | function createOptions() { 82 | // Delete any existing options 83 | endpointSelect.innerHTML = '' 84 | 85 | for ( let api of settings.apis ) { 86 | let option = document.createElement('option') 87 | option.id = `komple-option-${api.name}` 88 | option.textContent = api.name 89 | option.selected = api == settings.api 90 | endpointSelect.appendChild(option) 91 | } 92 | 93 | } 94 | 95 | createOptions() 96 | 97 | 98 | // If the user changes the selected API, update the settings.currentApiName and rerun the createInputs function. 99 | endpointSelect.addEventListener('change', ({ target }) => { 100 | settings.currentApiName = target.options[target.selectedIndex].textContent 101 | createInputs() 102 | }) 103 | 104 | // Add an empty span to anchor the inputs to. 105 | let inputsAnchor = document.createElement('span') 106 | modalBody.appendChild(inputsAnchor) 107 | 108 | function createInputs() { 109 | // First, delete the inputs table if it exists. 110 | document.getElementById('komple-inputs-table')?.remove() 111 | 112 | let inputsTable = document.createElement('table') 113 | inputsTable.id = 'komple-inputs-table' 114 | 115 | // Append the table to the anchor 116 | inputsAnchor.appendChild(inputsTable) 117 | 118 | let inputs = {} 119 | let { api } = settings 120 | for ( let key of [ 121 | 'name', 'endpoint', 'auth', 'censor', 'promptKey', 'suffixKey', 'otherBodyParams', 'arrayKey', 'resultKey' 122 | ] ) { 123 | 124 | let multiline = ['otherBodyParams'].includes(key) 125 | 126 | let input = document.createElement( 127 | multiline ? 'textarea' : 'input' 128 | ) 129 | 130 | // If text area, set number of rows to the number of lines in the value. 131 | multiline && ( input.rows = JSON.stringify(api[key], null, 2).split('\n').length ) 132 | 133 | !multiline && ( 134 | input.type = 135 | ['endpoint', 'auth'].includes(key) ? 136 | api.censor ? 'password' : 'text' 137 | : ['censor'].includes(key) ? 138 | 'checkbox' 139 | : 'text' 140 | ) 141 | 142 | let valueKey = input.type === 'checkbox' ? 'checked' : 'value' 143 | input[valueKey] = key === 'otherBodyParams' ? JSON.stringify(api[key], null, 2) : api[key] 144 | 145 | let tr = document.createElement('tr') 146 | inputsTable.appendChild(tr) 147 | 148 | let labelTd = document.createElement('td') 149 | labelTd.textContent = { 150 | name: 'Name', 151 | endpoint: 'Endpoint', 152 | auth: 'Authorization header', 153 | promptKey: 'Prompt key', 154 | suffixKey: 'Suffix key', 155 | arrayKey: 'Array key', 156 | resultKey: 'Result key', 157 | otherBodyParams: 'Other body params', 158 | censor: 'Censor endpoint \& key' 159 | }[key] 160 | 161 | let inputTd = document.createElement('td') 162 | inputTd.appendChild(input) 163 | 164 | tr.appendChild(labelTd) 165 | tr.appendChild(inputTd) 166 | 167 | let notes = { 168 | name: 'Any name you want to use for this API.', 169 | suffixKey: 'Leave empty if not supported.', 170 | arrayKey: 'Leave empty if no array returned.', 171 | auth: 'Include "Bearer", if applicable.', 172 | } 173 | 174 | for ( let noteKey in notes ) 175 | if ( noteKey === key ) { 176 | let note = document.createElement('div') 177 | note.style.cssText = 'font-size: 0.8em; color: #888; margin-bottom: 5px;' 178 | note.textContent = notes[noteKey] 179 | labelTd.appendChild(note) 180 | } 181 | 182 | input.addEventListener('change', () => { 183 | if ( ['otherBodyParams'].includes(key) ) { 184 | try { 185 | api[key] = JSON.parse(input.value) 186 | } catch (e) { 187 | alert('Invalid JSON; reverting to previous value.') 188 | input.value = JSON.stringify(api[key], null, 2) 189 | return 190 | } 191 | } else { 192 | 193 | key === 'censor' && ( 194 | ['endpoint', 'auth'].forEach(key => { 195 | inputs[key].type = input.checked ? 'password' : 'text' 196 | }) 197 | ) 198 | 199 | if ( key === 'name' ) { 200 | 201 | // Convert to lowercase and replace any non-alphanumeric characters with a dash. Update the input. 202 | input.value = input.value.toLowerCase().replace(/[^a-z0-9]+/gi, '-') 203 | 204 | if ( api !== settings.api ) { 205 | if ( settings.apis.find(({ name }) => name === input.value) ) { 206 | alert('Name already taken; reverting to previous value.') 207 | input.value = api.name 208 | return 209 | } 210 | } else { 211 | settings.currentApiName = input.value 212 | } 213 | 214 | // Change the respective option in the dropdown. 215 | let option = document.getElementById(`komple-option-${api.name}`) 216 | option.textContent = input.value 217 | option.id = `komple-option-${input.value}` 218 | 219 | } 220 | 221 | api[key] = input[valueKey] 222 | 223 | } 224 | 225 | saveSettings() 226 | }) 227 | 228 | inputs[key] = input 229 | 230 | } 231 | 232 | } 233 | 234 | createInputs() 235 | 236 | let modalFooter = document.createElement('div') 237 | modalFooter.classList.add('komple-config-footer') 238 | modalContent.appendChild(modalFooter) 239 | 240 | 241 | let buttonDiv = document.createElement('div') 242 | buttonDiv.classList.add('komple-config-buttons') 243 | // Align right with margins and paddings as needed 244 | buttonDiv.style.cssText = 'display: flex; justify-content: flex-end; margin-top: 10px; margin-bottom: 10px;' 245 | 246 | let buttonActions = ({ 247 | Clone() { 248 | 249 | let newApi = { 250 | ...JSON.parse(JSON.stringify(settings.api)), 251 | otherBodyParams: JSON.parse(JSON.stringify(settings.api.otherBodyParams)), 252 | name: `${settings.api.name}-clone` 253 | } 254 | 255 | settings.apis.push(newApi) 256 | settings.currentApiName = newApi.name 257 | 258 | }, 259 | Delete() { 260 | 261 | if ( settings.apis.length === 1 ) { 262 | alert('You must have at least one API.') 263 | return 264 | } 265 | 266 | settings.apis = settings.apis.filter(({ name }) => name !== settings.currentApiName) 267 | settings.currentApiName = settings.apis[settings.apis.length - 1].name 268 | 269 | }, 270 | Nudge() { 271 | // Move up 272 | let index = settings.apis.findIndex(({ name }) => name === settings.currentApiName) 273 | if ( index === 0 ) return 274 | let previousIndex = index - 1 275 | let previousApi = settings.apis[previousIndex] 276 | settings.apis[previousIndex] = settings.apis[index] 277 | settings.apis[index] = previousApi 278 | 279 | } 280 | }) 281 | 282 | for ( let caption in buttonActions ) { 283 | let action = buttonActions[caption] 284 | let button = document.createElement('button') 285 | button.textContent = caption 286 | button.id = `komple-config-button-${caption.toLowerCase()}` 287 | button.addEventListener('click', () => { 288 | action() 289 | createOptions() 290 | createInputs() 291 | saveSettings() 292 | }) 293 | addStyleToButton(button) 294 | buttonDiv.appendChild(button) 295 | } 296 | 297 | modalFooter.appendChild(buttonDiv) 298 | 299 | // Add a 'buy me a beer' link on the right 300 | let buyMeABeer = document.createElement('a') 301 | buyMeABeer.href = 'https://vzakharov.github.io/buy-me-a-beer' 302 | buyMeABeer.target = '_blank' 303 | buyMeABeer.textContent = 'Buy me a 🍺' 304 | buyMeABeer.style.cssText = 'margin-top: 10px; text-decoration: none; color: #888; float: right;' 305 | modalFooter.appendChild(buyMeABeer) 306 | 307 | document.body.appendChild(modalBackground) 308 | 309 | return modalBackground 310 | } -------------------------------------------------------------------------------- /vue.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Vue.js v2.6.14 3 | * (c) 2014-2021 Evan You 4 | * Released under the MIT License. 5 | */ 6 | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).Vue=t()}(this,function(){"use strict";var e=Object.freeze({});function t(e){return null==e}function n(e){return null!=e}function r(e){return!0===e}function i(e){return"string"==typeof e||"number"==typeof e||"symbol"==typeof e||"boolean"==typeof e}function o(e){return null!==e&&"object"==typeof e}var a=Object.prototype.toString;function s(e){return"[object Object]"===a.call(e)}function c(e){var t=parseFloat(String(e));return t>=0&&Math.floor(t)===t&&isFinite(e)}function u(e){return n(e)&&"function"==typeof e.then&&"function"==typeof e.catch}function l(e){return null==e?"":Array.isArray(e)||s(e)&&e.toString===a?JSON.stringify(e,null,2):String(e)}function f(e){var t=parseFloat(e);return isNaN(t)?e:t}function p(e,t){for(var n=Object.create(null),r=e.split(","),i=0;i-1)return e.splice(n,1)}}var m=Object.prototype.hasOwnProperty;function y(e,t){return m.call(e,t)}function g(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}}var _=/-(\w)/g,b=g(function(e){return e.replace(_,function(e,t){return t?t.toUpperCase():""})}),$=g(function(e){return e.charAt(0).toUpperCase()+e.slice(1)}),w=/\B([A-Z])/g,C=g(function(e){return e.replace(w,"-$1").toLowerCase()});var x=Function.prototype.bind?function(e,t){return e.bind(t)}:function(e,t){function n(n){var r=arguments.length;return r?r>1?e.apply(t,arguments):e.call(t,n):e.call(t)}return n._length=e.length,n};function k(e,t){t=t||0;for(var n=e.length-t,r=new Array(n);n--;)r[n]=e[n+t];return r}function A(e,t){for(var n in t)e[n]=t[n];return e}function O(e){for(var t={},n=0;n0,Z=J&&J.indexOf("edge/")>0,G=(J&&J.indexOf("android"),J&&/iphone|ipad|ipod|ios/.test(J)||"ios"===K),X=(J&&/chrome\/\d+/.test(J),J&&/phantomjs/.test(J),J&&J.match(/firefox\/(\d+)/)),Y={}.watch,Q=!1;if(V)try{var ee={};Object.defineProperty(ee,"passive",{get:function(){Q=!0}}),window.addEventListener("test-passive",null,ee)}catch(e){}var te=function(){return void 0===B&&(B=!V&&!z&&"undefined"!=typeof global&&(global.process&&"server"===global.process.env.VUE_ENV)),B},ne=V&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__;function re(e){return"function"==typeof e&&/native code/.test(e.toString())}var ie,oe="undefined"!=typeof Symbol&&re(Symbol)&&"undefined"!=typeof Reflect&&re(Reflect.ownKeys);ie="undefined"!=typeof Set&&re(Set)?Set:function(){function e(){this.set=Object.create(null)}return e.prototype.has=function(e){return!0===this.set[e]},e.prototype.add=function(e){this.set[e]=!0},e.prototype.clear=function(){this.set=Object.create(null)},e}();var ae=S,se=0,ce=function(){this.id=se++,this.subs=[]};ce.prototype.addSub=function(e){this.subs.push(e)},ce.prototype.removeSub=function(e){h(this.subs,e)},ce.prototype.depend=function(){ce.target&&ce.target.addDep(this)},ce.prototype.notify=function(){for(var e=this.subs.slice(),t=0,n=e.length;t-1)if(o&&!y(i,"default"))a=!1;else if(""===a||a===C(e)){var c=Re(String,i.type);(c<0||s0&&(ct((u=e(u,(a||"")+"_"+c))[0])&&ct(f)&&(s[l]=he(f.text+u[0].text),u.shift()),s.push.apply(s,u)):i(u)?ct(f)?s[l]=he(f.text+u):""!==u&&s.push(he(u)):ct(u)&&ct(f)?s[l]=he(f.text+u.text):(r(o._isVList)&&n(u.tag)&&t(u.key)&&n(a)&&(u.key="__vlist"+a+"_"+c+"__"),s.push(u)));return s}(e):void 0}function ct(e){return n(e)&&n(e.text)&&!1===e.isComment}function ut(e,t){if(e){for(var n=Object.create(null),r=oe?Reflect.ownKeys(e):Object.keys(e),i=0;i0,a=t?!!t.$stable:!o,s=t&&t.$key;if(t){if(t._normalized)return t._normalized;if(a&&r&&r!==e&&s===r.$key&&!o&&!r.$hasNormal)return r;for(var c in i={},t)t[c]&&"$"!==c[0]&&(i[c]=vt(n,c,t[c]))}else i={};for(var u in n)u in i||(i[u]=ht(n,u));return t&&Object.isExtensible(t)&&(t._normalized=i),R(i,"$stable",a),R(i,"$key",s),R(i,"$hasNormal",o),i}function vt(e,t,n){var r=function(){var e=arguments.length?n.apply(null,arguments):n({}),t=(e=e&&"object"==typeof e&&!Array.isArray(e)?[e]:st(e))&&e[0];return e&&(!t||1===e.length&&t.isComment&&!pt(t))?void 0:e};return n.proxy&&Object.defineProperty(e,t,{get:r,enumerable:!0,configurable:!0}),r}function ht(e,t){return function(){return e[t]}}function mt(e,t){var r,i,a,s,c;if(Array.isArray(e)||"string"==typeof e)for(r=new Array(e.length),i=0,a=e.length;idocument.createEvent("Event").timeStamp&&(cn=function(){return un.now()})}function ln(){var e,t;for(sn=cn(),on=!0,en.sort(function(e,t){return e.id-t.id}),an=0;anan&&en[n].id>e.id;)n--;en.splice(n+1,0,e)}else en.push(e);rn||(rn=!0,Qe(ln))}}(this)},pn.prototype.run=function(){if(this.active){var e=this.get();if(e!==this.value||o(e)||this.deep){var t=this.value;if(this.value=e,this.user){var n='callback for watcher "'+this.expression+'"';Be(this.cb,this.vm,[e,t],this.vm,n)}else this.cb.call(this.vm,e,t)}}},pn.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},pn.prototype.depend=function(){for(var e=this.deps.length;e--;)this.deps[e].depend()},pn.prototype.teardown=function(){if(this.active){this.vm._isBeingDestroyed||h(this.vm._watchers,this);for(var e=this.deps.length;e--;)this.deps[e].removeSub(this);this.active=!1}};var dn={enumerable:!0,configurable:!0,get:S,set:S};function vn(e,t,n){dn.get=function(){return this[t][n]},dn.set=function(e){this[t][n]=e},Object.defineProperty(e,n,dn)}function hn(e){e._watchers=[];var t=e.$options;t.props&&function(e,t){var n=e.$options.propsData||{},r=e._props={},i=e.$options._propKeys=[];e.$parent&&$e(!1);var o=function(o){i.push(o);var a=Ie(o,t,n,e);xe(r,o,a),o in e||vn(e,"_props",o)};for(var a in t)o(a);$e(!0)}(e,t.props),t.methods&&function(e,t){e.$options.props;for(var n in t)e[n]="function"!=typeof t[n]?S:x(t[n],e)}(e,t.methods),t.data?function(e){var t=e.$options.data;s(t=e._data="function"==typeof t?function(e,t){le();try{return e.call(t,t)}catch(e){return He(e,t,"data()"),{}}finally{fe()}}(t,e):t||{})||(t={});var n=Object.keys(t),r=e.$options.props,i=(e.$options.methods,n.length);for(;i--;){var o=n[i];r&&y(r,o)||(a=void 0,36!==(a=(o+"").charCodeAt(0))&&95!==a&&vn(e,"_data",o))}var a;Ce(t,!0)}(e):Ce(e._data={},!0),t.computed&&function(e,t){var n=e._computedWatchers=Object.create(null),r=te();for(var i in t){var o=t[i],a="function"==typeof o?o:o.get;r||(n[i]=new pn(e,a||S,S,mn)),i in e||yn(e,i,o)}}(e,t.computed),t.watch&&t.watch!==Y&&function(e,t){for(var n in t){var r=t[n];if(Array.isArray(r))for(var i=0;i-1:"string"==typeof e?e.split(",").indexOf(t)>-1:(n=e,"[object RegExp]"===a.call(n)&&e.test(t));var n}function On(e,t){var n=e.cache,r=e.keys,i=e._vnode;for(var o in n){var a=n[o];if(a){var s=a.name;s&&!t(s)&&Sn(n,o,r,i)}}}function Sn(e,t,n,r){var i=e[t];!i||r&&i.tag===r.tag||i.componentInstance.$destroy(),e[t]=null,h(n,t)}!function(t){t.prototype._init=function(t){var n=this;n._uid=$n++,n._isVue=!0,t&&t._isComponent?function(e,t){var n=e.$options=Object.create(e.constructor.options),r=t._parentVnode;n.parent=t.parent,n._parentVnode=r;var i=r.componentOptions;n.propsData=i.propsData,n._parentListeners=i.listeners,n._renderChildren=i.children,n._componentTag=i.tag,t.render&&(n.render=t.render,n.staticRenderFns=t.staticRenderFns)}(n,t):n.$options=De(wn(n.constructor),t||{},n),n._renderProxy=n,n._self=n,function(e){var t=e.$options,n=t.parent;if(n&&!t.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(e)}e.$parent=n,e.$root=n?n.$root:e,e.$children=[],e.$refs={},e._watcher=null,e._inactive=null,e._directInactive=!1,e._isMounted=!1,e._isDestroyed=!1,e._isBeingDestroyed=!1}(n),function(e){e._events=Object.create(null),e._hasHookEvent=!1;var t=e.$options._parentListeners;t&&Wt(e,t)}(n),function(t){t._vnode=null,t._staticTrees=null;var n=t.$options,r=t.$vnode=n._parentVnode,i=r&&r.context;t.$slots=lt(n._renderChildren,i),t.$scopedSlots=e,t._c=function(e,n,r,i){return Ht(t,e,n,r,i,!1)},t.$createElement=function(e,n,r,i){return Ht(t,e,n,r,i,!0)};var o=r&&r.data;xe(t,"$attrs",o&&o.attrs||e,null,!0),xe(t,"$listeners",n._parentListeners||e,null,!0)}(n),Qt(n,"beforeCreate"),function(e){var t=ut(e.$options.inject,e);t&&($e(!1),Object.keys(t).forEach(function(n){xe(e,n,t[n])}),$e(!0))}(n),hn(n),function(e){var t=e.$options.provide;t&&(e._provided="function"==typeof t?t.call(e):t)}(n),Qt(n,"created"),n.$options.el&&n.$mount(n.$options.el)}}(Cn),function(e){var t={get:function(){return this._data}},n={get:function(){return this._props}};Object.defineProperty(e.prototype,"$data",t),Object.defineProperty(e.prototype,"$props",n),e.prototype.$set=ke,e.prototype.$delete=Ae,e.prototype.$watch=function(e,t,n){if(s(t))return bn(this,e,t,n);(n=n||{}).user=!0;var r=new pn(this,e,t,n);if(n.immediate){var i='callback for immediate watcher "'+r.expression+'"';le(),Be(t,this,[r.value],this,i),fe()}return function(){r.teardown()}}}(Cn),function(e){var t=/^hook:/;e.prototype.$on=function(e,n){var r=this;if(Array.isArray(e))for(var i=0,o=e.length;i1?k(t):t;for(var n=k(arguments,1),r='event handler for "'+e+'"',i=0,o=t.length;iparseInt(this.max)&&Sn(e,t[0],t,this._vnode),this.vnodeToCache=null}}},created:function(){this.cache=Object.create(null),this.keys=[]},destroyed:function(){for(var e in this.cache)Sn(this.cache,e,this.keys)},mounted:function(){var e=this;this.cacheVNode(),this.$watch("include",function(t){On(e,function(e){return An(t,e)})}),this.$watch("exclude",function(t){On(e,function(e){return!An(t,e)})})},updated:function(){this.cacheVNode()},render:function(){var e=this.$slots.default,t=zt(e),n=t&&t.componentOptions;if(n){var r=kn(n),i=this.include,o=this.exclude;if(i&&(!r||!An(i,r))||o&&r&&An(o,r))return t;var a=this.cache,s=this.keys,c=null==t.key?n.Ctor.cid+(n.tag?"::"+n.tag:""):t.key;a[c]?(t.componentInstance=a[c].componentInstance,h(s,c),s.push(c)):(this.vnodeToCache=t,this.keyToCache=c),t.data.keepAlive=!0}return t||e&&e[0]}}};!function(e){var t={get:function(){return F}};Object.defineProperty(e,"config",t),e.util={warn:ae,extend:A,mergeOptions:De,defineReactive:xe},e.set=ke,e.delete=Ae,e.nextTick=Qe,e.observable=function(e){return Ce(e),e},e.options=Object.create(null),I.forEach(function(t){e.options[t+"s"]=Object.create(null)}),e.options._base=e,A(e.options.components,Nn),function(e){e.use=function(e){var t=this._installedPlugins||(this._installedPlugins=[]);if(t.indexOf(e)>-1)return this;var n=k(arguments,1);return n.unshift(this),"function"==typeof e.install?e.install.apply(e,n):"function"==typeof e&&e.apply(null,n),t.push(e),this}}(e),function(e){e.mixin=function(e){return this.options=De(this.options,e),this}}(e),xn(e),function(e){I.forEach(function(t){e[t]=function(e,n){return n?("component"===t&&s(n)&&(n.name=n.name||e,n=this.options._base.extend(n)),"directive"===t&&"function"==typeof n&&(n={bind:n,update:n}),this.options[t+"s"][e]=n,n):this.options[t+"s"][e]}})}(e)}(Cn),Object.defineProperty(Cn.prototype,"$isServer",{get:te}),Object.defineProperty(Cn.prototype,"$ssrContext",{get:function(){return this.$vnode&&this.$vnode.ssrContext}}),Object.defineProperty(Cn,"FunctionalRenderContext",{value:Et}),Cn.version="2.6.14";var En=p("style,class"),jn=p("input,textarea,option,select,progress"),Dn=function(e,t,n){return"value"===n&&jn(e)&&"button"!==t||"selected"===n&&"option"===e||"checked"===n&&"input"===e||"muted"===n&&"video"===e},Ln=p("contenteditable,draggable,spellcheck"),In=p("events,caret,typing,plaintext-only"),Mn=function(e,t){return Bn(t)||"false"===t?"false":"contenteditable"===e&&In(t)?t:"true"},Fn=p("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,truespeed,typemustmatch,visible"),Pn="http://www.w3.org/1999/xlink",Rn=function(e){return":"===e.charAt(5)&&"xlink"===e.slice(0,5)},Hn=function(e){return Rn(e)?e.slice(6,e.length):""},Bn=function(e){return null==e||!1===e};function Un(e){for(var t=e.data,r=e,i=e;n(i.componentInstance);)(i=i.componentInstance._vnode)&&i.data&&(t=Vn(i.data,t));for(;n(r=r.parent);)r&&r.data&&(t=Vn(t,r.data));return function(e,t){if(n(e)||n(t))return zn(e,Kn(t));return""}(t.staticClass,t.class)}function Vn(e,t){return{staticClass:zn(e.staticClass,t.staticClass),class:n(e.class)?[e.class,t.class]:t.class}}function zn(e,t){return e?t?e+" "+t:e:t||""}function Kn(e){return Array.isArray(e)?function(e){for(var t,r="",i=0,o=e.length;i-1?mr(e,t,n):Fn(t)?Bn(n)?e.removeAttribute(t):(n="allowfullscreen"===t&&"EMBED"===e.tagName?"true":t,e.setAttribute(t,n)):Ln(t)?e.setAttribute(t,Mn(t,n)):Rn(t)?Bn(n)?e.removeAttributeNS(Pn,Hn(t)):e.setAttributeNS(Pn,t,n):mr(e,t,n)}function mr(e,t,n){if(Bn(n))e.removeAttribute(t);else{if(q&&!W&&"TEXTAREA"===e.tagName&&"placeholder"===t&&""!==n&&!e.__ieph){var r=function(t){t.stopImmediatePropagation(),e.removeEventListener("input",r)};e.addEventListener("input",r),e.__ieph=!0}e.setAttribute(t,n)}}var yr={create:vr,update:vr};function gr(e,r){var i=r.elm,o=r.data,a=e.data;if(!(t(o.staticClass)&&t(o.class)&&(t(a)||t(a.staticClass)&&t(a.class)))){var s=Un(r),c=i._transitionClasses;n(c)&&(s=zn(s,Kn(c))),s!==i._prevClass&&(i.setAttribute("class",s),i._prevClass=s)}}var _r,br,$r,wr,Cr,xr,kr={create:gr,update:gr},Ar=/[\w).+\-_$\]]/;function Or(e){var t,n,r,i,o,a=!1,s=!1,c=!1,u=!1,l=0,f=0,p=0,d=0;for(r=0;r=0&&" "===(h=e.charAt(v));v--);h&&Ar.test(h)||(u=!0)}}else void 0===i?(d=r+1,i=e.slice(0,r).trim()):m();function m(){(o||(o=[])).push(e.slice(d,r).trim()),d=r+1}if(void 0===i?i=e.slice(0,r).trim():0!==d&&m(),o)for(r=0;r-1?{exp:e.slice(0,wr),key:'"'+e.slice(wr+1)+'"'}:{exp:e,key:null};br=e,wr=Cr=xr=0;for(;!zr();)Kr($r=Vr())?qr($r):91===$r&&Jr($r);return{exp:e.slice(0,Cr),key:e.slice(Cr+1,xr)}}(e);return null===n.key?e+"="+t:"$set("+n.exp+", "+n.key+", "+t+")"}function Vr(){return br.charCodeAt(++wr)}function zr(){return wr>=_r}function Kr(e){return 34===e||39===e}function Jr(e){var t=1;for(Cr=wr;!zr();)if(Kr(e=Vr()))qr(e);else if(91===e&&t++,93===e&&t--,0===t){xr=wr;break}}function qr(e){for(var t=e;!zr()&&(e=Vr())!==t;);}var Wr,Zr="__r",Gr="__c";function Xr(e,t,n){var r=Wr;return function i(){null!==t.apply(null,arguments)&&ei(e,i,n,r)}}var Yr=Ke&&!(X&&Number(X[1])<=53);function Qr(e,t,n,r){if(Yr){var i=sn,o=t;t=o._wrapper=function(e){if(e.target===e.currentTarget||e.timeStamp>=i||e.timeStamp<=0||e.target.ownerDocument!==document)return o.apply(this,arguments)}}Wr.addEventListener(e,t,Q?{capture:n,passive:r}:n)}function ei(e,t,n,r){(r||Wr).removeEventListener(e,t._wrapper||t,n)}function ti(e,r){if(!t(e.data.on)||!t(r.data.on)){var i=r.data.on||{},o=e.data.on||{};Wr=r.elm,function(e){if(n(e[Zr])){var t=q?"change":"input";e[t]=[].concat(e[Zr],e[t]||[]),delete e[Zr]}n(e[Gr])&&(e.change=[].concat(e[Gr],e.change||[]),delete e[Gr])}(i),it(i,o,Qr,ei,Xr,r.context),Wr=void 0}}var ni,ri={create:ti,update:ti};function ii(e,r){if(!t(e.data.domProps)||!t(r.data.domProps)){var i,o,a=r.elm,s=e.data.domProps||{},c=r.data.domProps||{};for(i in n(c.__ob__)&&(c=r.data.domProps=A({},c)),s)i in c||(a[i]="");for(i in c){if(o=c[i],"textContent"===i||"innerHTML"===i){if(r.children&&(r.children.length=0),o===s[i])continue;1===a.childNodes.length&&a.removeChild(a.childNodes[0])}if("value"===i&&"PROGRESS"!==a.tagName){a._value=o;var u=t(o)?"":String(o);oi(a,u)&&(a.value=u)}else if("innerHTML"===i&&Wn(a.tagName)&&t(a.innerHTML)){(ni=ni||document.createElement("div")).innerHTML=""+o+"";for(var l=ni.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;l.firstChild;)a.appendChild(l.firstChild)}else if(o!==s[i])try{a[i]=o}catch(e){}}}}function oi(e,t){return!e.composing&&("OPTION"===e.tagName||function(e,t){var n=!0;try{n=document.activeElement!==e}catch(e){}return n&&e.value!==t}(e,t)||function(e,t){var r=e.value,i=e._vModifiers;if(n(i)){if(i.number)return f(r)!==f(t);if(i.trim)return r.trim()!==t.trim()}return r!==t}(e,t))}var ai={create:ii,update:ii},si=g(function(e){var t={},n=/:(.+)/;return e.split(/;(?![^(]*\))/g).forEach(function(e){if(e){var r=e.split(n);r.length>1&&(t[r[0].trim()]=r[1].trim())}}),t});function ci(e){var t=ui(e.style);return e.staticStyle?A(e.staticStyle,t):t}function ui(e){return Array.isArray(e)?O(e):"string"==typeof e?si(e):e}var li,fi=/^--/,pi=/\s*!important$/,di=function(e,t,n){if(fi.test(t))e.style.setProperty(t,n);else if(pi.test(n))e.style.setProperty(C(t),n.replace(pi,""),"important");else{var r=hi(t);if(Array.isArray(n))for(var i=0,o=n.length;i-1?t.split(gi).forEach(function(t){return e.classList.add(t)}):e.classList.add(t);else{var n=" "+(e.getAttribute("class")||"")+" ";n.indexOf(" "+t+" ")<0&&e.setAttribute("class",(n+t).trim())}}function bi(e,t){if(t&&(t=t.trim()))if(e.classList)t.indexOf(" ")>-1?t.split(gi).forEach(function(t){return e.classList.remove(t)}):e.classList.remove(t),e.classList.length||e.removeAttribute("class");else{for(var n=" "+(e.getAttribute("class")||"")+" ",r=" "+t+" ";n.indexOf(r)>=0;)n=n.replace(r," ");(n=n.trim())?e.setAttribute("class",n):e.removeAttribute("class")}}function $i(e){if(e){if("object"==typeof e){var t={};return!1!==e.css&&A(t,wi(e.name||"v")),A(t,e),t}return"string"==typeof e?wi(e):void 0}}var wi=g(function(e){return{enterClass:e+"-enter",enterToClass:e+"-enter-to",enterActiveClass:e+"-enter-active",leaveClass:e+"-leave",leaveToClass:e+"-leave-to",leaveActiveClass:e+"-leave-active"}}),Ci=V&&!W,xi="transition",ki="animation",Ai="transition",Oi="transitionend",Si="animation",Ti="animationend";Ci&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(Ai="WebkitTransition",Oi="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(Si="WebkitAnimation",Ti="webkitAnimationEnd"));var Ni=V?window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout:function(e){return e()};function Ei(e){Ni(function(){Ni(e)})}function ji(e,t){var n=e._transitionClasses||(e._transitionClasses=[]);n.indexOf(t)<0&&(n.push(t),_i(e,t))}function Di(e,t){e._transitionClasses&&h(e._transitionClasses,t),bi(e,t)}function Li(e,t,n){var r=Mi(e,t),i=r.type,o=r.timeout,a=r.propCount;if(!i)return n();var s=i===xi?Oi:Ti,c=0,u=function(){e.removeEventListener(s,l),n()},l=function(t){t.target===e&&++c>=a&&u()};setTimeout(function(){c0&&(n=xi,l=a,f=o.length):t===ki?u>0&&(n=ki,l=u,f=c.length):f=(n=(l=Math.max(a,u))>0?a>u?xi:ki:null)?n===xi?o.length:c.length:0,{type:n,timeout:l,propCount:f,hasTransform:n===xi&&Ii.test(r[Ai+"Property"])}}function Fi(e,t){for(;e.length1}function Vi(e,t){!0!==t.data.show&&Ri(t)}var zi=function(e){var o,a,s={},c=e.modules,u=e.nodeOps;for(o=0;ov?_(e,t(i[y+1])?null:i[y+1].elm,i,d,y,o):d>y&&$(r,p,v)}(p,h,y,o,l):n(y)?(n(e.text)&&u.setTextContent(p,""),_(p,null,y,0,y.length-1,o)):n(h)?$(h,0,h.length-1):n(e.text)&&u.setTextContent(p,""):e.text!==i.text&&u.setTextContent(p,i.text),n(v)&&n(d=v.hook)&&n(d=d.postpatch)&&d(e,i)}}}function k(e,t,i){if(r(i)&&n(e.parent))e.parent.data.pendingInsert=t;else for(var o=0;o-1,a.selected!==o&&(a.selected=o);else if(E(Zi(a),r))return void(e.selectedIndex!==s&&(e.selectedIndex=s));i||(e.selectedIndex=-1)}}function Wi(e,t){return t.every(function(t){return!E(t,e)})}function Zi(e){return"_value"in e?e._value:e.value}function Gi(e){e.target.composing=!0}function Xi(e){e.target.composing&&(e.target.composing=!1,Yi(e.target,"input"))}function Yi(e,t){var n=document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),e.dispatchEvent(n)}function Qi(e){return!e.componentInstance||e.data&&e.data.transition?e:Qi(e.componentInstance._vnode)}var eo={model:Ki,show:{bind:function(e,t,n){var r=t.value,i=(n=Qi(n)).data&&n.data.transition,o=e.__vOriginalDisplay="none"===e.style.display?"":e.style.display;r&&i?(n.data.show=!0,Ri(n,function(){e.style.display=o})):e.style.display=r?o:"none"},update:function(e,t,n){var r=t.value;!r!=!t.oldValue&&((n=Qi(n)).data&&n.data.transition?(n.data.show=!0,r?Ri(n,function(){e.style.display=e.__vOriginalDisplay}):Hi(n,function(){e.style.display="none"})):e.style.display=r?e.__vOriginalDisplay:"none")},unbind:function(e,t,n,r,i){i||(e.style.display=e.__vOriginalDisplay)}}},to={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String,duration:[Number,String,Object]};function no(e){var t=e&&e.componentOptions;return t&&t.Ctor.options.abstract?no(zt(t.children)):e}function ro(e){var t={},n=e.$options;for(var r in n.propsData)t[r]=e[r];var i=n._parentListeners;for(var o in i)t[b(o)]=i[o];return t}function io(e,t){if(/\d-keep-alive$/.test(t.tag))return e("keep-alive",{props:t.componentOptions.propsData})}var oo=function(e){return e.tag||pt(e)},ao=function(e){return"show"===e.name},so={name:"transition",props:to,abstract:!0,render:function(e){var t=this,n=this.$slots.default;if(n&&(n=n.filter(oo)).length){var r=this.mode,o=n[0];if(function(e){for(;e=e.parent;)if(e.data.transition)return!0}(this.$vnode))return o;var a=no(o);if(!a)return o;if(this._leaving)return io(e,o);var s="__transition-"+this._uid+"-";a.key=null==a.key?a.isComment?s+"comment":s+a.tag:i(a.key)?0===String(a.key).indexOf(s)?a.key:s+a.key:a.key;var c=(a.data||(a.data={})).transition=ro(this),u=this._vnode,l=no(u);if(a.data.directives&&a.data.directives.some(ao)&&(a.data.show=!0),l&&l.data&&!function(e,t){return t.key===e.key&&t.tag===e.tag}(a,l)&&!pt(l)&&(!l.componentInstance||!l.componentInstance._vnode.isComment)){var f=l.data.transition=A({},c);if("out-in"===r)return this._leaving=!0,ot(f,"afterLeave",function(){t._leaving=!1,t.$forceUpdate()}),io(e,o);if("in-out"===r){if(pt(a))return u;var p,d=function(){p()};ot(c,"afterEnter",d),ot(c,"enterCancelled",d),ot(f,"delayLeave",function(e){p=e})}}return o}}},co=A({tag:String,moveClass:String},to);function uo(e){e.elm._moveCb&&e.elm._moveCb(),e.elm._enterCb&&e.elm._enterCb()}function lo(e){e.data.newPos=e.elm.getBoundingClientRect()}function fo(e){var t=e.data.pos,n=e.data.newPos,r=t.left-n.left,i=t.top-n.top;if(r||i){e.data.moved=!0;var o=e.elm.style;o.transform=o.WebkitTransform="translate("+r+"px,"+i+"px)",o.transitionDuration="0s"}}delete co.mode;var po={Transition:so,TransitionGroup:{props:co,beforeMount:function(){var e=this,t=this._update;this._update=function(n,r){var i=Gt(e);e.__patch__(e._vnode,e.kept,!1,!0),e._vnode=e.kept,i(),t.call(e,n,r)}},render:function(e){for(var t=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||[],o=this.children=[],a=ro(this),s=0;s-1?Xn[e]=t.constructor===window.HTMLUnknownElement||t.constructor===window.HTMLElement:Xn[e]=/HTMLUnknownElement/.test(t.toString())},A(Cn.options.directives,eo),A(Cn.options.components,po),Cn.prototype.__patch__=V?zi:S,Cn.prototype.$mount=function(e,t){return function(e,t,n){var r;return e.$el=t,e.$options.render||(e.$options.render=ve),Qt(e,"beforeMount"),r=function(){e._update(e._render(),n)},new pn(e,r,S,{before:function(){e._isMounted&&!e._isDestroyed&&Qt(e,"beforeUpdate")}},!0),n=!1,null==e.$vnode&&(e._isMounted=!0,Qt(e,"mounted")),e}(this,e=e&&V?Qn(e):void 0,t)},V&&setTimeout(function(){F.devtools&&ne&&ne.emit("init",Cn)},0);var vo=/\{\{((?:.|\r?\n)+?)\}\}/g,ho=/[-.*+?^${}()|[\]\/\\]/g,mo=g(function(e){var t=e[0].replace(ho,"\\$&"),n=e[1].replace(ho,"\\$&");return new RegExp(t+"((?:.|\\n)+?)"+n,"g")});var yo={staticKeys:["staticClass"],transformNode:function(e,t){t.warn;var n=Pr(e,"class");n&&(e.staticClass=JSON.stringify(n));var r=Fr(e,"class",!1);r&&(e.classBinding=r)},genData:function(e){var t="";return e.staticClass&&(t+="staticClass:"+e.staticClass+","),e.classBinding&&(t+="class:"+e.classBinding+","),t}};var go,_o={staticKeys:["staticStyle"],transformNode:function(e,t){t.warn;var n=Pr(e,"style");n&&(e.staticStyle=JSON.stringify(si(n)));var r=Fr(e,"style",!1);r&&(e.styleBinding=r)},genData:function(e){var t="";return e.staticStyle&&(t+="staticStyle:"+e.staticStyle+","),e.styleBinding&&(t+="style:("+e.styleBinding+"),"),t}},bo=function(e){return(go=go||document.createElement("div")).innerHTML=e,go.textContent},$o=p("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr"),wo=p("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source"),Co=p("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track"),xo=/^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,ko=/^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+?\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,Ao="[a-zA-Z_][\\-\\.0-9_a-zA-Z"+P.source+"]*",Oo="((?:"+Ao+"\\:)?"+Ao+")",So=new RegExp("^<"+Oo),To=/^\s*(\/?)>/,No=new RegExp("^<\\/"+Oo+"[^>]*>"),Eo=/^]+>/i,jo=/^",""":'"',"&":"&"," ":"\n"," ":"\t","'":"'"},Fo=/&(?:lt|gt|quot|amp|#39);/g,Po=/&(?:lt|gt|quot|amp|#39|#10|#9);/g,Ro=p("pre,textarea",!0),Ho=function(e,t){return e&&Ro(e)&&"\n"===t[0]};function Bo(e,t){var n=t?Po:Fo;return e.replace(n,function(e){return Mo[e]})}var Uo,Vo,zo,Ko,Jo,qo,Wo,Zo,Go=/^@|^v-on:/,Xo=/^v-|^@|^:|^#/,Yo=/([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/,Qo=/,([^,\}\]]*)(?:,([^,\}\]]*))?$/,ea=/^\(|\)$/g,ta=/^\[.*\]$/,na=/:(.*)$/,ra=/^:|^\.|^v-bind:/,ia=/\.[^.\]]+(?=[^\]]*$)/g,oa=/^v-slot(:|$)|^#/,aa=/[\r\n]/,sa=/[ \f\t\r\n]+/g,ca=g(bo),ua="_empty_";function la(e,t,n){return{type:1,tag:e,attrsList:t,attrsMap:ya(t),rawAttrsMap:{},parent:n,children:[]}}function fa(e,t){Uo=t.warn||Tr,qo=t.isPreTag||T,Wo=t.mustUseProp||T,Zo=t.getTagNamespace||T;t.isReservedTag;zo=Nr(t.modules,"transformNode"),Ko=Nr(t.modules,"preTransformNode"),Jo=Nr(t.modules,"postTransformNode"),Vo=t.delimiters;var n,r,i=[],o=!1!==t.preserveWhitespace,a=t.whitespace,s=!1,c=!1;function u(e){if(l(e),s||e.processed||(e=pa(e,t)),i.length||e===n||n.if&&(e.elseif||e.else)&&va(n,{exp:e.elseif,block:e}),r&&!e.forbidden)if(e.elseif||e.else)a=e,(u=function(e){var t=e.length;for(;t--;){if(1===e[t].type)return e[t];e.pop()}}(r.children))&&u.if&&va(u,{exp:a.elseif,block:a});else{if(e.slotScope){var o=e.slotTarget||'"default"';(r.scopedSlots||(r.scopedSlots={}))[o]=e}r.children.push(e),e.parent=r}var a,u;e.children=e.children.filter(function(e){return!e.slotScope}),l(e),e.pre&&(s=!1),qo(e.tag)&&(c=!1);for(var f=0;f]*>)","i")),p=e.replace(f,function(e,n,r){return u=r.length,Lo(l)||"noscript"===l||(n=n.replace(//g,"$1").replace(//g,"$1")),Ho(l,n)&&(n=n.slice(1)),t.chars&&t.chars(n),""});c+=e.length-p.length,e=p,A(l,c-u,c)}else{var d=e.indexOf("<");if(0===d){if(jo.test(e)){var v=e.indexOf("--\x3e");if(v>=0){t.shouldKeepComment&&t.comment(e.substring(4,v),c,c+v+3),C(v+3);continue}}if(Do.test(e)){var h=e.indexOf("]>");if(h>=0){C(h+2);continue}}var m=e.match(Eo);if(m){C(m[0].length);continue}var y=e.match(No);if(y){var g=c;C(y[0].length),A(y[1],g,c);continue}var _=x();if(_){k(_),Ho(_.tagName,e)&&C(1);continue}}var b=void 0,$=void 0,w=void 0;if(d>=0){for($=e.slice(d);!(No.test($)||So.test($)||jo.test($)||Do.test($)||(w=$.indexOf("<",1))<0);)d+=w,$=e.slice(d);b=e.substring(0,d)}d<0&&(b=e),b&&C(b.length),t.chars&&b&&t.chars(b,c-b.length,c)}if(e===n){t.chars&&t.chars(e);break}}function C(t){c+=t,e=e.substring(t)}function x(){var t=e.match(So);if(t){var n,r,i={tagName:t[1],attrs:[],start:c};for(C(t[0].length);!(n=e.match(To))&&(r=e.match(ko)||e.match(xo));)r.start=c,C(r[0].length),r.end=c,i.attrs.push(r);if(n)return i.unarySlash=n[1],C(n[0].length),i.end=c,i}}function k(e){var n=e.tagName,c=e.unarySlash;o&&("p"===r&&Co(n)&&A(r),s(n)&&r===n&&A(n));for(var u=a(n)||!!c,l=e.attrs.length,f=new Array(l),p=0;p=0&&i[a].lowerCasedTag!==s;a--);else a=0;if(a>=0){for(var u=i.length-1;u>=a;u--)t.end&&t.end(i[u].tag,n,o);i.length=a,r=a&&i[a-1].tag}else"br"===s?t.start&&t.start(e,[],!0,n,o):"p"===s&&(t.start&&t.start(e,[],!1,n,o),t.end&&t.end(e,n,o))}A()}(e,{warn:Uo,expectHTML:t.expectHTML,isUnaryTag:t.isUnaryTag,canBeLeftOpenTag:t.canBeLeftOpenTag,shouldDecodeNewlines:t.shouldDecodeNewlines,shouldDecodeNewlinesForHref:t.shouldDecodeNewlinesForHref,shouldKeepComment:t.comments,outputSourceRange:t.outputSourceRange,start:function(e,o,a,l,f){var p=r&&r.ns||Zo(e);q&&"svg"===p&&(o=function(e){for(var t=[],n=0;nc&&(s.push(o=e.slice(c,i)),a.push(JSON.stringify(o)));var u=Or(r[1].trim());a.push("_s("+u+")"),s.push({"@binding":u}),c=i+r[0].length}return c-1"+("true"===o?":("+t+")":":_q("+t+","+o+")")),Mr(e,"change","var $$a="+t+",$$el=$event.target,$$c=$$el.checked?("+o+"):("+a+");if(Array.isArray($$a)){var $$v="+(r?"_n("+i+")":i)+",$$i=_i($$a,$$v);if($$el.checked){$$i<0&&("+Ur(t,"$$a.concat([$$v])")+")}else{$$i>-1&&("+Ur(t,"$$a.slice(0,$$i).concat($$a.slice($$i+1))")+")}}else{"+Ur(t,"$$c")+"}",null,!0)}(e,r,i);else if("input"===o&&"radio"===a)!function(e,t,n){var r=n&&n.number,i=Fr(e,"value")||"null";Er(e,"checked","_q("+t+","+(i=r?"_n("+i+")":i)+")"),Mr(e,"change",Ur(t,i),null,!0)}(e,r,i);else if("input"===o||"textarea"===o)!function(e,t,n){var r=e.attrsMap.type,i=n||{},o=i.lazy,a=i.number,s=i.trim,c=!o&&"range"!==r,u=o?"change":"range"===r?Zr:"input",l="$event.target.value";s&&(l="$event.target.value.trim()"),a&&(l="_n("+l+")");var f=Ur(t,l);c&&(f="if($event.target.composing)return;"+f),Er(e,"value","("+t+")"),Mr(e,u,f,null,!0),(s||a)&&Mr(e,"blur","$forceUpdate()")}(e,r,i);else if(!F.isReservedTag(o))return Br(e,r,i),!1;return!0},text:function(e,t){t.value&&Er(e,"textContent","_s("+t.value+")",t)},html:function(e,t){t.value&&Er(e,"innerHTML","_s("+t.value+")",t)}},isPreTag:function(e){return"pre"===e},isUnaryTag:$o,mustUseProp:Dn,canBeLeftOpenTag:wo,isReservedTag:Zn,getTagNamespace:Gn,staticKeys:function(e){return e.reduce(function(e,t){return e.concat(t.staticKeys||[])},[]).join(",")}($a)},ka=g(function(e){return p("type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap"+(e?","+e:""))});function Aa(e,t){e&&(wa=ka(t.staticKeys||""),Ca=t.isReservedTag||T,function e(t){t.static=function(e){if(2===e.type)return!1;if(3===e.type)return!0;return!(!e.pre&&(e.hasBindings||e.if||e.for||d(e.tag)||!Ca(e.tag)||function(e){for(;e.parent;){if("template"!==(e=e.parent).tag)return!1;if(e.for)return!0}return!1}(e)||!Object.keys(e).every(wa)))}(t);if(1===t.type){if(!Ca(t.tag)&&"slot"!==t.tag&&null==t.attrsMap["inline-template"])return;for(var n=0,r=t.children.length;n|^function(?:\s+[\w$]+)?\s*\(/,Sa=/\([^)]*?\);*$/,Ta=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/,Na={esc:27,tab:9,enter:13,space:32,up:38,left:37,right:39,down:40,delete:[8,46]},Ea={esc:["Esc","Escape"],tab:"Tab",enter:"Enter",space:[" ","Spacebar"],up:["Up","ArrowUp"],left:["Left","ArrowLeft"],right:["Right","ArrowRight"],down:["Down","ArrowDown"],delete:["Backspace","Delete","Del"]},ja=function(e){return"if("+e+")return null;"},Da={stop:"$event.stopPropagation();",prevent:"$event.preventDefault();",self:ja("$event.target !== $event.currentTarget"),ctrl:ja("!$event.ctrlKey"),shift:ja("!$event.shiftKey"),alt:ja("!$event.altKey"),meta:ja("!$event.metaKey"),left:ja("'button' in $event && $event.button !== 0"),middle:ja("'button' in $event && $event.button !== 1"),right:ja("'button' in $event && $event.button !== 2")};function La(e,t){var n=t?"nativeOn:":"on:",r="",i="";for(var o in e){var a=Ia(e[o]);e[o]&&e[o].dynamic?i+=o+","+a+",":r+='"'+o+'":'+a+","}return r="{"+r.slice(0,-1)+"}",i?n+"_d("+r+",["+i.slice(0,-1)+"])":n+r}function Ia(e){if(!e)return"function(){}";if(Array.isArray(e))return"["+e.map(function(e){return Ia(e)}).join(",")+"]";var t=Ta.test(e.value),n=Oa.test(e.value),r=Ta.test(e.value.replace(Sa,""));if(e.modifiers){var i="",o="",a=[];for(var s in e.modifiers)if(Da[s])o+=Da[s],Na[s]&&a.push(s);else if("exact"===s){var c=e.modifiers;o+=ja(["ctrl","shift","alt","meta"].filter(function(e){return!c[e]}).map(function(e){return"$event."+e+"Key"}).join("||"))}else a.push(s);return a.length&&(i+=function(e){return"if(!$event.type.indexOf('key')&&"+e.map(Ma).join("&&")+")return null;"}(a)),o&&(i+=o),"function($event){"+i+(t?"return "+e.value+".apply(null, arguments)":n?"return ("+e.value+").apply(null, arguments)":r?"return "+e.value:e.value)+"}"}return t||n?e.value:"function($event){"+(r?"return "+e.value:e.value)+"}"}function Ma(e){var t=parseInt(e,10);if(t)return"$event.keyCode!=="+t;var n=Na[e],r=Ea[e];return"_k($event.keyCode,"+JSON.stringify(e)+","+JSON.stringify(n)+",$event.key,"+JSON.stringify(r)+")"}var Fa={on:function(e,t){e.wrapListeners=function(e){return"_g("+e+","+t.value+")"}},bind:function(e,t){e.wrapData=function(n){return"_b("+n+",'"+e.tag+"',"+t.value+","+(t.modifiers&&t.modifiers.prop?"true":"false")+(t.modifiers&&t.modifiers.sync?",true":"")+")"}},cloak:S},Pa=function(e){this.options=e,this.warn=e.warn||Tr,this.transforms=Nr(e.modules,"transformCode"),this.dataGenFns=Nr(e.modules,"genData"),this.directives=A(A({},Fa),e.directives);var t=e.isReservedTag||T;this.maybeComponent=function(e){return!!e.component||!t(e.tag)},this.onceId=0,this.staticRenderFns=[],this.pre=!1};function Ra(e,t){var n=new Pa(t);return{render:"with(this){return "+(e?"script"===e.tag?"null":Ha(e,n):'_c("div")')+"}",staticRenderFns:n.staticRenderFns}}function Ha(e,t){if(e.parent&&(e.pre=e.pre||e.parent.pre),e.staticRoot&&!e.staticProcessed)return Ba(e,t);if(e.once&&!e.onceProcessed)return Ua(e,t);if(e.for&&!e.forProcessed)return za(e,t);if(e.if&&!e.ifProcessed)return Va(e,t);if("template"!==e.tag||e.slotTarget||t.pre){if("slot"===e.tag)return function(e,t){var n=e.slotName||'"default"',r=Wa(e,t),i="_t("+n+(r?",function(){return "+r+"}":""),o=e.attrs||e.dynamicAttrs?Xa((e.attrs||[]).concat(e.dynamicAttrs||[]).map(function(e){return{name:b(e.name),value:e.value,dynamic:e.dynamic}})):null,a=e.attrsMap["v-bind"];!o&&!a||r||(i+=",null");o&&(i+=","+o);a&&(i+=(o?"":",null")+","+a);return i+")"}(e,t);var n;if(e.component)n=function(e,t,n){var r=t.inlineTemplate?null:Wa(t,n,!0);return"_c("+e+","+Ka(t,n)+(r?","+r:"")+")"}(e.component,e,t);else{var r;(!e.plain||e.pre&&t.maybeComponent(e))&&(r=Ka(e,t));var i=e.inlineTemplate?null:Wa(e,t,!0);n="_c('"+e.tag+"'"+(r?","+r:"")+(i?","+i:"")+")"}for(var o=0;o>>0}(a):"")+")"}(e,e.scopedSlots,t)+","),e.model&&(n+="model:{value:"+e.model.value+",callback:"+e.model.callback+",expression:"+e.model.expression+"},"),e.inlineTemplate){var o=function(e,t){var n=e.children[0];if(n&&1===n.type){var r=Ra(n,t.options);return"inlineTemplate:{render:function(){"+r.render+"},staticRenderFns:["+r.staticRenderFns.map(function(e){return"function(){"+e+"}"}).join(",")+"]}"}}(e,t);o&&(n+=o+",")}return n=n.replace(/,$/,"")+"}",e.dynamicAttrs&&(n="_b("+n+',"'+e.tag+'",'+Xa(e.dynamicAttrs)+")"),e.wrapData&&(n=e.wrapData(n)),e.wrapListeners&&(n=e.wrapListeners(n)),n}function Ja(e){return 1===e.type&&("slot"===e.tag||e.children.some(Ja))}function qa(e,t){var n=e.attrsMap["slot-scope"];if(e.if&&!e.ifProcessed&&!n)return Va(e,t,qa,"null");if(e.for&&!e.forProcessed)return za(e,t,qa);var r=e.slotScope===ua?"":String(e.slotScope),i="function("+r+"){return "+("template"===e.tag?e.if&&n?"("+e.if+")?"+(Wa(e,t)||"undefined")+":undefined":Wa(e,t)||"undefined":Ha(e,t))+"}",o=r?"":",proxy:true";return"{key:"+(e.slotTarget||'"default"')+",fn:"+i+o+"}"}function Wa(e,t,n,r,i){var o=e.children;if(o.length){var a=o[0];if(1===o.length&&a.for&&"template"!==a.tag&&"slot"!==a.tag){var s=n?t.maybeComponent(a)?",1":",0":"";return""+(r||Ha)(a,t)+s}var c=n?function(e,t){for(var n=0,r=0;r':'
',ns.innerHTML.indexOf(" ")>0}var as=!!V&&os(!1),ss=!!V&&os(!0),cs=g(function(e){var t=Qn(e);return t&&t.innerHTML}),us=Cn.prototype.$mount;return Cn.prototype.$mount=function(e,t){if((e=e&&Qn(e))===document.body||e===document.documentElement)return this;var n=this.$options;if(!n.render){var r=n.template;if(r)if("string"==typeof r)"#"===r.charAt(0)&&(r=cs(r));else{if(!r.nodeType)return this;r=r.innerHTML}else e&&(r=function(e){if(e.outerHTML)return e.outerHTML;var t=document.createElement("div");return t.appendChild(e.cloneNode(!0)),t.innerHTML}(e));if(r){var i=is(r,{outputSourceRange:!1,shouldDecodeNewlines:as,shouldDecodeNewlinesForHref:ss,delimiters:n.delimiters,comments:n.comments},this),o=i.render,a=i.staticRenderFns;n.render=o,n.staticRenderFns=a}}return us.call(this,e,t)},Cn.compile=is,Cn}); 7 | 8 | console.log('vue.min.js loaded') --------------------------------------------------------------------------------