@pyscript/core 0.6.16 → 0.6.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/{codemirror-58X3ss1_.js → codemirror-CYQioq7P.js} +2 -2
  2. package/dist/{codemirror-58X3ss1_.js.map → codemirror-CYQioq7P.js.map} +1 -1
  3. package/dist/{codemirror_lang-python-tUxVZ93u.js → codemirror_lang-python-D6XFbhta.js} +2 -2
  4. package/dist/{codemirror_lang-python-tUxVZ93u.js.map → codemirror_lang-python-D6XFbhta.js.map} +1 -1
  5. package/dist/{core-B41yp4Hb.js → core-C6OIYLp0.js} +2 -2
  6. package/dist/{core-B41yp4Hb.js.map → core-C6OIYLp0.js.map} +1 -1
  7. package/dist/core.js +1 -1
  8. package/dist/{deprecations-manager-DbhzVmhG.js → deprecations-manager-C7jJsYNl.js} +2 -2
  9. package/dist/{deprecations-manager-DbhzVmhG.js.map → deprecations-manager-C7jJsYNl.js.map} +1 -1
  10. package/dist/{donkey-BF4VqSCX.js → donkey-CvBTfD_H.js} +2 -2
  11. package/dist/{donkey-BF4VqSCX.js.map → donkey-CvBTfD_H.js.map} +1 -1
  12. package/dist/{error-BWLhIfGl.js → error-vhadFB-7.js} +2 -2
  13. package/dist/{error-BWLhIfGl.js.map → error-vhadFB-7.js.map} +1 -1
  14. package/dist/index-BuWusYhv.js +2 -0
  15. package/dist/index-BuWusYhv.js.map +1 -0
  16. package/dist/{mpy-DUBVfsP_.js → mpy-WE2y1AX3.js} +2 -2
  17. package/dist/{mpy-DUBVfsP_.js.map → mpy-WE2y1AX3.js.map} +1 -1
  18. package/dist/{py-BJabKiMI.js → py-BDTcLC5t.js} +2 -2
  19. package/dist/{py-BJabKiMI.js.map → py-BDTcLC5t.js.map} +1 -1
  20. package/dist/{py-editor-C0NJhJsg.js → py-editor-BjQVskL1.js} +2 -2
  21. package/dist/{py-editor-C0NJhJsg.js.map → py-editor-BjQVskL1.js.map} +1 -1
  22. package/dist/{py-terminal-eSfZvBaK.js → py-terminal-FvAvZfH0.js} +2 -2
  23. package/dist/{py-terminal-eSfZvBaK.js.map → py-terminal-FvAvZfH0.js.map} +1 -1
  24. package/dist/xterm-7LwxAMsn.js +2 -0
  25. package/dist/xterm-7LwxAMsn.js.map +1 -0
  26. package/dist/{xterm-readline-CP-6ePRb.js → xterm-readline-e8QPhSrm.js} +2 -2
  27. package/dist/xterm-readline-e8QPhSrm.js.map +1 -0
  28. package/dist/xterm.css +2 -2
  29. package/package.json +4 -4
  30. package/src/3rd-party/xterm-readline.js +2 -2
  31. package/src/3rd-party/xterm.css +2 -2
  32. package/src/3rd-party/xterm.js +2 -2
  33. package/src/stdlib/pyscript/__init__.py +3 -13
  34. package/src/stdlib/pyscript/events.py +166 -0
  35. package/src/stdlib/pyscript/util.py +25 -0
  36. package/src/stdlib/pyscript/web.py +49 -3
  37. package/src/stdlib/pyscript.js +4 -4
  38. package/types/3rd-party/xterm-readline.d.ts +9 -9
  39. package/types/3rd-party/xterm.d.ts +4 -4
  40. package/types/stdlib/pyscript.d.ts +1 -1
  41. package/dist/index-K1IVD1z0.js +0 -2
  42. package/dist/index-K1IVD1z0.js.map +0 -1
  43. package/dist/xterm-BY7uk_OU.js +0 -2
  44. package/dist/xterm-BY7uk_OU.js.map +0 -1
  45. package/dist/xterm-readline-CP-6ePRb.js.map +0 -1
  46. package/src/stdlib/pyscript/event_handling.py +0 -76
@@ -30,8 +30,6 @@
30
30
  # as it works transparently in both the main thread and worker cases.
31
31
 
32
32
  from polyscript import lazy_py_modules as py_import
33
- from pyscript.display import HTML, display
34
- from pyscript.fetch import fetch
35
33
  from pyscript.magic_js import (
36
34
  RUNNING_IN_WORKER,
37
35
  PyWorker,
@@ -43,19 +41,11 @@ from pyscript.magic_js import (
43
41
  sync,
44
42
  window,
45
43
  )
44
+ from pyscript.display import HTML, display
45
+ from pyscript.fetch import fetch
46
46
  from pyscript.storage import Storage, storage
47
47
  from pyscript.websocket import WebSocket
48
+ from pyscript.events import when, Event
48
49
 
49
50
  if not RUNNING_IN_WORKER:
50
51
  from pyscript.workers import create_named_worker, workers
51
-
52
- try:
53
- from pyscript.event_handling import when
54
- except:
55
- # TODO: should we remove this? Or at the very least, we should capture
56
- # the traceback otherwise it's very hard to debug
57
- from pyscript.util import NotSupported
58
-
59
- when = NotSupported(
60
- "pyscript.when", "pyscript.when currently not available with this interpreter"
61
- )
@@ -0,0 +1,166 @@
1
+ import asyncio
2
+ import inspect
3
+ import sys
4
+
5
+ from functools import wraps
6
+ from pyscript.magic_js import document
7
+ from pyscript.ffi import create_proxy
8
+ from pyscript.util import is_awaitable
9
+ from pyscript import config
10
+
11
+
12
+ class Event:
13
+ """
14
+ Represents something that may happen at some point in the future.
15
+ """
16
+
17
+ def __init__(self):
18
+ self._listeners = []
19
+
20
+ def trigger(self, result):
21
+ """
22
+ Trigger the event with a result to pass into the handlers.
23
+ """
24
+ for listener in self._listeners:
25
+ if is_awaitable(listener):
26
+ # Use create task to avoid making this an async function.
27
+ asyncio.create_task(listener(result))
28
+ else:
29
+ listener(result)
30
+
31
+ def add_listener(self, listener):
32
+ """
33
+ Add a callable/awaitable to listen to when this event is triggered.
34
+ """
35
+ if is_awaitable(listener) or callable(listener):
36
+ if listener not in self._listeners:
37
+ self._listeners.append(listener)
38
+ else:
39
+ raise ValueError("Listener must be callable or awaitable.")
40
+
41
+ def remove_listener(self, *args):
42
+ """
43
+ Clear the specified handler functions in *args. If no handlers
44
+ provided, clear all handlers.
45
+ """
46
+ if args:
47
+ for listener in args:
48
+ self._listeners.remove(listener)
49
+ else:
50
+ self._listeners = []
51
+
52
+
53
+ def when(target, *args, **kwargs):
54
+ """
55
+ Add an event listener to the target element(s) for the specified event type.
56
+
57
+ The target can be a string representing the event type, or an Event object.
58
+ If the target is an Event object, the event listener will be added to that
59
+ object. If the target is a string, the event listener will be added to the
60
+ element(s) that match the (second) selector argument.
61
+
62
+ If a (third) handler argument is provided, it will be called when the event
63
+ is triggered; thus allowing this to be used as both a function and a
64
+ decorator.
65
+ """
66
+ # If "when" is called as a function, try to grab the handler from the
67
+ # arguments. If there's no handler, this must be a decorator based call.
68
+ handler = None
69
+ if args and (callable(args[0]) or is_awaitable(args[0])):
70
+ handler = args[0]
71
+ elif callable(kwargs.get("handler")) or is_awaitable(kwargs.get("handler")):
72
+ handler = kwargs.pop("handler")
73
+ # If the target is a string, it is the "older" use of `when` where it
74
+ # represents the name of a DOM event.
75
+ if isinstance(target, str):
76
+ # Extract the selector from the arguments or keyword arguments.
77
+ selector = args[0] if args else kwargs.pop("selector")
78
+ if not selector:
79
+ raise ValueError("No selector provided.")
80
+ # Grab the DOM elements to which the target event will be attached.
81
+ from pyscript.web import Element, ElementCollection
82
+
83
+ if isinstance(selector, str):
84
+ elements = document.querySelectorAll(selector)
85
+ elif isinstance(selector, Element):
86
+ elements = [selector._dom_element]
87
+ elif isinstance(selector, ElementCollection):
88
+ elements = [el._dom_element for el in selector]
89
+ else:
90
+ elements = selector if isinstance(selector, list) else [selector]
91
+
92
+ def decorator(func):
93
+ if config["type"] == "mpy": # Is MicroPython?
94
+ if is_awaitable(func):
95
+
96
+ async def wrapper(*args, **kwargs):
97
+ """
98
+ This is a very ugly hack to get micropython working because
99
+ `inspect.signature` doesn't exist. It may be actually better
100
+ to not try any magic for now and raise the error.
101
+ """
102
+ try:
103
+ return await func(*args, **kwargs)
104
+
105
+ except TypeError as e:
106
+ if "takes" in str(e) and "positional arguments" in str(e):
107
+ return await func()
108
+ raise
109
+
110
+ else:
111
+
112
+ def wrapper(*args, **kwargs):
113
+ """
114
+ This is a very ugly hack to get micropython working because
115
+ `inspect.signature` doesn't exist. It may be actually better
116
+ to not try any magic for now and raise the error.
117
+ """
118
+ try:
119
+ return func(*args, **kwargs)
120
+
121
+ except TypeError as e:
122
+ if "takes" in str(e) and "positional arguments" in str(e):
123
+ return func()
124
+ raise
125
+
126
+ else:
127
+ sig = inspect.signature(func)
128
+ if sig.parameters:
129
+ if is_awaitable(func):
130
+
131
+ async def wrapper(event):
132
+ return await func(event)
133
+
134
+ else:
135
+ wrapper = func
136
+ else:
137
+ # Function doesn't receive events.
138
+ if is_awaitable(func):
139
+
140
+ async def wrapper(*args, **kwargs):
141
+ return await func()
142
+
143
+ else:
144
+
145
+ def wrapper(*args, **kwargs):
146
+ return func()
147
+
148
+ wrapper = wraps(func)(wrapper)
149
+ if isinstance(target, Event):
150
+ # The target is a single Event object.
151
+ target.add_listener(wrapper)
152
+ elif isinstance(target, list) and all(isinstance(t, Event) for t in target):
153
+ # The target is a list of Event objects.
154
+ for evt in target:
155
+ evt.add_listener(wrapper)
156
+ else:
157
+ # The target is a string representing an event type, and so a
158
+ # DOM element or collection of elements is found in "elements".
159
+ for el in elements:
160
+ el.addEventListener(target, create_proxy(wrapper))
161
+ return wrapper
162
+
163
+ # If "when" was called as a decorator, return the decorator function,
164
+ # otherwise just call the internal decorator function with the supplied
165
+ # handler.
166
+ return decorator(handler) if handler else decorator
@@ -1,7 +1,13 @@
1
1
  import js
2
+ import sys
3
+ import inspect
2
4
 
3
5
 
4
6
  def as_bytearray(buffer):
7
+ """
8
+ Given a JavaScript ArrayBuffer, convert it to a Python bytearray in a
9
+ MicroPython friendly manner.
10
+ """
5
11
  ui8a = js.Uint8Array.new(buffer)
6
12
  size = ui8a.length
7
13
  ba = bytearray(size)
@@ -31,3 +37,22 @@ class NotSupported:
31
37
 
32
38
  def __call__(self, *args):
33
39
  raise TypeError(self.error)
40
+
41
+
42
+ def is_awaitable(obj):
43
+ """
44
+ Returns a boolean indication if the passed in obj is an awaitable
45
+ function. (MicroPython treats awaitables as generator functions, and if
46
+ the object is a closure containing an async function we need to work
47
+ carefully.)
48
+ """
49
+ from pyscript import config
50
+
51
+ if config["type"] == "mpy": # Is MicroPython?
52
+ # MicroPython doesn't appear to have a way to determine if a closure is
53
+ # an async function except via the repr. This is a bit hacky.
54
+ if "<closure <generator>" in repr(obj):
55
+ return True
56
+ return inspect.isgeneratorfunction(obj)
57
+
58
+ return inspect.iscoroutinefunction(obj)
@@ -2,7 +2,8 @@
2
2
 
3
3
  # `when` is not used in this module. It is imported here save the user an additional
4
4
  # import (i.e. they can get what they need from `pyscript.web`).
5
- from pyscript import document, when # NOQA
5
+ from pyscript import document, when, Event # NOQA
6
+ from pyscript.ffi import create_proxy
6
7
 
7
8
 
8
9
  def wrap_dom_element(dom_element):
@@ -68,6 +69,18 @@ class Element:
68
69
  type(self).get_tag_name()
69
70
  )
70
71
 
72
+ # HTML on_events attached to the element become pyscript.Event instances.
73
+ self._on_events = {}
74
+
75
+ # Handle kwargs for handling named events with a default handler function.
76
+ properties = {}
77
+ for name, handler in kwargs.items():
78
+ if name.startswith("on_"):
79
+ ev = self.get_event(name) # Create the default Event instance.
80
+ ev.add_listener(handler)
81
+ else:
82
+ properties[name] = handler
83
+
71
84
  # A set-like interface to the element's `classList`.
72
85
  self._classes = Classes(self)
73
86
 
@@ -75,7 +88,7 @@ class Element:
75
88
  self._style = Style(self)
76
89
 
77
90
  # Set any specified classes, styles, and DOM properties.
78
- self.update(classes=classes, style=style, **kwargs)
91
+ self.update(classes=classes, style=style, **properties)
79
92
 
80
93
  def __eq__(self, obj):
81
94
  """Check for equality by comparing the underlying DOM element."""
@@ -93,13 +106,21 @@ class Element:
93
106
  return self.find(key)
94
107
 
95
108
  def __getattr__(self, name):
109
+ """
110
+ Get an attribute from the element.
111
+
112
+ If the attribute is an event (e.g. "on_click"), we wrap it in an `Event`
113
+ instance and return that. Otherwise, we return the attribute from the
114
+ underlying DOM element.
115
+ """
116
+ if name.startswith("on_"):
117
+ return self.get_event(name)
96
118
  # This allows us to get attributes on the underlying DOM element that clash
97
119
  # with Python keywords or built-ins (e.g. the output element has an
98
120
  # attribute `for` which is a Python keyword, so you can access it on the
99
121
  # Element instance via `for_`).
100
122
  if name.endswith("_"):
101
123
  name = name[:-1]
102
-
103
124
  return getattr(self._dom_element, name)
104
125
 
105
126
  def __setattr__(self, name, value):
@@ -119,8 +140,33 @@ class Element:
119
140
  if name.endswith("_"):
120
141
  name = name[:-1]
121
142
 
143
+ if name.startswith("on_"):
144
+ # Ensure on-events are cached in the _on_events dict if the
145
+ # user is setting them directly.
146
+ self._on_events[name] = value
147
+
122
148
  setattr(self._dom_element, name, value)
123
149
 
150
+ def get_event(self, name):
151
+ """
152
+ Get an `Event` instance for the specified event name.
153
+ """
154
+ if not name.startswith("on_"):
155
+ raise ValueError("Event names must start with 'on_'.")
156
+ event_name = name[3:] # Remove the "on_" prefix.
157
+ if not hasattr(self._dom_element, event_name):
158
+ raise ValueError(f"Element has no '{event_name}' event.")
159
+ if name in self._on_events:
160
+ return self._on_events[name]
161
+ # Such an on-event exists in the DOM element, but we haven't yet
162
+ # wrapped it in an Event instance. Let's do that now. When the
163
+ # underlying DOM element's event is triggered, the Event instance
164
+ # will be triggered too.
165
+ ev = Event()
166
+ self._on_events[name] = ev
167
+ self._dom_element.addEventListener(event_name, create_proxy(ev.trigger))
168
+ return ev
169
+
124
170
  @property
125
171
  def children(self):
126
172
  """Return the element's children as an `ElementCollection`."""
@@ -1,17 +1,17 @@
1
1
  // ⚠️ This file is an artifact: DO NOT MODIFY
2
2
  export default {
3
3
  "pyscript": {
4
- "__init__.py": "from polyscript import lazy_py_modules as py_import\nfrom pyscript.display import HTML,display\nfrom pyscript.fetch import fetch\nfrom pyscript.magic_js import RUNNING_IN_WORKER,PyWorker,config,current_target,document,js_import,js_modules,sync,window\nfrom pyscript.storage import Storage,storage\nfrom pyscript.websocket import WebSocket\nif not RUNNING_IN_WORKER:from pyscript.workers import create_named_worker,workers\ntry:from pyscript.event_handling import when\nexcept:from pyscript.util import NotSupported;when=NotSupported('pyscript.when','pyscript.when currently not available with this interpreter')",
4
+ "__init__.py": "from polyscript import lazy_py_modules as py_import\nfrom pyscript.magic_js import RUNNING_IN_WORKER,PyWorker,config,current_target,document,js_import,js_modules,sync,window\nfrom pyscript.display import HTML,display\nfrom pyscript.fetch import fetch\nfrom pyscript.storage import Storage,storage\nfrom pyscript.websocket import WebSocket\nfrom pyscript.events import when,Event\nif not RUNNING_IN_WORKER:from pyscript.workers import create_named_worker,workers",
5
5
  "display.py": "_L='_repr_mimebundle_'\n_K='image/svg+xml'\n_J='application/json'\n_I='__repr__'\n_H='savefig'\n_G='text/html'\n_F='image/jpeg'\n_E='application/javascript'\n_D='utf-8'\n_C='text/plain'\n_B='image/png'\n_A=None\nimport base64,html,io,re\nfrom pyscript.magic_js import current_target,document,window\n_MIME_METHODS={_H:_B,'_repr_javascript_':_E,'_repr_json_':_J,'_repr_latex':'text/latex','_repr_png_':_B,'_repr_jpeg_':_F,'_repr_pdf_':'application/pdf','_repr_svg_':_K,'_repr_markdown_':'text/markdown','_repr_html_':_G,_I:_C}\ndef _render_image(mime,value,meta):\n\tA=value\n\tif isinstance(A,bytes):A=base64.b64encode(A).decode(_D)\n\tB=re.compile('^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$')\n\tif len(A)>0 and not B.match(A):A=base64.b64encode(A.encode(_D)).decode(_D)\n\tC=f\"data:{mime};charset=utf-8;base64,{A}\";D=' '.join(['{k}=\"{v}\"'for(A,B)in meta.items()]);return f'<img src=\"{C}\" {D}></img>'\ndef _identity(value,meta):return value\n_MIME_RENDERERS={_C:html.escape,_G:_identity,_B:lambda value,meta:_render_image(_B,value,meta),_F:lambda value,meta:_render_image(_F,value,meta),_K:_identity,_J:_identity,_E:lambda value,meta:f\"<script>{value}<\\\\/script>\"}\nclass HTML:\n\tdef __init__(A,html):A._html=html\n\tdef _repr_html_(A):return A._html\ndef _eval_formatter(obj,print_method):\n\tB=obj;A=print_method\n\tif A==_I:return repr(B)\n\telif hasattr(B,A):\n\t\tif A==_H:C=io.BytesIO();B.savefig(C,format='png');C.seek(0);return base64.b64encode(C.read()).decode(_D)\n\t\treturn getattr(B,A)()\n\telif A==_L:return{},{}\ndef _format_mime(obj):\n\tC=obj\n\tif isinstance(C,str):return html.escape(C),_C\n\tD=_eval_formatter(C,_L)\n\tif isinstance(D,tuple):E,I=D\n\telse:E=D\n\tA,F=_A,[]\n\tfor(H,B)in _MIME_METHODS.items():\n\t\tif B in E:A=E[B]\n\t\telse:A=_eval_formatter(C,H)\n\t\tif A is _A:continue\n\t\telif B not in _MIME_RENDERERS:F.append(B);continue\n\t\tbreak\n\tif A is _A:\n\t\tif F:window.console.warn(f\"Rendered object requested unavailable MIME renderers: {F}\")\n\t\tA=repr(A);B=_C\n\telif isinstance(A,tuple):A,G=A\n\telse:G={}\n\treturn _MIME_RENDERERS[B](A,G),B\ndef _write(element,value,append=False):\n\tB=element;C,D=_format_mime(value)\n\tif C=='\\\\n':return\n\tif append:A=document.createElement('div');B.append(A)\n\telse:\n\t\tA=B.lastElementChild\n\t\tif A is _A:A=B\n\tif D in(_E,_G):E=document.createRange().createContextualFragment(C);A.append(E)\n\telse:A.innerHTML=C\ndef display(*D,target=_A,append=True):\n\tC=append;A=target\n\tif A is _A:A=current_target()\n\telif not isinstance(A,str):raise TypeError(f\"target must be str or None, not {A.__class__.__name__}\")\n\telif A=='':raise ValueError('Cannot have an empty target')\n\telif A.startswith('#'):A=A[1:]\n\tB=document.getElementById(A)\n\tif B is _A:raise ValueError(f\"Invalid selector with id={A}. Cannot be found in the page.\")\n\tif B.tagName=='SCRIPT'and hasattr(B,'target'):B=B.target\n\tfor E in D:\n\t\tif not C:B.replaceChildren()\n\t\t_write(B,E,append=C)",
6
- "event_handling.py": "import inspect\ntry:from pyodide.ffi.wrappers import add_event_listener\nexcept ImportError:\n\tdef add_event_listener(el,event_type,func):el.addEventListener(event_type,func)\nfrom pyscript.magic_js import document\ndef when(event_type=None,selector=None):\n\tA=selector\n\tdef B(func):\n\t\tB=func;from pyscript.web import Element as E,ElementCollection as F\n\t\tif isinstance(A,str):C=document.querySelectorAll(A)\n\t\telif isinstance(A,E):C=[A._dom_element]\n\t\telif isinstance(A,F):C=[A._dom_element for A in A]\n\t\telif isinstance(A,list):C=A\n\t\telse:C=[A]\n\t\ttry:\n\t\t\tG=inspect.signature(B)\n\t\t\tif not G.parameters:\n\t\t\t\tif inspect.iscoroutinefunction(B):\n\t\t\t\t\tasync def D(*A,**C):await B()\n\t\t\t\telse:\n\t\t\t\t\tdef D(*A,**C):B()\n\t\t\telse:D=B\n\t\texcept AttributeError:\n\t\t\tdef D(*C,**D):\n\t\t\t\ttry:return B(*C,**D)\n\t\t\t\texcept TypeError as A:\n\t\t\t\t\tif'takes'in str(A)and'positional arguments'in str(A):return B()\n\t\t\t\t\traise\n\t\tfor H in C:add_event_listener(H,event_type,D)\n\t\treturn B\n\treturn B",
6
+ "events.py": "import asyncio,inspect,sys\nfrom functools import wraps\nfrom pyscript.magic_js import document\nfrom pyscript.ffi import create_proxy\nfrom pyscript.util import is_awaitable\nfrom pyscript import config\nclass Event:\n\tdef __init__(A):A._listeners=[]\n\tdef trigger(C,result):\n\t\tB=result\n\t\tfor A in C._listeners:\n\t\t\tif is_awaitable(A):asyncio.create_task(A(B))\n\t\t\telse:A(B)\n\tdef add_listener(B,listener):\n\t\tA=listener\n\t\tif is_awaitable(A)or callable(A):\n\t\t\tif A not in B._listeners:B._listeners.append(A)\n\t\telse:raise ValueError('Listener must be callable or awaitable.')\n\tdef remove_listener(A,*B):\n\t\tif B:\n\t\t\tfor C in B:A._listeners.remove(C)\n\t\telse:A._listeners=[]\ndef when(target,*B,**D):\n\tG='handler';C=target;E=None\n\tif B and(callable(B[0])or is_awaitable(B[0])):E=B[0]\n\telif callable(D.get(G))or is_awaitable(D.get(G)):E=D.pop(G)\n\tif isinstance(C,str):\n\t\tA=B[0]if B else D.pop('selector')\n\t\tif not A:raise ValueError('No selector provided.')\n\t\tfrom pyscript.web import Element as I,ElementCollection as J\n\t\tif isinstance(A,str):F=document.querySelectorAll(A)\n\t\telif isinstance(A,I):F=[A._dom_element]\n\t\telif isinstance(A,J):F=[A._dom_element for A in A]\n\t\telse:F=A if isinstance(A,list)else[A]\n\tdef H(func):\n\t\tE='positional arguments';D='takes';A=func\n\t\tif config['type']=='mpy':\n\t\t\tif is_awaitable(A):\n\t\t\t\tasync def B(*C,**F):\n\t\t\t\t\ttry:return await A(*C,**F)\n\t\t\t\t\texcept TypeError as B:\n\t\t\t\t\t\tif D in str(B)and E in str(B):return await A()\n\t\t\t\t\t\traise\n\t\t\telse:\n\t\t\t\tdef B(*C,**F):\n\t\t\t\t\ttry:return A(*C,**F)\n\t\t\t\t\texcept TypeError as B:\n\t\t\t\t\t\tif D in str(B)and E in str(B):return A()\n\t\t\t\t\t\traise\n\t\telse:\n\t\t\tG=inspect.signature(A)\n\t\t\tif G.parameters:\n\t\t\t\tif is_awaitable(A):\n\t\t\t\t\tasync def B(event):return await A(event)\n\t\t\t\telse:B=A\n\t\t\telif is_awaitable(A):\n\t\t\t\tasync def B(*B,**C):return await A()\n\t\t\telse:\n\t\t\t\tdef B(*B,**C):return A()\n\t\tB=wraps(A)(B)\n\t\tif isinstance(C,Event):C.add_listener(B)\n\t\telif isinstance(C,list)and all(isinstance(A,Event)for A in C):\n\t\t\tfor H in C:H.add_listener(B)\n\t\telse:\n\t\t\tfor I in F:I.addEventListener(C,create_proxy(B))\n\t\treturn B\n\treturn H(E)if E else H",
7
7
  "fetch.py": "import json,js\nfrom pyscript.util import as_bytearray\nclass _Response:\n\tdef __init__(A,response):A._response=response\n\tdef __getattr__(A,attr):return getattr(A._response,attr)\n\tasync def arrayBuffer(B):\n\t\tA=await B._response.arrayBuffer()\n\t\tif hasattr(A,'to_py'):return A.to_py()\n\t\treturn memoryview(as_bytearray(A))\n\tasync def blob(A):return await A._response.blob()\n\tasync def bytearray(A):B=await A._response.arrayBuffer();return as_bytearray(B)\n\tasync def json(A):return json.loads(await A.text())\n\tasync def text(A):return await A._response.text()\nclass _DirectResponse:\n\t@staticmethod\n\tdef setup(promise,response):A=promise;A._response=_Response(response);return A._response\n\tdef __init__(B,promise):A=promise;B._promise=A;A._response=None;A.arrayBuffer=B.arrayBuffer;A.blob=B.blob;A.bytearray=B.bytearray;A.json=B.json;A.text=B.text\n\tasync def _response(A):\n\t\tif not A._promise._response:await A._promise\n\t\treturn A._promise._response\n\tasync def arrayBuffer(A):B=await A._response();return await B.arrayBuffer()\n\tasync def blob(A):B=await A._response();return await B.blob()\n\tasync def bytearray(A):B=await A._response();return await B.bytearray()\n\tasync def json(A):B=await A._response();return await B.json()\n\tasync def text(A):B=await A._response();return await B.text()\ndef fetch(url,**B):C=js.JSON.parse(json.dumps(B));D=lambda response,*B:_DirectResponse.setup(A,response);A=js.fetch(url,C).then(D);_DirectResponse(A);return A",
8
8
  "ffi.py": "try:\n\timport js;from pyodide.ffi import create_proxy as _cp,to_js as _py_tjs;from_entries=js.Object.fromEntries\n\tdef _tjs(value,**A):\n\t\tB='dict_converter'\n\t\tif not hasattr(A,B):A[B]=from_entries\n\t\treturn _py_tjs(value,**A)\nexcept:from jsffi import create_proxy as _cp;from jsffi import to_js as _tjs\ncreate_proxy=_cp\nto_js=_tjs",
9
9
  "flatted.py": "import json as _json\nclass _Known:\n\tdef __init__(A):A.key=[];A.value=[]\nclass _String:\n\tdef __init__(A,value):A.value=value\ndef _array_keys(value):\n\tA=[];B=0\n\tfor C in value:A.append(B);B+=1\n\treturn A\ndef _object_keys(value):\n\tA=[]\n\tfor B in value:A.append(B)\n\treturn A\ndef _is_array(value):A=value;return isinstance(A,list)or isinstance(A,tuple)\ndef _is_object(value):return isinstance(value,dict)\ndef _is_string(value):return isinstance(value,str)\ndef _index(known,input,value):B=value;A=known;input.append(B);C=str(len(input)-1);A.key.append(B);A.value.append(C);return C\ndef _loop(keys,input,known,output):\n\tA=output\n\tfor B in keys:\n\t\tC=A[B]\n\t\tif isinstance(C,_String):_ref(B,input[int(C.value)],input,known,A)\n\treturn A\ndef _ref(key,value,input,known,output):\n\tB=known;A=value\n\tif _is_array(A)and not A in B:B.append(A);A=_loop(_array_keys(A),input,B,A)\n\telif _is_object(A)and not A in B:B.append(A);A=_loop(_object_keys(A),input,B,A)\n\toutput[key]=A\ndef _relate(known,input,value):\n\tB=known;A=value\n\tif _is_string(A)or _is_array(A)or _is_object(A):\n\t\ttry:return B.value[B.key.index(A)]\n\t\texcept:return _index(B,input,A)\n\treturn A\ndef _transform(known,input,value):\n\tB=known;A=value\n\tif _is_array(A):\n\t\tC=[]\n\t\tfor F in A:C.append(_relate(B,input,F))\n\t\treturn C\n\tif _is_object(A):\n\t\tD={}\n\t\tfor E in A:D[E]=_relate(B,input,A[E])\n\t\treturn D\n\treturn A\ndef _wrap(value):\n\tA=value\n\tif _is_string(A):return _String(A)\n\tif _is_array(A):\n\t\tB=0\n\t\tfor D in A:A[B]=_wrap(D);B+=1\n\telif _is_object(A):\n\t\tfor C in A:A[C]=_wrap(A[C])\n\treturn A\ndef parse(value,*C,**D):\n\tA=value;E=_json.loads(A,*C,**D);B=[]\n\tfor A in E:B.append(_wrap(A))\n\tinput=[]\n\tfor A in B:\n\t\tif isinstance(A,_String):input.append(A.value)\n\t\telse:input.append(A)\n\tA=input[0]\n\tif _is_array(A):return _loop(_array_keys(A),input,[A],A)\n\tif _is_object(A):return _loop(_object_keys(A),input,[A],A)\n\treturn A\ndef stringify(value,*D,**E):\n\tB=_Known();input=[];C=[];A=int(_index(B,input,value))\n\twhile A<len(input):C.append(_transform(B,input,input[A]));A+=1\n\treturn _json.dumps(C,*D,**E)",
10
10
  "magic_js.py": "import json,sys,js as globalThis\nfrom polyscript import config as _config,js_modules\nfrom pyscript.util import NotSupported\nRUNNING_IN_WORKER=not hasattr(globalThis,'document')\nconfig=json.loads(globalThis.JSON.stringify(_config))\nif'MicroPython'in sys.version:config['type']='mpy'\nelse:config['type']='py'\nclass JSModule:\n\tdef __init__(A,name):A.name=name\n\tdef __getattr__(B,field):\n\t\tA=field\n\t\tif not A.startswith('_'):return getattr(getattr(js_modules,B.name),A)\nfor name in globalThis.Reflect.ownKeys(js_modules):sys.modules[f\"pyscript.js_modules.{name}\"]=JSModule(name)\nsys.modules['pyscript.js_modules']=js_modules\nif RUNNING_IN_WORKER:\n\timport polyscript;PyWorker=NotSupported('pyscript.PyWorker','pyscript.PyWorker works only when running in the main thread')\n\ttry:import js;window=polyscript.xworker.window;document=window.document;js.document=document;js_import=window.Function('return (...urls) => Promise.all(urls.map((url) => import(url)))')()\n\texcept:message='Unable to use `window` or `document` -> https://docs.pyscript.net/latest/faq/#sharedarraybuffer';globalThis.console.warn(message);window=NotSupported('pyscript.window',message);document=NotSupported('pyscript.document',message);js_import=None\n\tsync=polyscript.xworker.sync\n\tdef current_target():return polyscript.target\nelse:\n\timport _pyscript;from _pyscript import PyWorker,js_import;window=globalThis;document=globalThis.document;sync=NotSupported('pyscript.sync','pyscript.sync works only when running in a worker')\n\tdef current_target():return _pyscript.target",
11
11
  "media.py": "from pyscript import window\nfrom pyscript.ffi import to_js\nclass Device:\n\tdef __init__(A,device):A._dom_element=device\n\t@property\n\tdef id(self):return self._dom_element.deviceId\n\t@property\n\tdef group(self):return self._dom_element.groupId\n\t@property\n\tdef kind(self):return self._dom_element.kind\n\t@property\n\tdef label(self):return self._dom_element.label\n\tdef __getitem__(A,key):return getattr(A,key)\n\t@classmethod\n\tasync def load(E,audio=False,video=True):\n\t\tB=video;A=window.Object.new();A.audio=audio\n\t\tif isinstance(B,bool):A.video=B\n\t\telse:\n\t\t\tA.video=window.Object.new()\n\t\t\tfor C in B:setattr(A.video,C,to_js(B[C]))\n\t\tD=await window.navigator.mediaDevices.getUserMedia(A);return D\n\tasync def get_stream(A):B=A.kind.replace('input','').replace('output','');C={B:{'deviceId':{'exact':A.id}}};return await A.load(**C)\nasync def list_devices():return[Device(A)for A in await window.navigator.mediaDevices.enumerateDevices()]",
12
12
  "storage.py": "_C='memoryview'\n_B='bytearray'\n_A='generic'\nfrom polyscript import storage as _storage\nfrom pyscript.flatted import parse as _parse\nfrom pyscript.flatted import stringify as _stringify\ndef _to_idb(value):\n\tA=value\n\tif A is None:return _stringify(['null',0])\n\tif isinstance(A,(bool,float,int,str,list,dict,tuple)):return _stringify([_A,A])\n\tif isinstance(A,bytearray):return _stringify([_B,[A for A in A]])\n\tif isinstance(A,memoryview):return _stringify([_C,[A for A in A]])\n\traise TypeError(f\"Unexpected value: {A}\")\ndef _from_idb(value):\n\tC=value;A,B=_parse(C)\n\tif A=='null':return\n\tif A==_A:return B\n\tif A==_B:return bytearray(B)\n\tif A==_C:return memoryview(bytearray(B))\n\treturn C\nclass Storage(dict):\n\tdef __init__(B,store):A=store;super().__init__({A:_from_idb(B)for(A,B)in A.entries()});B.__store__=A\n\tdef __delitem__(A,attr):A.__store__.delete(attr);super().__delitem__(attr)\n\tdef __setitem__(B,attr,value):A=value;B.__store__.set(attr,_to_idb(A));super().__setitem__(attr,A)\n\tdef clear(A):A.__store__.clear();super().clear()\n\tasync def sync(A):await A.__store__.sync()\nasync def storage(name='',storage_class=Storage):\n\tif not name:raise ValueError('The storage name must be defined')\n\treturn storage_class(await _storage(f\"@pyscript/{name}\"))",
13
- "util.py": "import js\ndef as_bytearray(buffer):\n\tA=js.Uint8Array.new(buffer);B=A.length;C=bytearray(B)\n\tfor D in range(0,B):C[D]=A[D]\n\treturn C\nclass NotSupported:\n\tdef __init__(A,name,error):object.__setattr__(A,'name',name);object.__setattr__(A,'error',error)\n\tdef __repr__(A):return f\"<NotSupported {A.name} [{A.error}]>\"\n\tdef __getattr__(A,attr):raise AttributeError(A.error)\n\tdef __setattr__(A,attr,value):raise AttributeError(A.error)\n\tdef __call__(A,*B):raise TypeError(A.error)",
14
- "web.py": "_A=None\nfrom pyscript import document,when\ndef wrap_dom_element(dom_element):return Element.wrap_dom_element(dom_element)\nclass Element:\n\telement_classes_by_tag_name={}\n\t@classmethod\n\tdef get_tag_name(A):return A.__name__.replace('_','')\n\t@classmethod\n\tdef register_element_classes(B,element_classes):\n\t\tfor A in element_classes:C=A.get_tag_name();B.element_classes_by_tag_name[C]=A\n\t@classmethod\n\tdef unregister_element_classes(A,element_classes):\n\t\tfor B in element_classes:C=B.get_tag_name();A.element_classes_by_tag_name.pop(C,_A)\n\t@classmethod\n\tdef wrap_dom_element(A,dom_element):B=dom_element;C=A.element_classes_by_tag_name.get(B.tagName.lower(),A);return C(dom_element=B)\n\tdef __init__(A,dom_element=_A,classes=_A,style=_A,**B):A._dom_element=dom_element or document.createElement(type(A).get_tag_name());A._classes=Classes(A);A._style=Style(A);A.update(classes=classes,style=style,**B)\n\tdef __eq__(A,obj):return isinstance(obj,Element)and obj._dom_element==A._dom_element\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int)or isinstance(A,slice):return B.children[A]\n\t\treturn B.find(A)\n\tdef __getattr__(B,name):\n\t\tA=name\n\t\tif A.endswith('_'):A=A[:-1]\n\t\treturn getattr(B._dom_element,A)\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tif A.endswith('_'):A=A[:-1]\n\t\t\tsetattr(C._dom_element,A,B)\n\t@property\n\tdef children(self):return ElementCollection.wrap_dom_elements(self._dom_element.children)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef parent(self):\n\t\tif self._dom_element.parentElement is _A:return\n\t\treturn Element.wrap_dom_element(self._dom_element.parentElement)\n\t@property\n\tdef style(self):return self._style\n\tdef append(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,Element):B._dom_element.appendChild(A._dom_element)\n\t\t\telif isinstance(A,ElementCollection):\n\t\t\t\tfor D in A:B._dom_element.appendChild(D._dom_element)\n\t\t\telif isinstance(A,list)or isinstance(A,tuple):\n\t\t\t\tfor E in A:B.append(E)\n\t\t\telse:\n\t\t\t\ttry:A.tagName;B._dom_element.appendChild(A)\n\t\t\t\texcept AttributeError:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tA.length\n\t\t\t\t\t\tfor F in A:B._dom_element.appendChild(F)\n\t\t\t\t\texcept AttributeError:raise TypeError(f'Element \"{A}\" is a proxy object, \"but not a valid element or a NodeList.')\n\tdef clone(B,clone_id=_A):A=Element.wrap_dom_element(B._dom_element.cloneNode(True));A.id=clone_id;return A\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(A._dom_element.querySelectorAll(selector))\n\tdef show_me(A):A._dom_element.scrollIntoView()\n\tdef update(A,classes=_A,style=_A,**D):\n\t\tC=style;B=classes\n\t\tif B:A.classes.add(B)\n\t\tif C:A.style.set(**C)\n\t\tfor(E,F)in D.items():setattr(A,E,F)\nclass Classes:\n\tdef __init__(A,element):A._element=element;A._class_list=A._element._dom_element.classList\n\tdef __contains__(A,item):return item in A._class_list\n\tdef __eq__(C,other):\n\t\tA=other\n\t\tif isinstance(A,Classes):B=list(A._class_list)\n\t\telse:\n\t\t\ttry:B=iter(A)\n\t\t\texcept TypeError:return False\n\t\treturn set(C._class_list)==set(B)\n\tdef __iter__(A):return iter(A._class_list)\n\tdef __len__(A):return A._class_list.length\n\tdef __repr__(A):return f\"Classes({\", \".join(A._class_list)})\"\n\tdef __str__(A):return' '.join(A._class_list)\n\tdef add(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.add(D)\n\t\t\telse:B._class_list.add(A)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.remove(D)\n\t\t\telse:B._class_list.remove(A)\n\tdef replace(A,old_class,new_class):A.remove(old_class);A.add(new_class)\n\tdef toggle(A,*C):\n\t\tfor B in C:\n\t\t\tif B in A:A.remove(B)\n\t\t\telse:A.add(B)\nclass HasOptions:\n\t@property\n\tdef options(self):\n\t\tA=self\n\t\tif not hasattr(A,'_options'):A._options=Options(A)\n\t\treturn A._options\nclass Options:\n\tdef __init__(A,element):A._element=element\n\tdef __getitem__(A,key):return A.options[key]\n\tdef __iter__(A):yield from A.options\n\tdef __len__(A):return len(A.options)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A)}) {A.options}\"\n\t@property\n\tdef options(self):return[Element.wrap_dom_element(A)for A in self._element._dom_element.options]\n\t@property\n\tdef selected(self):return self.options[self._element._dom_element.selectedIndex]\n\tdef add(D,value=_A,html=_A,text=_A,before=_A,**B):\n\t\tC=value;A=before\n\t\tif C is not _A:B['value']=C\n\t\tif html is not _A:B['innerHTML']=html\n\t\tif text is not _A:B['text']=text\n\t\tE=option(**B)\n\t\tif A:\n\t\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD._element._dom_element.add(E._dom_element,A)\n\tdef clear(A):\n\t\twhile len(A)>0:A.remove(0)\n\tdef remove(A,index):A._element._dom_element.remove(index)\nclass Style:\n\tdef __init__(A,element):A._element=element;A._style=A._element._dom_element.style\n\tdef __getitem__(A,key):return A._style.getPropertyValue(key)\n\tdef __setitem__(A,key,value):A._style.setProperty(key,value)\n\tdef remove(A,key):A._style.removeProperty(key)\n\tdef set(A,**B):\n\t\tfor(C,D)in B.items():A._element._dom_element.style.setProperty(C,D)\n\t@property\n\tdef visible(self):return self._element._dom_element.style.visibility\n\t@visible.setter\n\tdef visible(self,value):self._element._dom_element.style.visibility=value\nclass ContainerElement(Element):\n\tdef __init__(B,*C,children=_A,dom_element=_A,style=_A,classes=_A,**D):\n\t\tsuper().__init__(dom_element=dom_element,style=style,classes=classes,**D)\n\t\tfor A in list(C)+(children or[]):\n\t\t\tif isinstance(A,Element)or isinstance(A,ElementCollection):B.append(A)\n\t\t\telse:B._dom_element.insertAdjacentHTML('beforeend',A)\n\tdef __iter__(A):yield from A.children\nclass ClassesCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __contains__(A,class_name):\n\t\tfor B in A._collection:\n\t\t\tif class_name in B.classes:return True\n\t\treturn False\n\tdef __eq__(B,other):A=other;return isinstance(A,ClassesCollection)and B._collection==A._collection\n\tdef __iter__(A):\n\t\tfor B in A._all_class_names():yield B\n\tdef __len__(A):return len(A._all_class_names())\n\tdef __repr__(A):return f\"ClassesCollection({repr(A._collection)})\"\n\tdef __str__(A):return' '.join(A._all_class_names())\n\tdef add(A,*B):\n\t\tfor C in A._collection:C.classes.add(*B)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(A,*B):\n\t\tfor C in A._collection:C.classes.remove(*B)\n\tdef replace(A,old_class,new_class):\n\t\tfor B in A._collection:B.classes.replace(old_class,new_class)\n\tdef toggle(A,*B):\n\t\tfor C in A._collection:C.classes.toggle(*B)\n\tdef _all_class_names(B):\n\t\tA=set()\n\t\tfor C in B._collection:\n\t\t\tfor D in C.classes:A.add(D)\n\t\treturn A\nclass StyleCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __getitem__(A,key):return[A.style[key]for A in A._collection._elements]\n\tdef __setitem__(A,key,value):\n\t\tfor B in A._collection._elements:B.style[key]=value\n\tdef __repr__(A):return f\"StyleCollection({repr(A._collection)})\"\n\tdef remove(A,key):\n\t\tfor B in A._collection._elements:B.style.remove(key)\nclass ElementCollection:\n\t@classmethod\n\tdef wrap_dom_elements(A,dom_elements):return A([Element.wrap_dom_element(A)for A in dom_elements])\n\tdef __init__(A,elements):A._elements=elements;A._classes=ClassesCollection(A);A._style=StyleCollection(A)\n\tdef __eq__(A,obj):return isinstance(obj,ElementCollection)and obj._elements==A._elements\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int):return B._elements[A]\n\t\telif isinstance(A,slice):return ElementCollection(B._elements[A])\n\t\treturn B.find(A)\n\tdef __iter__(A):yield from A._elements\n\tdef __len__(A):return len(A._elements)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A._elements)}) {A._elements}\"\n\tdef __getattr__(A,name):return[getattr(A,name)for A in A._elements]\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tfor D in C._elements:setattr(D,A,B)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef elements(self):return self._elements\n\t@property\n\tdef style(self):return self._style\n\tdef find(B,selector):\n\t\tA=[]\n\t\tfor C in B._elements:A.extend(C.find(selector))\n\t\treturn ElementCollection(A)\nclass a(ContainerElement):0\nclass abbr(ContainerElement):0\nclass address(ContainerElement):0\nclass area(Element):0\nclass article(ContainerElement):0\nclass aside(ContainerElement):0\nclass audio(ContainerElement):0\nclass b(ContainerElement):0\nclass base(Element):0\nclass blockquote(ContainerElement):0\nclass body(ContainerElement):0\nclass br(Element):0\nclass button(ContainerElement):0\nclass canvas(ContainerElement):\n\tdef download(A,filename='snapped.png'):B=a(download=filename,href=A._dom_element.toDataURL());A.append(B);B._dom_element.click()\n\tdef draw(E,what,width=_A,height=_A):\n\t\tC=height;B=width;A=what\n\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD=E._dom_element.getContext('2d')\n\t\tif B or C:D.drawImage(A,0,0,B,C)\n\t\telse:D.drawImage(A,0,0)\nclass caption(ContainerElement):0\nclass cite(ContainerElement):0\nclass code(ContainerElement):0\nclass col(Element):0\nclass colgroup(ContainerElement):0\nclass data(ContainerElement):0\nclass datalist(ContainerElement,HasOptions):0\nclass dd(ContainerElement):0\nclass del_(ContainerElement):0\nclass details(ContainerElement):0\nclass dialog(ContainerElement):0\nclass div(ContainerElement):0\nclass dl(ContainerElement):0\nclass dt(ContainerElement):0\nclass em(ContainerElement):0\nclass embed(Element):0\nclass fieldset(ContainerElement):0\nclass figcaption(ContainerElement):0\nclass figure(ContainerElement):0\nclass footer(ContainerElement):0\nclass form(ContainerElement):0\nclass h1(ContainerElement):0\nclass h2(ContainerElement):0\nclass h3(ContainerElement):0\nclass h4(ContainerElement):0\nclass h5(ContainerElement):0\nclass h6(ContainerElement):0\nclass head(ContainerElement):0\nclass header(ContainerElement):0\nclass hgroup(ContainerElement):0\nclass hr(Element):0\nclass html(ContainerElement):0\nclass i(ContainerElement):0\nclass iframe(ContainerElement):0\nclass img(Element):0\nclass input_(Element):0\nclass ins(ContainerElement):0\nclass kbd(ContainerElement):0\nclass label(ContainerElement):0\nclass legend(ContainerElement):0\nclass li(ContainerElement):0\nclass link(Element):0\nclass main(ContainerElement):0\nclass map_(ContainerElement):0\nclass mark(ContainerElement):0\nclass menu(ContainerElement):0\nclass meta(ContainerElement):0\nclass meter(ContainerElement):0\nclass nav(ContainerElement):0\nclass object_(ContainerElement):0\nclass ol(ContainerElement):0\nclass optgroup(ContainerElement,HasOptions):0\nclass option(ContainerElement):0\nclass output(ContainerElement):0\nclass p(ContainerElement):0\nclass param(ContainerElement):0\nclass picture(ContainerElement):0\nclass pre(ContainerElement):0\nclass progress(ContainerElement):0\nclass q(ContainerElement):0\nclass s(ContainerElement):0\nclass script(ContainerElement):0\nclass section(ContainerElement):0\nclass select(ContainerElement,HasOptions):0\nclass small(ContainerElement):0\nclass source(Element):0\nclass span(ContainerElement):0\nclass strong(ContainerElement):0\nclass style(ContainerElement):0\nclass sub(ContainerElement):0\nclass summary(ContainerElement):0\nclass sup(ContainerElement):0\nclass table(ContainerElement):0\nclass tbody(ContainerElement):0\nclass td(ContainerElement):0\nclass template(ContainerElement):0\nclass textarea(ContainerElement):0\nclass tfoot(ContainerElement):0\nclass th(ContainerElement):0\nclass thead(ContainerElement):0\nclass time(ContainerElement):0\nclass title(ContainerElement):0\nclass tr(ContainerElement):0\nclass track(Element):0\nclass u(ContainerElement):0\nclass ul(ContainerElement):0\nclass var(ContainerElement):0\nclass video(ContainerElement):\n\tdef snap(D,to=_A,width=_A,height=_A):\n\t\tG='CANVAS';F='Element to snap to must be a canvas.';C=height;B=width;A=to;B=B if B is not _A else D.videoWidth;C=C if C is not _A else D.videoHeight\n\t\tif A is _A:A=canvas(width=B,height=C)\n\t\telif isinstance(A,Element):\n\t\t\tif A.tag!='canvas':raise TypeError(F)\n\t\telif getattr(A,'tagName','')==G:A=canvas(dom_element=A)\n\t\telif isinstance(A,str):\n\t\t\tE=document.querySelectorAll(A)\n\t\t\tif E.length==0:raise TypeError('No element with selector {to} to snap to.')\n\t\t\tif E[0].tagName!=G:raise TypeError(F)\n\t\t\tA=canvas(dom_element=E[0])\n\t\tA.draw(D,B,C);return A\nclass wbr(Element):0\nELEMENT_CLASSES=[a,abbr,address,area,article,aside,audio,b,base,blockquote,body,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,dd,del_,details,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,img,input_,ins,kbd,label,legend,li,link,main,map_,mark,menu,meta,meter,nav,object_,ol,optgroup,option,output,p,param,picture,pre,progress,q,s,script,section,select,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,u,ul,var,video,wbr]\nElement.register_element_classes(ELEMENT_CLASSES)\nclass Page:\n\tdef __init__(A):A.html=Element.wrap_dom_element(document.documentElement);A.body=Element.wrap_dom_element(document.body);A.head=Element.wrap_dom_element(document.head)\n\tdef __getitem__(A,selector):return A.find(selector)\n\t@property\n\tdef title(self):return document.title\n\t@title.setter\n\tdef title(self,value):document.title=value\n\tdef append(A,*B):A.body.append(*B)\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(document.querySelectorAll(selector))\npage=Page()",
13
+ "util.py": "import js,sys,inspect\ndef as_bytearray(buffer):\n\tA=js.Uint8Array.new(buffer);B=A.length;C=bytearray(B)\n\tfor D in range(0,B):C[D]=A[D]\n\treturn C\nclass NotSupported:\n\tdef __init__(A,name,error):object.__setattr__(A,'name',name);object.__setattr__(A,'error',error)\n\tdef __repr__(A):return f\"<NotSupported {A.name} [{A.error}]>\"\n\tdef __getattr__(A,attr):raise AttributeError(A.error)\n\tdef __setattr__(A,attr,value):raise AttributeError(A.error)\n\tdef __call__(A,*B):raise TypeError(A.error)\ndef is_awaitable(obj):\n\tA=obj;from pyscript import config as B\n\tif B['type']=='mpy':\n\t\tif'<closure <generator>'in repr(A):return True\n\t\treturn inspect.isgeneratorfunction(A)\n\treturn inspect.iscoroutinefunction(A)",
14
+ "web.py": "_B='on_'\n_A=None\nfrom pyscript import document,when,Event\nfrom pyscript.ffi import create_proxy\ndef wrap_dom_element(dom_element):return Element.wrap_dom_element(dom_element)\nclass Element:\n\telement_classes_by_tag_name={}\n\t@classmethod\n\tdef get_tag_name(A):return A.__name__.replace('_','')\n\t@classmethod\n\tdef register_element_classes(B,element_classes):\n\t\tfor A in element_classes:C=A.get_tag_name();B.element_classes_by_tag_name[C]=A\n\t@classmethod\n\tdef unregister_element_classes(A,element_classes):\n\t\tfor B in element_classes:C=B.get_tag_name();A.element_classes_by_tag_name.pop(C,_A)\n\t@classmethod\n\tdef wrap_dom_element(A,dom_element):B=dom_element;C=A.element_classes_by_tag_name.get(B.tagName.lower(),A);return C(dom_element=B)\n\tdef __init__(A,dom_element=_A,classes=_A,style=_A,**E):\n\t\tA._dom_element=dom_element or document.createElement(type(A).get_tag_name());A._on_events={};C={}\n\t\tfor(B,D)in E.items():\n\t\t\tif B.startswith(_B):F=A.get_event(B);F.add_listener(D)\n\t\t\telse:C[B]=D\n\t\tA._classes=Classes(A);A._style=Style(A);A.update(classes=classes,style=style,**C)\n\tdef __eq__(A,obj):return isinstance(obj,Element)and obj._dom_element==A._dom_element\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int)or isinstance(A,slice):return B.children[A]\n\t\treturn B.find(A)\n\tdef __getattr__(B,name):\n\t\tA=name\n\t\tif A.startswith(_B):return B.get_event(A)\n\t\tif A.endswith('_'):A=A[:-1]\n\t\treturn getattr(B._dom_element,A)\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tif A.endswith('_'):A=A[:-1]\n\t\t\tif A.startswith(_B):C._on_events[A]=B\n\t\t\tsetattr(C._dom_element,A,B)\n\tdef get_event(A,name):\n\t\tB=name\n\t\tif not B.startswith(_B):raise ValueError(\"Event names must start with 'on_'.\")\n\t\tC=B[3:]\n\t\tif not hasattr(A._dom_element,C):raise ValueError(f\"Element has no '{C}' event.\")\n\t\tif B in A._on_events:return A._on_events[B]\n\t\tD=Event();A._on_events[B]=D;A._dom_element.addEventListener(C,create_proxy(D.trigger));return D\n\t@property\n\tdef children(self):return ElementCollection.wrap_dom_elements(self._dom_element.children)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef parent(self):\n\t\tif self._dom_element.parentElement is _A:return\n\t\treturn Element.wrap_dom_element(self._dom_element.parentElement)\n\t@property\n\tdef style(self):return self._style\n\tdef append(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,Element):B._dom_element.appendChild(A._dom_element)\n\t\t\telif isinstance(A,ElementCollection):\n\t\t\t\tfor D in A:B._dom_element.appendChild(D._dom_element)\n\t\t\telif isinstance(A,list)or isinstance(A,tuple):\n\t\t\t\tfor E in A:B.append(E)\n\t\t\telse:\n\t\t\t\ttry:A.tagName;B._dom_element.appendChild(A)\n\t\t\t\texcept AttributeError:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tA.length\n\t\t\t\t\t\tfor F in A:B._dom_element.appendChild(F)\n\t\t\t\t\texcept AttributeError:raise TypeError(f'Element \"{A}\" is a proxy object, \"but not a valid element or a NodeList.')\n\tdef clone(B,clone_id=_A):A=Element.wrap_dom_element(B._dom_element.cloneNode(True));A.id=clone_id;return A\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(A._dom_element.querySelectorAll(selector))\n\tdef show_me(A):A._dom_element.scrollIntoView()\n\tdef update(A,classes=_A,style=_A,**D):\n\t\tC=style;B=classes\n\t\tif B:A.classes.add(B)\n\t\tif C:A.style.set(**C)\n\t\tfor(E,F)in D.items():setattr(A,E,F)\nclass Classes:\n\tdef __init__(A,element):A._element=element;A._class_list=A._element._dom_element.classList\n\tdef __contains__(A,item):return item in A._class_list\n\tdef __eq__(C,other):\n\t\tA=other\n\t\tif isinstance(A,Classes):B=list(A._class_list)\n\t\telse:\n\t\t\ttry:B=iter(A)\n\t\t\texcept TypeError:return False\n\t\treturn set(C._class_list)==set(B)\n\tdef __iter__(A):return iter(A._class_list)\n\tdef __len__(A):return A._class_list.length\n\tdef __repr__(A):return f\"Classes({\", \".join(A._class_list)})\"\n\tdef __str__(A):return' '.join(A._class_list)\n\tdef add(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.add(D)\n\t\t\telse:B._class_list.add(A)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.remove(D)\n\t\t\telse:B._class_list.remove(A)\n\tdef replace(A,old_class,new_class):A.remove(old_class);A.add(new_class)\n\tdef toggle(A,*C):\n\t\tfor B in C:\n\t\t\tif B in A:A.remove(B)\n\t\t\telse:A.add(B)\nclass HasOptions:\n\t@property\n\tdef options(self):\n\t\tA=self\n\t\tif not hasattr(A,'_options'):A._options=Options(A)\n\t\treturn A._options\nclass Options:\n\tdef __init__(A,element):A._element=element\n\tdef __getitem__(A,key):return A.options[key]\n\tdef __iter__(A):yield from A.options\n\tdef __len__(A):return len(A.options)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A)}) {A.options}\"\n\t@property\n\tdef options(self):return[Element.wrap_dom_element(A)for A in self._element._dom_element.options]\n\t@property\n\tdef selected(self):return self.options[self._element._dom_element.selectedIndex]\n\tdef add(D,value=_A,html=_A,text=_A,before=_A,**B):\n\t\tC=value;A=before\n\t\tif C is not _A:B['value']=C\n\t\tif html is not _A:B['innerHTML']=html\n\t\tif text is not _A:B['text']=text\n\t\tE=option(**B)\n\t\tif A:\n\t\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD._element._dom_element.add(E._dom_element,A)\n\tdef clear(A):\n\t\twhile len(A)>0:A.remove(0)\n\tdef remove(A,index):A._element._dom_element.remove(index)\nclass Style:\n\tdef __init__(A,element):A._element=element;A._style=A._element._dom_element.style\n\tdef __getitem__(A,key):return A._style.getPropertyValue(key)\n\tdef __setitem__(A,key,value):A._style.setProperty(key,value)\n\tdef remove(A,key):A._style.removeProperty(key)\n\tdef set(A,**B):\n\t\tfor(C,D)in B.items():A._element._dom_element.style.setProperty(C,D)\n\t@property\n\tdef visible(self):return self._element._dom_element.style.visibility\n\t@visible.setter\n\tdef visible(self,value):self._element._dom_element.style.visibility=value\nclass ContainerElement(Element):\n\tdef __init__(B,*C,children=_A,dom_element=_A,style=_A,classes=_A,**D):\n\t\tsuper().__init__(dom_element=dom_element,style=style,classes=classes,**D)\n\t\tfor A in list(C)+(children or[]):\n\t\t\tif isinstance(A,Element)or isinstance(A,ElementCollection):B.append(A)\n\t\t\telse:B._dom_element.insertAdjacentHTML('beforeend',A)\n\tdef __iter__(A):yield from A.children\nclass ClassesCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __contains__(A,class_name):\n\t\tfor B in A._collection:\n\t\t\tif class_name in B.classes:return True\n\t\treturn False\n\tdef __eq__(B,other):A=other;return isinstance(A,ClassesCollection)and B._collection==A._collection\n\tdef __iter__(A):\n\t\tfor B in A._all_class_names():yield B\n\tdef __len__(A):return len(A._all_class_names())\n\tdef __repr__(A):return f\"ClassesCollection({repr(A._collection)})\"\n\tdef __str__(A):return' '.join(A._all_class_names())\n\tdef add(A,*B):\n\t\tfor C in A._collection:C.classes.add(*B)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(A,*B):\n\t\tfor C in A._collection:C.classes.remove(*B)\n\tdef replace(A,old_class,new_class):\n\t\tfor B in A._collection:B.classes.replace(old_class,new_class)\n\tdef toggle(A,*B):\n\t\tfor C in A._collection:C.classes.toggle(*B)\n\tdef _all_class_names(B):\n\t\tA=set()\n\t\tfor C in B._collection:\n\t\t\tfor D in C.classes:A.add(D)\n\t\treturn A\nclass StyleCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __getitem__(A,key):return[A.style[key]for A in A._collection._elements]\n\tdef __setitem__(A,key,value):\n\t\tfor B in A._collection._elements:B.style[key]=value\n\tdef __repr__(A):return f\"StyleCollection({repr(A._collection)})\"\n\tdef remove(A,key):\n\t\tfor B in A._collection._elements:B.style.remove(key)\nclass ElementCollection:\n\t@classmethod\n\tdef wrap_dom_elements(A,dom_elements):return A([Element.wrap_dom_element(A)for A in dom_elements])\n\tdef __init__(A,elements):A._elements=elements;A._classes=ClassesCollection(A);A._style=StyleCollection(A)\n\tdef __eq__(A,obj):return isinstance(obj,ElementCollection)and obj._elements==A._elements\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int):return B._elements[A]\n\t\telif isinstance(A,slice):return ElementCollection(B._elements[A])\n\t\treturn B.find(A)\n\tdef __iter__(A):yield from A._elements\n\tdef __len__(A):return len(A._elements)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A._elements)}) {A._elements}\"\n\tdef __getattr__(A,name):return[getattr(A,name)for A in A._elements]\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tfor D in C._elements:setattr(D,A,B)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef elements(self):return self._elements\n\t@property\n\tdef style(self):return self._style\n\tdef find(B,selector):\n\t\tA=[]\n\t\tfor C in B._elements:A.extend(C.find(selector))\n\t\treturn ElementCollection(A)\nclass a(ContainerElement):0\nclass abbr(ContainerElement):0\nclass address(ContainerElement):0\nclass area(Element):0\nclass article(ContainerElement):0\nclass aside(ContainerElement):0\nclass audio(ContainerElement):0\nclass b(ContainerElement):0\nclass base(Element):0\nclass blockquote(ContainerElement):0\nclass body(ContainerElement):0\nclass br(Element):0\nclass button(ContainerElement):0\nclass canvas(ContainerElement):\n\tdef download(A,filename='snapped.png'):B=a(download=filename,href=A._dom_element.toDataURL());A.append(B);B._dom_element.click()\n\tdef draw(E,what,width=_A,height=_A):\n\t\tC=height;B=width;A=what\n\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD=E._dom_element.getContext('2d')\n\t\tif B or C:D.drawImage(A,0,0,B,C)\n\t\telse:D.drawImage(A,0,0)\nclass caption(ContainerElement):0\nclass cite(ContainerElement):0\nclass code(ContainerElement):0\nclass col(Element):0\nclass colgroup(ContainerElement):0\nclass data(ContainerElement):0\nclass datalist(ContainerElement,HasOptions):0\nclass dd(ContainerElement):0\nclass del_(ContainerElement):0\nclass details(ContainerElement):0\nclass dialog(ContainerElement):0\nclass div(ContainerElement):0\nclass dl(ContainerElement):0\nclass dt(ContainerElement):0\nclass em(ContainerElement):0\nclass embed(Element):0\nclass fieldset(ContainerElement):0\nclass figcaption(ContainerElement):0\nclass figure(ContainerElement):0\nclass footer(ContainerElement):0\nclass form(ContainerElement):0\nclass h1(ContainerElement):0\nclass h2(ContainerElement):0\nclass h3(ContainerElement):0\nclass h4(ContainerElement):0\nclass h5(ContainerElement):0\nclass h6(ContainerElement):0\nclass head(ContainerElement):0\nclass header(ContainerElement):0\nclass hgroup(ContainerElement):0\nclass hr(Element):0\nclass html(ContainerElement):0\nclass i(ContainerElement):0\nclass iframe(ContainerElement):0\nclass img(Element):0\nclass input_(Element):0\nclass ins(ContainerElement):0\nclass kbd(ContainerElement):0\nclass label(ContainerElement):0\nclass legend(ContainerElement):0\nclass li(ContainerElement):0\nclass link(Element):0\nclass main(ContainerElement):0\nclass map_(ContainerElement):0\nclass mark(ContainerElement):0\nclass menu(ContainerElement):0\nclass meta(ContainerElement):0\nclass meter(ContainerElement):0\nclass nav(ContainerElement):0\nclass object_(ContainerElement):0\nclass ol(ContainerElement):0\nclass optgroup(ContainerElement,HasOptions):0\nclass option(ContainerElement):0\nclass output(ContainerElement):0\nclass p(ContainerElement):0\nclass param(ContainerElement):0\nclass picture(ContainerElement):0\nclass pre(ContainerElement):0\nclass progress(ContainerElement):0\nclass q(ContainerElement):0\nclass s(ContainerElement):0\nclass script(ContainerElement):0\nclass section(ContainerElement):0\nclass select(ContainerElement,HasOptions):0\nclass small(ContainerElement):0\nclass source(Element):0\nclass span(ContainerElement):0\nclass strong(ContainerElement):0\nclass style(ContainerElement):0\nclass sub(ContainerElement):0\nclass summary(ContainerElement):0\nclass sup(ContainerElement):0\nclass table(ContainerElement):0\nclass tbody(ContainerElement):0\nclass td(ContainerElement):0\nclass template(ContainerElement):0\nclass textarea(ContainerElement):0\nclass tfoot(ContainerElement):0\nclass th(ContainerElement):0\nclass thead(ContainerElement):0\nclass time(ContainerElement):0\nclass title(ContainerElement):0\nclass tr(ContainerElement):0\nclass track(Element):0\nclass u(ContainerElement):0\nclass ul(ContainerElement):0\nclass var(ContainerElement):0\nclass video(ContainerElement):\n\tdef snap(D,to=_A,width=_A,height=_A):\n\t\tG='CANVAS';F='Element to snap to must be a canvas.';C=height;B=width;A=to;B=B if B is not _A else D.videoWidth;C=C if C is not _A else D.videoHeight\n\t\tif A is _A:A=canvas(width=B,height=C)\n\t\telif isinstance(A,Element):\n\t\t\tif A.tag!='canvas':raise TypeError(F)\n\t\telif getattr(A,'tagName','')==G:A=canvas(dom_element=A)\n\t\telif isinstance(A,str):\n\t\t\tE=document.querySelectorAll(A)\n\t\t\tif E.length==0:raise TypeError('No element with selector {to} to snap to.')\n\t\t\tif E[0].tagName!=G:raise TypeError(F)\n\t\t\tA=canvas(dom_element=E[0])\n\t\tA.draw(D,B,C);return A\nclass wbr(Element):0\nELEMENT_CLASSES=[a,abbr,address,area,article,aside,audio,b,base,blockquote,body,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,dd,del_,details,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,img,input_,ins,kbd,label,legend,li,link,main,map_,mark,menu,meta,meter,nav,object_,ol,optgroup,option,output,p,param,picture,pre,progress,q,s,script,section,select,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,u,ul,var,video,wbr]\nElement.register_element_classes(ELEMENT_CLASSES)\nclass Page:\n\tdef __init__(A):A.html=Element.wrap_dom_element(document.documentElement);A.body=Element.wrap_dom_element(document.body);A.head=Element.wrap_dom_element(document.head)\n\tdef __getitem__(A,selector):return A.find(selector)\n\t@property\n\tdef title(self):return document.title\n\t@title.setter\n\tdef title(self,value):document.title=value\n\tdef append(A,*B):A.body.append(*B)\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(document.querySelectorAll(selector))\npage=Page()",
15
15
  "websocket.py": "import js\nfrom pyscript.ffi import create_proxy\nfrom pyscript.util import as_bytearray\ncode='code'\nprotocols='protocols'\nreason='reason'\nmethods=['onclose','onerror','onmessage','onopen']\nclass EventMessage:\n\tdef __init__(A,event):A._event=event\n\tdef __getattr__(B,attr):\n\t\tA=getattr(B._event,attr)\n\t\tif attr=='data'and not isinstance(A,str):\n\t\t\tif hasattr(A,'to_py'):return A.to_py()\n\t\t\treturn memoryview(as_bytearray(A))\n\t\treturn A\nclass WebSocket:\n\tCONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3\n\tdef __init__(E,**A):\n\t\tD=A['url']\n\t\tif protocols in A:B=js.WebSocket.new(D,A[protocols])\n\t\telse:B=js.WebSocket.new(D)\n\t\tobject.__setattr__(E,'_ws',B)\n\t\tfor C in methods:\n\t\t\tif C in A:setattr(B,C,create_proxy(A[C]))\n\tdef __getattr__(A,attr):return getattr(A._ws,attr)\n\tdef __setattr__(B,attr,value):\n\t\tC=value;A=attr\n\t\tif A in methods:D=lambda e:C(EventMessage(e));setattr(B._ws,A,create_proxy(D))\n\t\telse:setattr(B._ws,A,C)\n\tdef close(B,**A):\n\t\tif code in A and reason in A:B._ws.close(A[code],A[reason])\n\t\telif code in A:B._ws.close(A[code])\n\t\telse:B._ws.close()\n\tdef send(B,data):\n\t\tA=data\n\t\tif isinstance(A,str):B._ws.send(A)\n\t\telse:\n\t\t\tC=js.Uint8Array.new(len(A))\n\t\t\tfor(D,E)in enumerate(A):C[D]=E\n\t\t\tB._ws.send(C)",
16
16
  "workers.py": "import js as _js\nfrom polyscript import workers as _workers\n_get=_js.Reflect.get\ndef _set(script,name,value=''):script.setAttribute(name,value)\nclass _ReadOnlyProxy:\n\tdef __getitem__(A,name):return _get(_workers,name)\n\tdef __getattr__(A,name):return _get(_workers,name)\nworkers=_ReadOnlyProxy()\nasync def create_named_worker(src='',name='',config=None,type='py'):\n\tC=name;B=config;from json import dumps\n\tif not src:raise ValueError('Named workers require src')\n\tif not C:raise ValueError('Named workers require a name')\n\tA=_js.document.createElement('script');A.type=type;A.src=src;_set(A,'worker');_set(A,'name',C)\n\tif B:_set(A,'config',isinstance(B,str)and B or dumps(B))\n\t_js.document.body.append(A);return await workers[C]"
17
17
  }
@@ -1,6 +1,6 @@
1
- declare var b: any;
2
- declare var I: boolean;
3
- declare namespace r {
1
+ declare var v: any;
2
+ declare var k: boolean;
3
+ declare namespace i {
4
4
  export let __esModule: boolean;
5
5
  export { Readline };
6
6
  }
@@ -57,7 +57,7 @@ declare class Readline {
57
57
  highlighter: any;
58
58
  history: any;
59
59
  promptSize: any;
60
- layout: p;
60
+ layout: c;
61
61
  buffer(): string;
62
62
  shouldHighlight(): boolean;
63
63
  clearScreen(): void;
@@ -124,15 +124,15 @@ declare class Readline {
124
124
  readPaste(t: any): void;
125
125
  readKey(t: any): void;
126
126
  }
127
- declare class p {
127
+ declare class c {
128
128
  constructor(t: any);
129
129
  promptSize: any;
130
- cursor: c;
131
- end: c;
130
+ cursor: u;
131
+ end: u;
132
132
  }
133
- declare class c {
133
+ declare class u {
134
134
  constructor(t: any, e: any);
135
135
  row: any;
136
136
  col: any;
137
137
  }
138
- export { b as Readline, I as __esModule, r as default };
138
+ export { v as Readline, k as __esModule, i as default };
@@ -1,4 +1,4 @@
1
- declare var i: any;
2
- declare var s: any;
3
- declare var t: {};
4
- export { i as Terminal, s as __esModule, t as default };
1
+ declare var D: any;
2
+ declare var R: any;
3
+ declare var L: {};
4
+ export { D as Terminal, R as __esModule, L as default };
@@ -2,7 +2,7 @@ declare namespace _default {
2
2
  let pyscript: {
3
3
  "__init__.py": string;
4
4
  "display.py": string;
5
- "event_handling.py": string;
5
+ "events.py": string;
6
6
  "fetch.py": string;
7
7
  "ffi.py": string;
8
8
  "flatted.py": string;
@@ -1,2 +0,0 @@
1
- import{codePointSize as t,codePointAt as e,EditorSelection as o,CharCategory as i,Prec as n,Facet as s,combineConfig as l,StateField as r,StateEffect as a,MapMode as c,RangeValue as h,RangeSet as p,fromCodePoint as f,Annotation as u,Text as d,Transaction as m}from"./codemirror_state-1d1uncXx.js";import{E as g,k as v,D as b,s as w,g as y,V as x,l as C,a as I,W as O}from"./codemirror_view-epWNLlvw.js";import{s as k,i as D}from"./codemirror_language-BXIPubDH.js";class T{constructor(t,e,o,i){this.state=t,this.pos=e,this.explicit=o,this.view=i,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(t){let e=k(this.state).resolveInner(this.pos,-1);for(;e&&t.indexOf(e.name)<0;)e=e.parent;return e?{from:e.from,to:this.pos,text:this.state.sliceDoc(e.from,this.pos),type:e.type}:null}matchBefore(t){let e=this.state.doc.lineAt(this.pos),o=Math.max(e.from,this.pos-250),i=e.text.slice(o-e.from,this.pos-e.from),n=i.search(P(t,!1));return n<0?null:{from:o+n,to:this.pos,text:i.slice(n)}}get aborted(){return null==this.abortListeners}addEventListener(t,e,o){"abort"==t&&this.abortListeners&&(this.abortListeners.push(e),o&&o.onDocChange&&(this.abortOnDocChange=!0))}}function S(t){let e=Object.keys(t).join(""),o=/\w/.test(e);return o&&(e=e.replace(/\w/g,"")),`[${o?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function A(t){let e=t.map((t=>"string"==typeof t?{label:t}:t)),[o,i]=e.every((t=>/^\w+$/.test(t.label)))?[/\w*$/,/\w+$/]:function(t){let e=Object.create(null),o=Object.create(null);for(let{label:i}of t){e[i[0]]=!0;for(let t=1;t<i.length;t++)o[i[t]]=!0}let i=S(e)+S(o)+"*$";return[new RegExp("^"+i),new RegExp(i)]}(e);return t=>{let n=t.matchBefore(i);return n||t.explicit?{from:n?n.from:t.pos,options:e,validFor:o}:null}}function L(t,e){return o=>{for(let e=k(o.state).resolveInner(o.pos,-1);e;e=e.parent){if(t.indexOf(e.name)>-1)return null;if(e.type.isTop)break}return e(o)}}class R{constructor(t,e,o,i){this.completion=t,this.source=e,this.match=o,this.score=i}}function E(t){return t.selection.main.from}function P(t,e){var o;let{source:i}=t,n=e&&"^"!=i[0],s="$"!=i[i.length-1];return n||s?new RegExp(`${n?"^":""}(?:${i})${s?"$":""}`,null!==(o=t.flags)&&void 0!==o?o:t.ignoreCase?"i":""):t}const M=u.define();const B=new WeakMap;function F(t){if(!Array.isArray(t))return t;let e=B.get(t);return e||B.set(t,e=A(t)),e}const j=a.define(),$=a.define();class N{constructor(o){this.pattern=o,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let i=0;i<o.length;){let n=e(o,i),s=t(n);this.chars.push(n);let l=o.slice(i,i+s),r=l.toUpperCase();this.folded.push(e(r==l?l.toLowerCase():r,0)),i+=s}this.astral=o.length!=this.chars.length}ret(t,e){return this.score=t,this.matched=e,this}match(o){if(0==this.pattern.length)return this.ret(-100,[]);if(o.length<this.pattern.length)return null;let{chars:i,folded:n,any:s,precise:l,byWord:r}=this;if(1==i.length){let s=e(o,0),l=t(s),r=l==o.length?0:-100;if(s==i[0]);else{if(s!=n[0])return null;r+=-200}return this.ret(r,[0,l])}let a=o.indexOf(this.pattern);if(0==a)return this.ret(o.length==this.pattern.length?0:-100,[0,this.pattern.length]);let c=i.length,h=0;if(a<0){for(let l=0,r=Math.min(o.length,200);l<r&&h<c;){let r=e(o,l);r!=i[h]&&r!=n[h]||(s[h++]=l),l+=t(r)}if(h<c)return null}let p=0,u=0,d=!1,m=0,g=-1,v=-1,b=/[a-z]/.test(o),w=!0;for(let s=0,h=Math.min(o.length,200),y=0;s<h&&u<c;){let h=e(o,s);a<0&&(p<c&&h==i[p]&&(l[p++]=s),m<c&&(h==i[m]||h==n[m]?(0==m&&(g=s),v=s+1,m++):m=0));let x,C=h<255?h>=48&&h<=57||h>=97&&h<=122?2:h>=65&&h<=90?1:0:(x=f(h))!=x.toLowerCase()?1:x!=x.toUpperCase()?2:0;(!s||1==C&&b||0==y&&0!=C)&&(i[u]==h||n[u]==h&&(d=!0)?r[u++]=s:r.length&&(w=!1)),y=C,s+=t(h)}return u==c&&0==r[0]&&w?this.result((d?-200:0)-100,r,o):m==c&&0==g?this.ret(-200-o.length+(v==o.length?0:-100),[0,v]):a>-1?this.ret(-700-o.length,[a,a+this.pattern.length]):m==c?this.ret(-900-o.length,[g,v]):u==c?this.result((d?-200:0)-100-700+(w?0:-1100),r,o):2==i.length?null:this.result((s[0]?-700:0)-200-1100,s,o)}result(o,i,n){let s=[],l=0;for(let o of i){let i=o+(this.astral?t(e(n,o)):1);l&&s[l-1]==o?s[l-1]=i:(s[l++]=o,s[l++]=i)}return this.ret(o-n.length,s)}}class U{constructor(t){this.pattern=t,this.matched=[],this.score=0,this.folded=t.toLowerCase()}match(t){if(t.length<this.pattern.length)return null;let e=t.slice(0,this.pattern.length),o=e==this.pattern?0:e.toLowerCase()==this.folded?-200:null;return null==o?null:(this.matched=[0,e.length],this.score=o+(t.length==this.pattern.length?0:-100),this)}}const W=s.define({combine:t=>l(t,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:H,filterStrict:!1,compareCompletions:(t,e)=>t.label.localeCompare(e.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(t,e)=>t&&e,closeOnBlur:(t,e)=>t&&e,icons:(t,e)=>t&&e,tooltipClass:(t,e)=>o=>q(t(o),e(o)),optionClass:(t,e)=>o=>q(t(o),e(o)),addToOptions:(t,e)=>t.concat(e),filterStrict:(t,e)=>t||e})});function q(t,e){return t?e?t+" "+e:t:e}function H(t,e,o,i,n,s){let l,r,a=t.textDirection==b.RTL,c=a,h=!1,p="top",f=e.left-n.left,u=n.right-e.right,d=i.right-i.left,m=i.bottom-i.top;if(c&&f<Math.min(d,u)?c=!1:!c&&u<Math.min(d,f)&&(c=!0),d<=(c?f:u))l=Math.max(n.top,Math.min(o.top,n.bottom-m))-e.top,r=Math.min(400,c?f:u);else{h=!0,r=Math.min(400,(a?e.right:n.right-e.left)-30);let t=n.bottom-e.bottom;t>=m||t>e.top?l=o.bottom-e.top:(p="bottom",l=e.bottom-o.top)}return{style:`${p}: ${l/((e.bottom-e.top)/s.offsetHeight)}px; max-width: ${r/((e.right-e.left)/s.offsetWidth)}px`,class:"cm-completionInfo-"+(h?a?"left-narrow":"right-narrow":c?"left":"right")}}function V(t,e,o){if(t<=o)return{from:0,to:t};if(e<0&&(e=0),e<=t>>1){let t=Math.floor(e/o);return{from:t*o,to:(t+1)*o}}let i=Math.floor((t-e)/o);return{from:t-(i+1)*o,to:t-i*o}}class z{constructor(t,e,o){this.view=t,this.stateField=e,this.applyCompletion=o,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:t=>this.placeInfo(t),key:this},this.space=null,this.currentClass="";let i=t.state.field(e),{options:n,selected:s}=i.open,l=t.state.facet(W);this.optionContent=function(t){let e=t.addToOptions.slice();return t.icons&&e.push({render(t){let e=document.createElement("div");return e.classList.add("cm-completionIcon"),t.type&&e.classList.add(...t.type.split(/\s+/g).map((t=>"cm-completionIcon-"+t))),e.setAttribute("aria-hidden","true"),e},position:20}),e.push({render(t,e,o,i){let n=document.createElement("span");n.className="cm-completionLabel";let s=t.displayLabel||t.label,l=0;for(let t=0;t<i.length;){let e=i[t++],o=i[t++];e>l&&n.appendChild(document.createTextNode(s.slice(l,e)));let r=n.appendChild(document.createElement("span"));r.appendChild(document.createTextNode(s.slice(e,o))),r.className="cm-completionMatchedText",l=o}return l<s.length&&n.appendChild(document.createTextNode(s.slice(l))),n},position:50},{render(t){if(!t.detail)return null;let e=document.createElement("span");return e.className="cm-completionDetail",e.textContent=t.detail,e},position:80}),e.sort(((t,e)=>t.position-e.position)).map((t=>t.render))}(l),this.optionClass=l.optionClass,this.tooltipClass=l.tooltipClass,this.range=V(n.length,s,l.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(t.state),this.dom.addEventListener("mousedown",(o=>{let{options:i}=t.state.field(e).open;for(let e,n=o.target;n&&n!=this.dom;n=n.parentNode)if("LI"==n.nodeName&&(e=/-(\d+)$/.exec(n.id))&&+e[1]<i.length)return this.applyCompletion(t,i[+e[1]]),void o.preventDefault()})),this.dom.addEventListener("focusout",(e=>{let o=t.state.field(this.stateField,!1);o&&o.tooltip&&t.state.facet(W).closeOnBlur&&e.relatedTarget!=t.contentDOM&&t.dispatch({effects:$.of(null)})})),this.showOptions(n,i.id)}mount(){this.updateSel()}showOptions(t,e){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(t,e,this.range)),this.list.addEventListener("scroll",(()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)}))}update(t){var e;let o=t.state.field(this.stateField),i=t.startState.field(this.stateField);if(this.updateTooltipClass(t.state),o!=i){let{options:n,selected:s,disabled:l}=o.open;i.open&&i.open.options==n||(this.range=V(n.length,s,t.state.facet(W).maxRenderedOptions),this.showOptions(n,o.id)),this.updateSel(),l!=(null===(e=i.open)||void 0===e?void 0:e.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!l)}}updateTooltipClass(t){let e=this.tooltipClass(t);if(e!=this.currentClass){for(let t of this.currentClass.split(" "))t&&this.dom.classList.remove(t);for(let t of e.split(" "))t&&this.dom.classList.add(t);this.currentClass=e}}positioned(t){this.space=t,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let t=this.view.state.field(this.stateField),e=t.open;if((e.selected>-1&&e.selected<this.range.from||e.selected>=this.range.to)&&(this.range=V(e.options.length,e.selected,this.view.state.facet(W).maxRenderedOptions),this.showOptions(e.options,t.id)),this.updateSelectedOption(e.selected)){this.destroyInfo();let{completion:o}=e.options[e.selected],{info:i}=o;if(!i)return;let n="string"==typeof i?document.createTextNode(i):i(o);if(!n)return;"then"in n?n.then((e=>{e&&this.view.state.field(this.stateField,!1)==t&&this.addInfoPane(e,o)})).catch((t=>C(this.view.state,t,"completion info"))):this.addInfoPane(n,o)}}addInfoPane(t,e){this.destroyInfo();let o=this.info=document.createElement("div");if(o.className="cm-tooltip cm-completionInfo",null!=t.nodeType)o.appendChild(t),this.infoDestroy=null;else{let{dom:e,destroy:i}=t;o.appendChild(e),this.infoDestroy=i||null}this.dom.appendChild(o),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(t){let e=null;for(let o=this.list.firstChild,i=this.range.from;o;o=o.nextSibling,i++)"LI"==o.nodeName&&o.id?i==t?o.hasAttribute("aria-selected")||(o.setAttribute("aria-selected","true"),e=o):o.hasAttribute("aria-selected")&&o.removeAttribute("aria-selected"):i--;return e&&function(t,e){let o=t.getBoundingClientRect(),i=e.getBoundingClientRect(),n=o.height/t.offsetHeight;i.top<o.top?t.scrollTop-=(o.top-i.top)/n:i.bottom>o.bottom&&(t.scrollTop+=(i.bottom-o.bottom)/n)}(this.list,e),e}measureInfo(){let t=this.dom.querySelector("[aria-selected]");if(!t||!this.info)return null;let e=this.dom.getBoundingClientRect(),o=this.info.getBoundingClientRect(),i=t.getBoundingClientRect(),n=this.space;if(!n){let t=this.dom.ownerDocument.defaultView||window;n={left:0,top:0,right:t.innerWidth,bottom:t.innerHeight}}return i.top>Math.min(n.bottom,e.bottom)-10||i.bottom<Math.max(n.top,e.top)+10?null:this.view.state.facet(W).positionInfo(this.view,e,i,o,n,this.dom)}placeInfo(t){this.info&&(t?(t.style&&(this.info.style.cssText=t.style),this.info.className="cm-tooltip cm-completionInfo "+(t.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(t,e,o){const i=document.createElement("ul");i.id=e,i.setAttribute("role","listbox"),i.setAttribute("aria-expanded","true"),i.setAttribute("aria-label",this.view.state.phrase("Completions"));let n=null;for(let s=o.from;s<o.to;s++){let{completion:l,match:r}=t[s],{section:a}=l;if(a){let t="string"==typeof a?a:a.name;if(t!=n&&(s>o.from||0==o.from))if(n=t,"string"!=typeof a&&a.header)i.appendChild(a.header(a));else{i.appendChild(document.createElement("completion-section")).textContent=t}}const c=i.appendChild(document.createElement("li"));c.id=e+"-"+s,c.setAttribute("role","option");let h=this.optionClass(l);h&&(c.className=h);for(let t of this.optionContent){let e=t(l,this.view.state,this.view,r);e&&c.appendChild(e)}}return o.from&&i.classList.add("cm-completionListIncompleteTop"),o.to<t.length&&i.classList.add("cm-completionListIncompleteBottom"),i}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}}function K(t,e){return o=>new z(o,t,e)}function Q(t){return 100*(t.boost||0)+(t.apply?10:0)+(t.info?5:0)+(t.type?1:0)}class _{constructor(t,e,o,i,n,s){this.options=t,this.attrs=e,this.tooltip=o,this.timestamp=i,this.selected=n,this.disabled=s}setSelected(t,e){return t==this.selected||t>=this.options.length?this:new _(this.options,J(e,t),this.tooltip,this.timestamp,t,this.disabled)}static build(t,e,o,i,n,s){if(i&&!s&&t.some((t=>1==t.state)))return i.setDisabled();let l=function(t,e){let o=[],i=null,n=t=>{o.push(t);let{section:e}=t.completion;if(e){i||(i=[]);let t="string"==typeof e?e:e.name;i.some((e=>e.name==t))||i.push("string"==typeof e?{name:t}:e)}},s=e.facet(W);for(let i of t)if(i.hasResult()){let t=i.result.getMatch;if(!1===i.result.filter)for(let e of i.result.options)n(new R(e,i.source,t?t(e):[],1e9-o.length));else{let o,l=e.sliceDoc(i.from,i.to),r=s.filterStrict?new U(l):new N(l);for(let e of i.result.options)if(o=r.match(e.label)){let s=e.displayLabel?t?t(e,o.matched):[]:o.matched;n(new R(e,i.source,s,o.score+(e.boost||0)))}}}if(i){let t=Object.create(null),e=0,n=(t,e)=>{var o,i;return(null!==(o=t.rank)&&void 0!==o?o:1e9)-(null!==(i=e.rank)&&void 0!==i?i:1e9)||(t.name<e.name?-1:1)};for(let o of i.sort(n))e-=1e5,t[o.name]=e;for(let e of o){let{section:o}=e.completion;o&&(e.score+=t["string"==typeof o?o:o.name])}}let l=[],r=null,a=s.compareCompletions;for(let t of o.sort(((t,e)=>e.score-t.score||a(t.completion,e.completion)))){let e=t.completion;!r||r.label!=e.label||r.detail!=e.detail||null!=r.type&&null!=e.type&&r.type!=e.type||r.apply!=e.apply||r.boost!=e.boost?l.push(t):Q(t.completion)>Q(r)&&(l[l.length-1]=t),r=t.completion}return l}(t,e);if(!l.length)return i&&t.some((t=>1==t.state))?i.setDisabled():null;let r=e.facet(W).selectOnOpen?0:-1;if(i&&i.selected!=r&&-1!=i.selected){let t=i.options[i.selected].completion;for(let e=0;e<l.length;e++)if(l[e].completion==t){r=e;break}}return new _(l,J(o,r),{pos:t.reduce(((t,e)=>e.hasResult()?Math.min(t,e.from):t),1e8),create:rt,above:n.aboveCursor},i?i.timestamp:Date.now(),r,!1)}map(t){return new _(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:t.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}setDisabled(){return new _(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class X{constructor(t,e,o){this.active=t,this.id=e,this.open=o}static start(){return new X(Z,"cm-ac-"+Math.floor(2e6*Math.random()).toString(36),null)}update(t){let{state:e}=t,o=e.facet(W),i=(o.override||e.languageDataAt("autocomplete",E(e)).map(F)).map((e=>(this.active.find((t=>t.source==e))||new et(e,this.active.some((t=>0!=t.state))?1:0)).update(t,o)));i.length==this.active.length&&i.every(((t,e)=>t==this.active[e]))&&(i=this.active);let n=this.open,s=t.effects.some((t=>t.is(it)));n&&t.docChanged&&(n=n.map(t.changes)),t.selection||i.some((e=>e.hasResult()&&t.changes.touchesRange(e.from,e.to)))||!function(t,e){if(t==e)return!0;for(let o=0,i=0;;){for(;o<t.length&&!t[o].hasResult;)o++;for(;i<e.length&&!e[i].hasResult;)i++;let n=o==t.length,s=i==e.length;if(n||s)return n==s;if(t[o++].result!=e[i++].result)return!1}}(i,this.active)||s?n=_.build(i,e,this.id,n,o,s):n&&n.disabled&&!i.some((t=>1==t.state))&&(n=null),!n&&i.every((t=>1!=t.state))&&i.some((t=>t.hasResult()))&&(i=i.map((t=>t.hasResult()?new et(t.source,0):t)));for(let e of t.effects)e.is(nt)&&(n=n&&n.setSelected(e.value,this.id));return i==this.active&&n==this.open?this:new X(i,this.id,n)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?Y:G}}const Y={"aria-autocomplete":"list"},G={};function J(t,e){let o={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":t};return e>-1&&(o["aria-activedescendant"]=t+"-"+e),o}const Z=[];function tt(t,e){if(t.isUserEvent("input.complete")){let o=t.annotation(M);if(o&&e.activateOnCompletion(o))return 12}let o=t.isUserEvent("input.type");return o&&e.activateOnTyping?5:o?1:t.isUserEvent("delete.backward")?2:t.selection?8:t.docChanged?16:0}class et{constructor(t,e,o=-1){this.source=t,this.state=e,this.explicitPos=o}hasResult(){return!1}update(t,e){let o=tt(t,e),i=this;(8&o||16&o&&this.touches(t))&&(i=new et(i.source,0)),4&o&&0==i.state&&(i=new et(this.source,1)),i=i.updateFor(t,o);for(let e of t.effects)if(e.is(j))i=new et(i.source,1,e.value?E(t.state):-1);else if(e.is($))i=new et(i.source,0);else if(e.is(it))for(let t of e.value)t.source==i.source&&(i=t);return i}updateFor(t,e){return this.map(t.changes)}map(t){return t.empty||this.explicitPos<0?this:new et(this.source,this.state,t.mapPos(this.explicitPos))}touches(t){return t.changes.touchesRange(E(t.state))}}class ot extends et{constructor(t,e,o,i,n){super(t,2,e),this.result=o,this.from=i,this.to=n}hasResult(){return!0}updateFor(t,e){var o;if(!(3&e))return this.map(t.changes);let i=this.result;i.map&&!t.changes.empty&&(i=i.map(i,t.changes));let n=t.changes.mapPos(this.from),s=t.changes.mapPos(this.to,1),l=E(t.state);if((this.explicitPos<0?l<=n:l<this.from)||l>s||!i||2&e&&E(t.startState)==this.from)return new et(this.source,4&e?1:0);let r=this.explicitPos<0?-1:t.changes.mapPos(this.explicitPos);return function(t,e,o,i){if(!t)return!1;let n=e.sliceDoc(o,i);return"function"==typeof t?t(n,o,i,e):P(t,!0).test(n)}(i.validFor,t.state,n,s)?new ot(this.source,r,i,n,s):i.update&&(i=i.update(i,n,s,new T(t.state,l,r>=0)))?new ot(this.source,r,i,i.from,null!==(o=i.to)&&void 0!==o?o:E(t.state)):new et(this.source,1,r)}map(t){if(t.empty)return this;return(this.result.map?this.result.map(this.result,t):this.result)?new ot(this.source,this.explicitPos<0?-1:t.mapPos(this.explicitPos),this.result,t.mapPos(this.from),t.mapPos(this.to,1)):new et(this.source,0)}touches(t){return t.changes.touchesRange(this.from,this.to)}}const it=a.define({map:(t,e)=>t.map((t=>t.map(e)))}),nt=a.define(),st=r.define({create:()=>X.start(),update:(t,e)=>t.update(e),provide:t=>[w.from(t,(t=>t.tooltip)),g.contentAttributes.from(t,(t=>t.attrs))]});function lt(t,e){const i=e.completion.apply||e.completion.label;let n=t.state.field(st).active.find((t=>t.source==e.source));return n instanceof ot&&("string"==typeof i?t.dispatch(Object.assign(Object.assign({},function(t,e,i,n){let{main:s}=t.selection,l=i-s.from,r=n-s.from;return Object.assign(Object.assign({},t.changeByRange((a=>{if(a!=s&&i!=n&&t.sliceDoc(a.from+l,a.from+r)!=t.sliceDoc(i,n))return{range:a};let c=t.toText(e);return{changes:{from:a.from+l,to:n==s.from?a.to:a.from+r,insert:c},range:o.cursor(a.from+l+c.length)}}))),{scrollIntoView:!0,userEvent:"input.complete"})}(t.state,i,n.from,n.to)),{annotations:M.of(e.completion)})):i(t,e.completion,n.from,n.to),!0)}const rt=K(st,lt);function at(t,e="option"){return o=>{let i=o.state.field(st,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp<o.state.facet(W).interactionDelay)return!1;let n,s=1;"page"==e&&(n=y(o,i.open.tooltip))&&(s=Math.max(2,Math.floor(n.dom.offsetHeight/n.dom.querySelector("li").offsetHeight)-1));let{length:l}=i.open.options,r=i.open.selected>-1?i.open.selected+s*(t?1:-1):t?0:l-1;return r<0?r="page"==e?0:l-1:r>=l&&(r="page"==e?l-1:0),o.dispatch({effects:nt.of(r)}),!0}}const ct=t=>!!t.state.field(st,!1)&&(t.dispatch({effects:j.of(!0)}),!0);class ht{constructor(t,e){this.active=t,this.context=e,this.time=Date.now(),this.updates=[],this.done=void 0}}const pt=x.fromClass(class{constructor(t){this.view=t,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of t.state.field(st).active)1==e.state&&this.startQuery(e)}update(t){let e=t.state.field(st),o=t.state.facet(W);if(!t.selectionSet&&!t.docChanged&&t.startState.field(st)==e)return;let i=t.transactions.some((t=>{let e=tt(t,o);return 8&e||(t.selection||t.docChanged)&&!(3&e)}));for(let e=0;e<this.running.length;e++){let o=this.running[e];if(i||o.context.abortOnDocChange&&t.docChanged||o.updates.length+t.transactions.length>50&&Date.now()-o.time>1e3){for(let t of o.context.abortListeners)try{t()}catch(t){C(this.view.state,t)}o.context.abortListeners=null,this.running.splice(e--,1)}else o.updates.push(...t.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),t.transactions.some((t=>t.effects.some((t=>t.is(j)))))&&(this.pendingStart=!0);let n=this.pendingStart?50:o.activateOnTypingDelay;if(this.debounceUpdate=e.active.some((t=>1==t.state&&!this.running.some((e=>e.active.source==t.source))))?setTimeout((()=>this.startUpdate()),n):-1,0!=this.composing)for(let e of t.transactions)e.isUserEvent("input.type")?this.composing=2:2==this.composing&&e.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:t}=this.view,e=t.field(st);for(let t of e.active)1!=t.state||this.running.some((e=>e.active.source==t.source))||this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout((()=>this.accept()),this.view.state.facet(W).updateSyncTime))}startQuery(t){let{state:e}=this.view,o=E(e),i=new T(e,o,t.explicitPos==o,this.view),n=new ht(t,i);this.running.push(n),Promise.resolve(t.source(i)).then((t=>{n.context.aborted||(n.done=t||null,this.scheduleAccept())}),(t=>{this.view.dispatch({effects:$.of(null)}),C(this.view.state,t)}))}scheduleAccept(){this.running.every((t=>void 0!==t.done))?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout((()=>this.accept()),this.view.state.facet(W).updateSyncTime))}accept(){var t;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],o=this.view.state.facet(W),i=this.view.state.field(st);for(let n=0;n<this.running.length;n++){let s=this.running[n];if(void 0===s.done)continue;if(this.running.splice(n--,1),s.done){let i=new ot(s.active.source,s.active.explicitPos,s.done,s.done.from,null!==(t=s.done.to)&&void 0!==t?t:E(s.updates.length?s.updates[0].startState:this.view.state));for(let t of s.updates)i=i.update(t,o);if(i.hasResult()){e.push(i);continue}}let l=i.active.find((t=>t.source==s.active.source));if(l&&1==l.state)if(null==s.done){let t=new et(s.active.source,0);for(let e of s.updates)t=t.update(e,o);1!=t.state&&e.push(t)}else this.startQuery(l)}(e.length||i.open&&i.open.disabled)&&this.view.dispatch({effects:it.of(e)})}},{eventHandlers:{blur(t){let e=this.view.state.field(st,!1);if(e&&e.tooltip&&this.view.state.facet(W).closeOnBlur){let o=e.open&&y(this.view,e.open.tooltip);o&&o.dom.contains(t.relatedTarget)||setTimeout((()=>this.view.dispatch({effects:$.of(null)})),10)}},compositionstart(){this.composing=1},compositionend(){3==this.composing&&setTimeout((()=>this.view.dispatch({effects:j.of(!1)})),20),this.composing=0}}}),ft="object"==typeof navigator&&/Win/.test(navigator.platform),ut=n.highest(g.domEventHandlers({keydown(t,e){let o=e.state.field(st,!1);if(!o||!o.open||o.open.disabled||o.open.selected<0||t.key.length>1||t.ctrlKey&&(!ft||!t.altKey)||t.metaKey)return!1;let i=o.open.options[o.open.selected],n=o.active.find((t=>t.source==i.source)),s=i.completion.commitCharacters||n.result.commitCharacters;return s&&s.indexOf(t.key)>-1&&lt(e,i),!1}})),dt=g.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class mt{constructor(t,e,o,i){this.field=t,this.line=e,this.from=o,this.to=i}}class gt{constructor(t,e,o){this.field=t,this.from=e,this.to=o}map(t){let e=t.mapPos(this.from,-1,c.TrackDel),o=t.mapPos(this.to,1,c.TrackDel);return null==e||null==o?null:new gt(this.field,e,o)}}class vt{constructor(t,e){this.lines=t,this.fieldPositions=e}instantiate(t,e){let o=[],i=[e],n=t.doc.lineAt(e),s=/^\s*/.exec(n.text)[0];for(let n of this.lines){if(o.length){let o=s,l=/^\t*/.exec(n)[0].length;for(let e=0;e<l;e++)o+=t.facet(D);i.push(e+o.length-l),n=o+n.slice(l)}o.push(n),e+=n.length+1}let l=this.fieldPositions.map((t=>new gt(t.field,i[t.line]+t.from,i[t.line]+t.to)));return{text:o,ranges:l}}static parse(t){let e,o=[],i=[],n=[];for(let s of t.split(/\r\n?|\n/)){for(;e=/[#$]\{(?:(\d+)(?::([^}]*))?|((?:\\[{}]|[^}])*))\}/.exec(s);){let t=e[1]?+e[1]:null,l=e[2]||e[3]||"",r=-1,a=l.replace(/\\[{}]/g,(t=>t[1]));for(let e=0;e<o.length;e++)(null!=t?o[e].seq==t:a&&o[e].name==a)&&(r=e);if(r<0){let e=0;for(;e<o.length&&(null==t||null!=o[e].seq&&o[e].seq<t);)e++;o.splice(e,0,{seq:t,name:a}),r=e;for(let t of n)t.field>=r&&t.field++}n.push(new mt(r,i.length,e.index,e.index+a.length)),s=s.slice(0,e.index)+l+s.slice(e.index+e[0].length)}s=s.replace(/\\([{}])/g,((t,e,o)=>{for(let t of n)t.line==i.length&&t.from>o&&(t.from--,t.to--);return e})),i.push(s)}return new vt(i,n)}}let bt=I.widget({widget:new class extends O{toDOM(){let t=document.createElement("span");return t.className="cm-snippetFieldPosition",t}ignoreEvent(){return!1}}}),wt=I.mark({class:"cm-snippetField"});class yt{constructor(t,e){this.ranges=t,this.active=e,this.deco=I.set(t.map((t=>(t.from==t.to?bt:wt).range(t.from,t.to))))}map(t){let e=[];for(let o of this.ranges){let i=o.map(t);if(!i)return null;e.push(i)}return new yt(e,this.active)}selectionInsideField(t){return t.ranges.every((t=>this.ranges.some((e=>e.field==this.active&&e.from<=t.from&&e.to>=t.to))))}}const xt=a.define({map:(t,e)=>t&&t.map(e)}),Ct=a.define(),It=r.define({create:()=>null,update(t,e){for(let o of e.effects){if(o.is(xt))return o.value;if(o.is(Ct)&&t)return new yt(t.ranges,o.value)}return t&&e.docChanged&&(t=t.map(e.changes)),t&&e.selection&&!t.selectionInsideField(e.selection)&&(t=null),t},provide:t=>g.decorations.from(t,(t=>t?t.deco:I.none))});function Ot(t,e){return o.create(t.filter((t=>t.field==e)).map((t=>o.range(t.from,t.to))))}function kt(t){let e=vt.parse(t);return(t,o,i,n)=>{let{text:s,ranges:l}=e.instantiate(t.state,i),r={changes:{from:i,to:n,insert:d.of(s)},scrollIntoView:!0,annotations:o?[M.of(o),m.userEvent.of("input.complete")]:void 0};if(l.length&&(r.selection=Ot(l,0)),l.some((t=>t.field>0))){let e=new yt(l,0),o=r.effects=[xt.of(e)];void 0===t.state.field(It,!1)&&o.push(a.appendConfig.of([It,At,Rt,dt]))}t.dispatch(t.state.update(r))}}function Dt(t){return({state:e,dispatch:o})=>{let i=e.field(It,!1);if(!i||t<0&&0==i.active)return!1;let n=i.active+t,s=t>0&&!i.ranges.some((e=>e.field==n+t));return o(e.update({selection:Ot(i.ranges,n),effects:xt.of(s?null:new yt(i.ranges,n)),scrollIntoView:!0})),!0}}const Tt=[{key:"Tab",run:Dt(1),shift:Dt(-1)},{key:"Escape",run:({state:t,dispatch:e})=>!!t.field(It,!1)&&(e(t.update({effects:xt.of(null)})),!0)}],St=s.define({combine:t=>t.length?t[0]:Tt}),At=n.highest(v.compute([St],(t=>t.facet(St))));function Lt(t,e){return Object.assign(Object.assign({},e),{apply:kt(t)})}const Rt=g.domEventHandlers({mousedown(t,e){let o,i=e.state.field(It,!1);if(!i||null==(o=e.posAtCoords({x:t.clientX,y:t.clientY})))return!1;let n=i.ranges.find((t=>t.from<=o&&t.to>=o));return!(!n||n.field==i.active)&&(e.dispatch({selection:Ot(i.ranges,n.field),effects:xt.of(i.ranges.some((t=>t.field>n.field))?new yt(i.ranges,n.field):null),scrollIntoView:!0}),!0)}}),Et={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Pt=a.define({map(t,e){let o=e.mapPos(t,-1,c.TrackAfter);return null==o?void 0:o}}),Mt=new class extends h{};Mt.startSide=1,Mt.endSide=-1;const Bt=r.define({create:()=>p.empty,update(t,e){if(t=t.map(e.changes),e.selection){let o=e.state.doc.lineAt(e.selection.main.head);t=t.update({filter:t=>t>=o.from&&t<=o.to})}for(let o of e.effects)o.is(Pt)&&(t=t.update({add:[Mt.range(o.value,o.value+1)]}));return t}});function Ft(){return[Wt,Bt]}const jt="()[]{}<>";function $t(t){for(let e=0;e<8;e+=2)if(jt.charCodeAt(e)==t)return jt.charAt(e+1);return f(t<128?t:t+1)}function Nt(t,e){return t.languageDataAt("closeBrackets",e)[0]||Et}const Ut="object"==typeof navigator&&/Android\b/.test(navigator.userAgent),Wt=g.inputHandler.of(((o,i,n,s)=>{if((Ut?o.composing:o.compositionStarted)||o.state.readOnly)return!1;let l=o.state.selection.main;if(s.length>2||2==s.length&&1==t(e(s,0))||i!=l.from||n!=l.to)return!1;let r=function(t,o){let i=Nt(t,t.selection.main.head),n=i.brackets||Et.brackets;for(let s of n){let l=$t(e(s,0));if(o==s)return l==s?Qt(t,s,n.indexOf(s+s+s)>-1,i):zt(t,s,l,i.before||Et.before);if(o==l&&Ht(t,t.selection.main.from))return Kt(t,s,l)}return null}(o.state,s);return!!r&&(o.dispatch(r),!0)})),qt=[{key:"Backspace",run:({state:i,dispatch:n})=>{if(i.readOnly)return!1;let s=Nt(i,i.selection.main.head).brackets||Et.brackets,l=null,r=i.changeByRange((n=>{if(n.empty){let l=function(o,i){let n=o.sliceString(i-2,i);return t(e(n,0))==n.length?n:n.slice(1)}(i.doc,n.head);for(let t of s)if(t==l&&Vt(i.doc,n.head)==$t(e(t,0)))return{changes:{from:n.head-t.length,to:n.head+t.length},range:o.cursor(n.head-t.length)}}return{range:l=n}}));return l||n(i.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!l}}];function Ht(t,e){let o=!1;return t.field(Bt).between(0,t.doc.length,(t=>{t==e&&(o=!0)})),o}function Vt(o,i){let n=o.sliceString(i,i+2);return n.slice(0,t(e(n,0)))}function zt(t,e,i,n){let s=null,l=t.changeByRange((l=>{if(!l.empty)return{changes:[{insert:e,from:l.from},{insert:i,from:l.to}],effects:Pt.of(l.to+e.length),range:o.range(l.anchor+e.length,l.head+e.length)};let r=Vt(t.doc,l.head);return!r||/\s/.test(r)||n.indexOf(r)>-1?{changes:{insert:e+i,from:l.head},effects:Pt.of(l.head+e.length),range:o.cursor(l.head+e.length)}:{range:s=l}}));return s?null:t.update(l,{scrollIntoView:!0,userEvent:"input.type"})}function Kt(t,e,i){let n=null,s=t.changeByRange((e=>e.empty&&Vt(t.doc,e.head)==i?{changes:{from:e.head,to:e.head+i.length,insert:i},range:o.cursor(e.head+i.length)}:n={range:e}));return n?null:t.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function Qt(t,e,n,s){let l=s.stringPrefixes||Et.stringPrefixes,r=null,a=t.changeByRange((s=>{if(!s.empty)return{changes:[{insert:e,from:s.from},{insert:e,from:s.to}],effects:Pt.of(s.to+e.length),range:o.range(s.anchor+e.length,s.head+e.length)};let a,c=s.head,h=Vt(t.doc,c);if(h==e){if(_t(t,c))return{changes:{insert:e+e,from:c},effects:Pt.of(c+e.length),range:o.cursor(c+e.length)};if(Ht(t,c)){let i=n&&t.sliceDoc(c,c+3*e.length)==e+e+e?e+e+e:e;return{changes:{from:c,to:c+i.length,insert:i},range:o.cursor(c+i.length)}}}else{if(n&&t.sliceDoc(c-2*e.length,c)==e+e&&(a=Xt(t,c-2*e.length,l))>-1&&_t(t,a))return{changes:{insert:e+e+e+e,from:c},effects:Pt.of(c+e.length),range:o.cursor(c+e.length)};if(t.charCategorizer(c)(h)!=i.Word&&Xt(t,c,l)>-1&&!function(t,e,o,i){let n=k(t).resolveInner(e,-1),s=i.reduce(((t,e)=>Math.max(t,e.length)),0);for(let l=0;l<5;l++){let l=t.sliceDoc(n.from,Math.min(n.to,n.from+o.length+s)),r=l.indexOf(o);if(!r||r>-1&&i.indexOf(l.slice(0,r))>-1){let e=n.firstChild;for(;e&&e.from==n.from&&e.to-e.from>o.length+r;){if(t.sliceDoc(e.to-o.length,e.to)==o)return!1;e=e.firstChild}return!0}let a=n.to==e&&n.parent;if(!a)break;n=a}return!1}(t,c,e,l))return{changes:{insert:e+e,from:c},effects:Pt.of(c+e.length),range:o.cursor(c+e.length)}}return{range:r=s}}));return r?null:t.update(a,{scrollIntoView:!0,userEvent:"input.type"})}function _t(t,e){let o=k(t).resolveInner(e+1);return o.parent&&o.from==e}function Xt(t,e,o){let n=t.charCategorizer(e);if(n(t.sliceDoc(e-1,e))!=i.Word)return e;for(let s of o){let o=e-s.length;if(t.sliceDoc(o,e)==s&&n(t.sliceDoc(o-1,o))!=i.Word)return o}return-1}function Yt(t={}){return[ut,st,W.of(t),pt,Jt,dt]}const Gt=[{key:"Ctrl-Space",run:ct},{mac:"Alt-`",run:ct},{key:"Escape",run:t=>{let e=t.state.field(st,!1);return!(!e||!e.active.some((t=>0!=t.state)))&&(t.dispatch({effects:$.of(null)}),!0)}},{key:"ArrowDown",run:at(!0)},{key:"ArrowUp",run:at(!1)},{key:"PageDown",run:at(!0,"page")},{key:"PageUp",run:at(!1,"page")},{key:"Enter",run:t=>{let e=t.state.field(st,!1);return!(t.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestamp<t.state.facet(W).interactionDelay)&&lt(t,e.open.options[e.open.selected])}}],Jt=n.highest(v.computeN([W],(t=>t.facet(W).defaultKeymap?[Gt]:[])));export{Ft as a,Yt as b,A as c,qt as d,Gt as e,L as i,Lt as s};
2
- //# sourceMappingURL=index-K1IVD1z0.js.map