Repository: munshkr/flok Branch: main Commit: b60608df84e5 Files: 196 Total size: 954.4 KB Directory structure: gitextract_72bb2f9g/ ├── .editorconfig ├── .github/ │ ├── FUNDING.yml │ └── workflows/ │ ├── deploy.yml │ └── test.yml ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── LICENSE.txt ├── README.md ├── lerna.json ├── package.json └── packages/ ├── cm-eval/ │ ├── .gitignore │ ├── lib/ │ │ ├── eval.ts │ │ ├── flashField.ts │ │ ├── index.ts │ │ └── remoteEvalFlash.ts │ ├── package.json │ └── tsconfig.json ├── example-vanilla-js/ │ ├── .gitignore │ ├── index.html │ ├── main.js │ ├── package.json │ └── style.css ├── lang-punctual/ │ ├── .gitignore │ ├── .npmignore │ ├── LICENSE │ ├── README.md │ ├── package.json │ ├── rollup.config.js │ ├── src/ │ │ ├── indentation.ts │ │ ├── index.ts │ │ └── punctual.ts │ └── tsconfig.json ├── lang-tidal/ │ ├── .gitignore │ ├── .npmignore │ ├── LICENSE │ ├── README.md │ ├── package.json │ ├── rollup.config.js │ ├── src/ │ │ ├── indentation.ts │ │ ├── index.ts │ │ └── tidal.ts │ └── tsconfig.json ├── pubsub/ │ ├── .gitignore │ ├── README.md │ ├── examples/ │ │ ├── client.js │ │ └── server.js │ ├── lib/ │ │ ├── client.ts │ │ ├── index.ts │ │ └── server.ts │ ├── package.json │ └── tsconfig.json ├── repl/ │ ├── bin/ │ │ └── flok-repl.js │ ├── lib/ │ │ ├── index.ts │ │ ├── repl/ │ │ │ ├── dummy.ts │ │ │ ├── foxdot.ts │ │ │ ├── mercury.ts │ │ │ ├── renardo.ts │ │ │ ├── sardine.ts │ │ │ ├── sclang.ts │ │ │ └── tidal.ts │ │ └── repl.ts │ ├── package.json │ └── tsconfig.json ├── server/ │ ├── .gitignore │ ├── bin/ │ │ └── flok-server.js │ └── package.json ├── server-middleware/ │ ├── .gitignore │ ├── lib/ │ │ ├── index.ts │ │ ├── signaling-server.ts │ │ └── y-websocket-server.ts │ ├── package.json │ └── tsconfig.json ├── session/ │ ├── .gitignore │ ├── lib/ │ │ ├── document.ts │ │ ├── index.ts │ │ └── session.ts │ ├── package.json │ └── tsconfig.json └── web/ ├── .gitignore ├── .prettierignore ├── bin/ │ └── flok-web.js ├── cert/ │ ├── cert.pem │ └── key.pem ├── index.html ├── package.json ├── postcss.config.cjs ├── script/ │ └── prebuild.js ├── server.js ├── src/ │ ├── assets/ │ │ └── fonts/ │ │ ├── BigBlue/ │ │ │ ├── LICENSE.TXT │ │ │ └── stylesheet.css │ │ ├── FiraCode/ │ │ │ ├── README.txt │ │ │ └── stylesheet.css │ │ ├── IBM Plex Mono/ │ │ │ └── stylesheet.css │ │ ├── JGS/ │ │ │ └── stylesheet.css │ │ ├── JetBrains/ │ │ │ └── stylesheet.css │ │ ├── Monocraft/ │ │ │ └── stylesheet.css │ │ ├── OpenDyslexic/ │ │ │ └── stylesheet.css │ │ ├── RobotoMono/ │ │ │ ├── LICENSE.txt │ │ │ └── stylesheet.css │ │ ├── StepsMono/ │ │ │ ├── COPYRIGHT.md │ │ │ ├── LICENSE.txt │ │ │ └── stylesheet.css │ │ ├── SyneMono/ │ │ │ ├── OFL.txt │ │ │ └── stylesheet.css │ │ ├── UbuntuMono/ │ │ │ ├── UFL.txt │ │ │ └── stylesheet.css │ │ └── VT323/ │ │ ├── OFL.txt │ │ ├── demo.html │ │ └── stylesheet.css │ ├── components/ │ │ ├── commands-button.tsx │ │ ├── configure-dialog.tsx │ │ ├── display-settings-dialog.tsx │ │ ├── editor.tsx │ │ ├── evaluate-button.tsx │ │ ├── hydra-canvas.tsx │ │ ├── icons.tsx │ │ ├── messages-panel.tsx │ │ ├── mosaic.tsx │ │ ├── pane.tsx │ │ ├── punctual-canvas.tsx │ │ ├── repls-button.tsx │ │ ├── repls-dialog.tsx │ │ ├── repls-info.tsx │ │ ├── session-command-dialog.tsx │ │ ├── session-menu.tsx │ │ ├── share-url-dialog.tsx │ │ ├── status-bar.tsx │ │ ├── target-select.tsx │ │ ├── ui/ │ │ │ ├── button.tsx │ │ │ ├── command.tsx │ │ │ ├── dialog.tsx │ │ │ ├── dropdown-menu.tsx │ │ │ ├── floating-panel.tsx │ │ │ ├── input.tsx │ │ │ ├── label.tsx │ │ │ ├── menubar.tsx │ │ │ ├── popover.tsx │ │ │ ├── select.tsx │ │ │ ├── toast.tsx │ │ │ ├── toaster.tsx │ │ │ ├── toggle.tsx │ │ │ └── tooltip.tsx │ │ ├── username-dialog.tsx │ │ ├── web-target-iframe.tsx │ │ └── welcome-dialog.tsx │ ├── error-page.tsx │ ├── hooks/ │ │ ├── use-animation-frame.tsx │ │ ├── use-eval-handler.tsx │ │ ├── use-hash.tsx │ │ ├── use-query.tsx │ │ ├── use-settings.tsx │ │ ├── use-shortcut.tsx │ │ ├── use-strudel-codemirror-extensions.ts │ │ ├── use-toast.tsx │ │ └── use-web-target.tsx │ ├── index.css │ ├── lib/ │ │ ├── display-settings.ts │ │ ├── fonts.ts │ │ ├── hydra-synth.d.ts │ │ ├── hydra-wrapper.ts │ │ ├── mercury-wrapper.ts │ │ ├── mercury.d.ts │ │ ├── p5-wrapper.ts │ │ ├── punctual-wrapper.ts │ │ ├── punctual.d.ts │ │ ├── punctual.js │ │ ├── settings.ts │ │ ├── strudel-wrapper.ts │ │ ├── strudel.d.ts │ │ ├── themes/ │ │ │ ├── ayu-dark.ts │ │ │ ├── dracula.ts │ │ │ ├── gruvbox-dark.ts │ │ │ ├── index.ts │ │ │ ├── monokai-dimmed.ts │ │ │ ├── nord.ts │ │ │ ├── one-dark.ts │ │ │ └── tokyo-night.ts │ │ ├── utils.ts │ │ ├── webgl-detector.ts │ │ └── y-codemirror.d.ts │ ├── main.tsx │ ├── routes/ │ │ ├── frames/ │ │ │ ├── hydra.tsx │ │ │ ├── mercury-web.tsx │ │ │ ├── punctual.tsx │ │ │ └── strudel.tsx │ │ ├── root.tsx │ │ └── session.tsx │ ├── settings.json │ └── vite-env.d.ts ├── tailwind.config.cjs ├── tsconfig.json ├── tsconfig.node.json ├── vite-express.js └── vite.config.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ [*] charset = utf-8 insert_final_newline = true end_of_line = lf indent_style = space indent_size = 2 max_line_length = 80 ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: munshkr tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .github/workflows/deploy.yml ================================================ name: Build and Deploy to flok.cc on: push: branches: - main workflow_dispatch: jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v3 with: node-version: 20 - run: npm install - run: npm run build - name: Configure SSH run: | mkdir -p ~/.ssh/ echo "$SSH_KEY" > ~/.ssh/prod.key chmod 600 ~/.ssh/prod.key cat >>~/.ssh/config <> $HOME/.npmrc 2> /dev/null deploy: provider: script script: yarn lerna publish from-git --no-git-reset --yes skip_cleanup: true on: node: "12" tags: true api_key: secure: hRpP7MGwhsCAXtKDS2KowriWu2ADLvW+/Jb/qSdBzR6v4UQ6WxYEiopHwuApk/m9iPLW0QmD14n//kU4ADTm84v4XqY5OoUZxkcQWi5wyY3EbFnOVT3Fr2cr/xNtjXP8so/5hKAHHxccx8ZeGd/pGEkolBhmKMpdmwzcCXTE1jN1xsgHduPPLg3/ob5ORGXvrTm2pF6aqWyaMS7eLydfJ8Dm1FLmLFGy9mUQXSF3RFuhIZeBy5I3emMOn+CgJv1XtTjf9YexD3e79LK/WzCVSxGB8Uhh0jcKDnHCY3wsRMB7R+0RLMB8mi6dYLl24DcQ6AwGrTj4gL7uWWfkVVF2pldTfz+NvfJ2tEszjTZ4Q0Z6pMc/g2YbP0Kam63Rv0FG9ZyW6HPUTnHiA86skpzwfW1TA+O5FgvdzsXAtwrmuxCx/I4a4C2pE9ldc3SkgKz9XJ60hZCilz3r8qknPJaGnkAEZBBOu+u3cEBJtQZESyZylENwdioyxSWXIHxbi9pjdupdGkjZ34QVX1lohTmxmALAB4X3REEm0jYY/OnvkhnWJ0tjaPQCmDp+ONOyyFvVtCMzFUZ+lyXv6xcyVththZMIirX8SnwKXDAsOFXuqXsIq7feRMiz6Nq3Q6IadKGC7LlMcIJgXVh8lypw6sAUnJUq362oyD4SmRE56sfsHs0= ================================================ FILE: CHANGELOG.md ================================================ # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.3.0] - 2025-01-05 ### New Features - Vim keybindings (#280) - Themes and font families (#283, #303) - Display settings dialog for changing canvas resolution (#301) - Define `fft`, `P` and `useStrudelCanvas` functions for Hydra (#310, #309) ### Bugfixes and minor changes - Use line separator for Windows on REPL command copy dialog (#285) - Initialize audio on Strudel on first user interaction (keydown/mouse) (#294) - Fix flash/highlight stuck on multiple evaluations (#308) - Add angle brackets to Tidal language autoclose (#302) - Upgrade `@strudel/*` packages to v1.1.0; add `@strudel/draw` (#292) ## [1.2.0] - 2024-04-26 ### New Features - Support for Renardo (Foxdot fork) - web: Sandbox web languages using iframes - web: Toggle line numbers with Shift-Ctrl-W and linewrap with Shift-Ctrl-W. - web(strudel): Code highlighting ### Bugfixes - repl: Use `sardine` instead of `fishery` when running Sardine REPL - web(hydra): Use correct canvas size by default + pixelated image rendering - web(strudel): Misc fixse - Lots of name clashing between hydra, strudel and mercury-web were solved with language sandboxes. ## [1.1.1] - 2024-01-29 ### Bugfixes - web(strudel): Use REPL evaluate method, this fixes the "`setcps` is not defined" error. ## [1.1.0] - 2024-01-28 ### Bugfixes - web(hydra): Fixed issues with P5 not loading properly - web(hydra): `await` now works properly - web: Fixed issue with `flok-web` binary script running in development mode ### New Features - web: Share URL command for sharing session URL along with current layout and code. - web: `hideErrors` query parameter option for hiding errors of web targets - web: `code` and `c0`..`c7` hash parameters to set code for each editor ### Changed - web(hydra): Updated P5 to 1.9.0 - web(mercury): Updated Mercury to 0.14.0 - web(strudel): Updated Strudel to 1.0.0 - web: Updated Codemirror and related packages - web: Updated Yjs and related packages - web: Updated Vite 5 - web: Moved `username` and `targets` query parameters as hash parameters ## [1.0.2] - 2024-01-13 ### Changed - repl: Fix error when trying to use flok-repl without `-T`/`--types` argument (default value) ## [1.0.1] - 2024-01-13 ### Changed - web: Fixed and optimized flok-web package, by removing lots of runtime deps that were used on build time only. - web: Removed pinned flok-repl version from REPL instructions. ## [1.0.0] - 2024-01-12 Complete rewrite of Flok, with a new architecture and new features. See [README.md](../README.md) for more information. - Started new web project, based on Vite, Tailwind, Radix UI and Shadcn CSS frameworks. - Upgraded CodeMirror to version 6 - Upgraded Yjs to latest version - New modular architecture, with separate plugins related to codemirror (following their new architecture as well) - Document layout is now part of the session state, and can be changed dynamically, instead of being based on the query parameter `?layout`. - Improved REPL message handling and UI - Command palette for executing commands and configuring the editor - Added support for Strudel and Mercury as web targets ## [0.4.12] - 2024-01-06 ### Added - web: Toggle comment with Ctrl-/ or Cmd-/ - web(sardine): Free all sound for Sardine ### Changed - repl(sardine): Changed interpreter name (fishery -> sardine) - web: Bugfixes related to the server script (flok-web) - web: Fixed @types/react wrong version ## [0.4.8] - 2022-05-26 ### Added - web: Add key binding Ctrl+Shift+H to hide or show editors ### Changed - web: Replace yjsdemo WebSocket Yjs server for an embedded WS server - web: Use a random english name + first 8 chars of uuid as default session name - web: Upgrade p5 to version 1.4.1 - web: Upgrade hydra-synth to version 1.3.16 - web: Upgrade Next to version 12 - web: Restore package bundle ## [0.4.6] - 2021-10-31 ### Added - web: Print possible network IPs when starting web server locally - web: New --static-dir option for setting a custom static files directory when starting web server. ### Changed - web: Upgrade hydra-synth to 1.3.8 - web: Upgrade next to 11 - repl: Remove "tidal> " from stdout on tidal target; other minor improvements ## [0.4.5] - 2021-01-05 ### Added - web: Read-only mode by adding a `readonly=1` query parameter to a session URL - repl: In `foxdot` REPL, call `load_startup_file()` after loading Foxdot package. ### Changed - web: Upgrade hydra-synth to 1.3.6 ## [0.4.4] - 2020-12-23 ### Added - web: Follow remote cursors when moving (jump to line), but only if editor is blurred. - web: Make remote caret visible to current user too. - web: Properly support block evaluation with parens for `sclang`/`remote_sclang` targets. ### Changed - web: Skip 'hydra' as a flok-repl example when joining a session - repl: Bugfix when using custom REPL command - repl: On sclang targets, add semicolons after closing parens ## [0.4.3] - 2020-12-04 ### Added - repl, web: Support for Mercury - web: When joining session, show flok-repl example based on first target in layout. - web: New shortcut for evaluating web-target (e.g. Hydra) code only on local client (Ctrl-Alt-Enter for block execution, Shift-Alt-Enter for line execution). ### Changed - web: Upgrade to Hydra 1.3.4 ## [0.4.2] - 2020-11-12 ### Changed - web: Better styles for selected text and remote caret - repl: Fix path to embedded BootTidal.hs when using fallback ## [0.4.1] - 2020-10-11 ### Added - web: Copy button for copying flok-repl example when joining session - repl: Add package metadata and data dir, which includes a Tidal bootScript file. ### Changed - web: Disable form when creating session, while session page loads - repl: If ghc-pkg fails to get tidal data dir, fallback to embedded bootScript file. ## [0.4.0] - 2020-10-06 ### Added - repl: Add `--nickname/-N` to send REPL messages (out/err) to named user instead of all connected users. - repl: Add `--notify-to-all` to force send messages to all users (old behaviour). - repl: Add extra option `ghci` for `tidal` REPL type, for customizing ghci binary path. - web: Show current Flok version when joining session. - web: Include -N option on flok-repl example when joining session. ### Changed - Now, by default, `flok-repl` _will not_ send messages to all users by default. You need to enable the `--notify-to-all` option if you want the old behaviour. If `--nickname/-N` and `--notify-to-all` are not present, flok-repl won't send any messages, only print them on standard output/error. ## [0.3.17] - 2020-10-06 ### Added - repl: Add new `--config` option for customizing parameters from a JSON file - repl: Load config file from `FLOK_CONFIG` environment file, if defined. Also, load _.env files_ automatically. ### Changed - web: Bugfix: host prop was undefined on first page load, failing to connect afterwards. ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at munshkr@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ ================================================ FILE: LICENSE.txt ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # Flok Web-based P2P collaborative editor for live coding music and graphics > [!NOTE] > Development has now moved to Codeberg here: https://codeberg.org/munshkr/flok ## License This project is licensed under GPL 3+. Refer to [LICENSE.txt](LICENSE.txt). Punctual is licensed under GPL 3+. Refer to [LICENSE](https://github.com/dktr0/Punctual/blob/main/LICENSE). Favicon based on "Origami" by Andrejs Kirma, from [Noun Project](https://thenounproject.com/browse/icons/term/origami/) (CC BY 3.0) ================================================ FILE: lerna.json ================================================ { "$schema": "node_modules/lerna/schemas/lerna-schema.json", "useWorkspaces": true, "version": "1.3.0" } ================================================ FILE: package.json ================================================ { "name": "root", "description": "Web-based P2P collaborative editor for live coding music and graphics", "private": true, "repository": { "type": "git", "url": "git+https://github.com/munshkr/flok.git" }, "scripts": { "build": "lerna run build", "check": "lerna run check", "lint": "lerna run lint", "format": "lerna run format" }, "keywords": [ "codemirror", "webrtc", "websockets", "live-coding", "collaborative-editing" ], "author": "Damián Silvani ", "license": "GPL-3.0+", "bugs": { "url": "https://github.com/munshkr/flok/issues" }, "homepage": "https://github.com/munshkr/flok#readme", "devDependencies": { "lerna": "^6.5.1" }, "workspaces": [ "packages/*" ], "dependencies": { "react-rnd": "^10.4.1" } } ================================================ FILE: packages/cm-eval/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: packages/cm-eval/lib/eval.ts ================================================ import { EditorView, keymap } from "@codemirror/view"; import { EditorState } from "@codemirror/state"; import { flash } from "./flashField.js"; import type { Document } from "@flok-editor/session"; interface EvalBlock { text: string; from: number | null; to: number | null; } export function getSelection(state: EditorState): EvalBlock { if (state.selection.main.empty) return { text: "", from: null, to: null }; let { from, to } = state.selection.main; let text = state.doc.sliceString(from, to); return { text, from, to }; } export function getLine(state: EditorState): EvalBlock { const line = state.doc.lineAt(state.selection.main.from); let { from, to } = line; let text = state.doc.sliceString(from, to); return { text, from, to }; } export function getBlock(state: EditorState): EvalBlock { let { doc, selection } = state; let { text, number } = state.doc.lineAt(selection.main.from); if (text.trim().length === 0) return { text: "", from: null, to: null }; let fromL, toL; fromL = toL = number; while (fromL > 1 && doc.line(fromL - 1).text.trim().length > 0) { fromL -= 1; } while (toL < doc.lines && doc.line(toL + 1).text.trim().length > 0) { toL += 1; } let { from } = doc.line(fromL); let { to } = doc.line(toL); text = state.doc.sliceString(from, to); return { text, from, to }; } export const evaluateBlockOrSelection = ( view: EditorView, doc: Document, web: boolean = false, ) => { const { state } = view; const selection = getSelection(state); if (selection.text) { const { text, from, to } = selection; flash(view, from, to); doc.evaluate(text, { from, to }); } else { const { text, from, to } = getBlock(state); flash(view, from, to); doc.evaluate(text, { from, to }, web ? "web" : "default"); } }; export const evaluateLine = ( view: EditorView, doc: Document, web: boolean = false, ) => { const { state } = view; const { text, from, to } = getLine(state); flash(view, from, to); doc.evaluate(text, { from, to }, web ? "web" : "default"); }; export const evaluateDocument = ( view: EditorView, doc: Document, web: boolean = false, ) => { const { state } = view; const { from } = state.doc.line(1); const { to } = state.doc.line(state.doc.lines); const text = state.doc.sliceString(from, to); flash(view, from, to); doc.evaluate(text, { from, to }, web ? "web" : "default"); }; export function evalKeymap( document: Document, { defaultEvalKeys = ["Ctrl-Enter", "Cmd-Enter"], lineEvalKeys = ["Shift-Enter"], documentEvalKeys = ["Alt-Enter", "Ctrl-Shift-Enter", "Cmd-Shift-Enter"], defaultMode = "block", web = false, }: { defaultEvalKeys?: string[]; lineEvalKeys?: string[]; documentEvalKeys?: string[]; defaultMode?: "block" | "document"; web?: boolean; } = {}, ) { return keymap.of([ ...defaultEvalKeys.map((key) => ({ key, run(view: EditorView) { if (defaultMode === "block") { evaluateBlockOrSelection(view, document, web); } else { evaluateDocument(view, document, web); } return true; }, })), ...lineEvalKeys.map((key) => ({ key, run(view: EditorView) { evaluateLine(view, document, web); return true; }, })), ...documentEvalKeys.map((key) => ({ key, run(view: EditorView) { evaluateDocument(view, document, web); return true; }, })), ]); } ================================================ FILE: packages/cm-eval/lib/flashField.ts ================================================ import { EditorView, Decoration } from "@codemirror/view"; import { StateField, StateEffect } from "@codemirror/state"; type FlashRange = [number, number]; export const setFlash = StateEffect.define(); const defaultStyle = { "background-color": "#FFCA2880", }; const styleObjectToString = (styleObj: object): string => Object.entries(styleObj) .map(([k, v]) => `${k}:${v}`) .join(";"); export const flash = ( view: EditorView, from: number | null, to: number | null, timeout: number = 150, ) => { if (from === null || to === null) return; view.dispatch({ effects: setFlash.of([from, to]) }); setTimeout(() => { view.dispatch({ effects: setFlash.of(null) }); }, timeout); }; export const flashField = (style: object = defaultStyle) => StateField.define({ create() { return Decoration.none; }, update(flash, tr) { try { for (let e of tr.effects) { if (e.is(setFlash)) { if (e.value) { const [from, to] = e.value; const mark = Decoration.mark({ attributes: { style: styleObjectToString(style) }, }); flash = Decoration.set([mark.range(from, to)]); } else { flash = Decoration.set([]); } } } return flash; } catch (err) { console.warn("flash error", err); return flash; } }, provide: (f) => EditorView.decorations.from(f), }); export default flashField; ================================================ FILE: packages/cm-eval/lib/index.ts ================================================ export * from "./eval.js"; export * from "./flashField.js"; export * from "./remoteEvalFlash.js"; ================================================ FILE: packages/cm-eval/lib/remoteEvalFlash.ts ================================================ import { ViewPlugin } from "@codemirror/view"; import type { EditorView } from "@codemirror/view"; import type { Document, EvalMessage } from "@flok-editor/session"; import { flash } from "./flashField.js"; export const remoteEvalFlash = (document: Document) => ViewPlugin.fromClass( class { _handleEval: any; constructor(view: EditorView) { this._handleEval = (msg: EvalMessage) => { const { docId, from, to } = msg; if (docId !== document.id) return; flash(view, from, to); }; document.session.on("eval", this._handleEval); } destroy() { document.session.off("eval", this._handleEval); } }, ); ================================================ FILE: packages/cm-eval/package.json ================================================ { "name": "@flok-editor/cm-eval", "version": "1.3.0", "description": "CodeMirror 6 extension for code evaluation", "author": "Damián Silvani ", "license": "GPL-3.0+", "type": "module", "files": [ "dist" ], "types": "./dist/index.d.ts", "module": "./dist/index.js", "main": "./dist/index.cjs", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" } }, "scripts": { "build": "tsc" }, "dependencies": { "debug": "^4.3.4" }, "devDependencies": { "@types/debug": "^4.1.7", "@types/lodash": "^4.14.191", "@types/node": "^18.14.6", "@types/uuid": "^9.0.1", "prettier": "^3.4.2", "typescript": "^4.9.4" }, "peerDependencies": { "@codemirror/commands": "^6.2.2", "@codemirror/state": "^6.2.0", "@codemirror/view": "^6.9.2", "@flok-editor/session": "*", "codemirror": "^6.0.1" } } ================================================ FILE: packages/cm-eval/tsconfig.json ================================================ { "compilerOptions": { "target": "ESNext", "module": "ESNext", "lib": ["ESNext", "DOM"], "moduleResolution": "nodenext", "strict": false, "sourceMap": true, "declaration": true, "allowSyntheticDefaultImports": true, "outDir": "dist" }, "include": ["lib"] } ================================================ FILE: packages/example-vanilla-js/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: packages/example-vanilla-js/index.html ================================================ @flok-editor/codemirror example
================================================ FILE: packages/example-vanilla-js/main.js ================================================ import { EditorView, basicSetup } from "codemirror"; import { javascript } from "@codemirror/lang-javascript"; import { oneDark } from "@codemirror/theme-one-dark"; import { EditorState, Prec } from "@codemirror/state"; import { yCollab } from "y-codemirror.next"; import { Session } from "@flok-editor/session"; import { flashField, evalKeymap, remoteEvalFlash } from "@flok-editor/cm-eval"; import { UndoManager } from "yjs"; import "./style.css"; const flokBasicSetup = (doc) => { const text = doc.getText(); const undoManager = new UndoManager(text); // if target is hydra, use "web" mode to evaluate on browser only, not REPLs const web = doc.target === "hydra"; return [ flashField(), remoteEvalFlash(doc), Prec.high(evalKeymap(doc, { web })), yCollab(text, doc.session.awareness, { undoManager }), ]; }; const createEditor = (doc) => { const state = EditorState.create({ doc: doc.content, extensions: [ basicSetup, flokBasicSetup(doc), javascript(), EditorView.lineWrapping, oneDark, ], }); const editorEl = document.querySelector(`#${doc.id} .editor`); const view = new EditorView({ state, parent: editorEl, }); const targetEl = document.querySelector(`#${doc.id} .target`); targetEl.value = doc.target; targetEl.addEventListener("change", (e) => { doc.target = e.target.value; }); doc.session.on(`change-target:${doc.id}`, () => { targetEl.value = doc.target; }); return [state, view]; }; const handleMessage = (msg) => { console.log("message", msg); }; const handleEvalHydra = (msg) => { console.log("eval:hydra", msg); // evaluate hydra code here... }; const session = new Session("default", { port: 3000 }); window.session = session; session.on("change", (...args) => console.log("change", ...args)); session.on("message", handleMessage); session.on("eval:hydra", handleEvalHydra); session.on("sync", () => { // If session is empty, create two documents if (session.getDocuments().length === 0) { session.setActiveDocuments([ { id: "slot1", target: "tidal" }, { id: "slot2", target: "hydra" }, ]); } // Create editors for each document session.getDocuments().map((doc) => createEditor(doc)); }); session.initialize(); ================================================ FILE: packages/example-vanilla-js/package.json ================================================ { "name": "example-vanilla-js", "private": true, "version": "1.3.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, "devDependencies": { "prettier": "^3.4.2", "vite": "^5.0.12" }, "dependencies": { "@codemirror/lang-javascript": "^6.1.4", "@codemirror/state": "^6.2.0", "@codemirror/theme-one-dark": "^6.1.1", "@codemirror/view": "^6.9.3", "@flok-editor/cm-eval": "^1.3.0", "@flok-editor/session": "^1.3.0", "codemirror": "^6.0.1", "y-codemirror.next": "^0.3.2", "y-indexeddb": "^9.0.9", "y-protocols": "^1.0.5", "y-webrtc": "^10.2.5", "y-websocket": "^1.5.0", "yjs": "^13.6.21" } } ================================================ FILE: packages/example-vanilla-js/style.css ================================================ body { background-color: #242424; color: #ccc; margin: 0; font-family: monospace; } .slots { display: flex; width: 100vw; height: 80vh; } .slot { flex-grow: 1; margin: 0.25em; width: 50%; } .slot .title { font-weight: 600; } ================================================ FILE: packages/lang-punctual/.gitignore ================================================ /node_modules package-lock.json /dist ================================================ FILE: packages/lang-punctual/.npmignore ================================================ /src /test /node_modules rollup.config.js tsconfig.json ================================================ FILE: packages/lang-punctual/LICENSE ================================================ MIT License Copyright (c) 2025 Damián Silvani and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/lang-punctual/README.md ================================================ # CodeMirror 6 language package template This is an example repository containing a minimal [CodeMirror](https://codemirror.net/6/) language support package. The idea is to clone it, rename it, and edit it to create support for a new language. Things you'll need to do (see the [language support example](https://codemirror.net/6/examples/lang-package/) for a more detailed tutorial): - `git grep EXAMPLE` and replace all instances with your language name. - Rewrite the grammar in `src/syntax.grammar` to cover your language. See the [Lezer system guide](https://lezer.codemirror.net/docs/guide/#writing-a-grammar) for information on this file format. - Adjust the metadata in `src/index.ts` to work with your new grammar. - Adjust the grammar tests in `test/cases.txt`. - Build (`npm run prepare`) and test (`npm test`). - Rewrite this readme file. - Optionally add a license. - Publish. Put your package on npm under a name like `codemirror-lang-EXAMPLE`. ================================================ FILE: packages/lang-punctual/package.json ================================================ { "name": "@flok-editor/lang-punctual", "version": "1.3.0", "description": "Punctual language support for CodeMirror", "scripts": { "build": "rollup -c" }, "type": "module", "main": "dist/index.cjs", "module": "dist/index.js", "exports": { "import": "./dist/index.js", "require": "./dist/index.cjs" }, "types": "dist/index.d.ts", "sideEffects": false, "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/legacy-modes": "^6.3.2", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" }, "devDependencies": { "@lezer/generator": "^1.0.0", "mocha": "^9.0.1", "prettier": "^3.4.2", "rollup": "^2.60.2", "rollup-plugin-dts": "^4.0.1", "rollup-plugin-ts": "^3.0.2", "typescript": "^4.3.4" }, "license": "MIT" } ================================================ FILE: packages/lang-punctual/rollup.config.js ================================================ import typescript from "rollup-plugin-ts"; import { lezer } from "@lezer/generator/rollup"; export default { input: "src/index.ts", external: (id) => id != "tslib" && !/^(\.?\/|\w:)/.test(id), output: [ { file: "dist/index.cjs", format: "cjs" }, { dir: "./dist", format: "es" }, ], plugins: [lezer(), typescript()], }; ================================================ FILE: packages/lang-punctual/src/indentation.ts ================================================ import { indentService } from "@codemirror/language"; export function indentation() { return indentService.of((context, pos) => { let { text, from } = context.lineAt(pos, -1); let parse = text.slice(0, pos - from).match(/^([^$#]+)\$.*/); if (parse) { return Math.min(parse[1].length, 8); } else { return 0; } }); } ================================================ FILE: packages/lang-punctual/src/index.ts ================================================ import { StreamLanguage } from "@codemirror/language"; import { punctualLanguage } from "./punctual"; import { indentation } from "./indentation"; export function punctual() { return [indentation(), StreamLanguage.define(punctualLanguage)]; } ================================================ FILE: packages/lang-punctual/src/punctual.ts ================================================ import { haskell } from "@codemirror/legacy-modes/mode/haskell"; export const punctualLanguage = { ...haskell, name: "punctual", languageData: { ...haskell.languageData, closeBrackets: { brackets: ["(", "[", "{", '"'], before: ')]}"' }, }, }; ================================================ FILE: packages/lang-punctual/tsconfig.json ================================================ { "compilerOptions": { "strict": true, "target": "es6", "module": "es2020", "newLine": "lf", "declaration": true, "moduleResolution": "node" }, "include": ["src/*.ts"] } ================================================ FILE: packages/lang-tidal/.gitignore ================================================ /node_modules package-lock.json /dist ================================================ FILE: packages/lang-tidal/.npmignore ================================================ /src /test /node_modules rollup.config.js tsconfig.json ================================================ FILE: packages/lang-tidal/LICENSE ================================================ MIT License Copyright (C) 2021 by Marijn Haverbeke and others Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/lang-tidal/README.md ================================================ # CodeMirror 6 language package template This is an example repository containing a minimal [CodeMirror](https://codemirror.net/6/) language support package. The idea is to clone it, rename it, and edit it to create support for a new language. Things you'll need to do (see the [language support example](https://codemirror.net/6/examples/lang-package/) for a more detailed tutorial): - `git grep EXAMPLE` and replace all instances with your language name. - Rewrite the grammar in `src/syntax.grammar` to cover your language. See the [Lezer system guide](https://lezer.codemirror.net/docs/guide/#writing-a-grammar) for information on this file format. - Adjust the metadata in `src/index.ts` to work with your new grammar. - Adjust the grammar tests in `test/cases.txt`. - Build (`npm run prepare`) and test (`npm test`). - Rewrite this readme file. - Optionally add a license. - Publish. Put your package on npm under a name like `codemirror-lang-EXAMPLE`. ================================================ FILE: packages/lang-tidal/package.json ================================================ { "name": "@flok-editor/lang-tidal", "version": "1.3.0", "description": "TidalCycles language support for CodeMirror", "scripts": { "build": "rollup -c" }, "type": "module", "main": "dist/index.cjs", "module": "dist/index.js", "exports": { "import": "./dist/index.js", "require": "./dist/index.cjs" }, "types": "dist/index.d.ts", "sideEffects": false, "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/legacy-modes": "^6.3.2", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" }, "devDependencies": { "@lezer/generator": "^1.0.0", "mocha": "^9.0.1", "prettier": "^3.4.2", "rollup": "^2.60.2", "rollup-plugin-dts": "^4.0.1", "rollup-plugin-ts": "^3.0.2", "typescript": "^4.3.4" }, "license": "MIT" } ================================================ FILE: packages/lang-tidal/rollup.config.js ================================================ import typescript from "rollup-plugin-ts"; import { lezer } from "@lezer/generator/rollup"; export default { input: "src/index.ts", external: (id) => id != "tslib" && !/^(\.?\/|\w:)/.test(id), output: [ { file: "dist/index.cjs", format: "cjs" }, { dir: "./dist", format: "es" }, ], plugins: [lezer(), typescript()], }; ================================================ FILE: packages/lang-tidal/src/indentation.ts ================================================ import { indentService } from "@codemirror/language"; export function indentation() { return indentService.of((context, pos) => { let { text, from } = context.lineAt(pos, -1); let parse = text.slice(0, pos - from).match(/^([^$#]+)\$.*/); if (parse) { return Math.min(parse[1].length, 8); } else { return 0; } }); } ================================================ FILE: packages/lang-tidal/src/index.ts ================================================ import { StreamLanguage } from "@codemirror/language"; import { tidalLanguage } from "./tidal"; import { indentation } from "./indentation"; export function tidal() { return [indentation(), StreamLanguage.define(tidalLanguage)]; } ================================================ FILE: packages/lang-tidal/src/tidal.ts ================================================ import { haskell } from "@codemirror/legacy-modes/mode/haskell"; export const tidalLanguage = { ...haskell, name: "tidal", languageData: { ...haskell.languageData, closeBrackets: { brackets: ["(", "[", "{", "<", '"'], before: ')]}>"' }, }, }; ================================================ FILE: packages/lang-tidal/tsconfig.json ================================================ { "compilerOptions": { "strict": true, "target": "es6", "module": "es2020", "newLine": "lf", "declaration": true, "moduleResolution": "node" }, "include": ["src/*.ts"] } ================================================ FILE: packages/pubsub/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: packages/pubsub/README.md ================================================ # @flok-editor/pubsub WebSocket-based Pub/Sub client and server, used for remote code execution and message passing in Flok. ## Features - Basic Publish/Subscribe functionality: `subscribe`, `unsubscribe`, `publish`, `unsubscribeAll`. - Payload is JSON serialized, topics are any string. - Allows subscribing or unsubscribing without being connected by storing state on the client. - Automatically reconnects if connection is lost, recovering client's state. - Ping/pong mechanism for detecting and closing broken connections both on client and server. ## Usage ### Server ```js import { WebSocketServer } from "ws"; import { PubSubServer } from "@flok-editor/pubsub"; // To use the server, you need to create a `WebSocketServer` and pass it to // `PubSubServer`. const wss = new WebSocketServer({ port: 4000 }); const server = new PubSubServer({ wss }); console.log(`PubSub server listening on`, wss.address()); ``` ### Client ```js import { PubSubClient } from "@flok-editor/pubsub"; const client = new PubSubClient({ url: "ws://localhost:4000" }); // Subscribe to topics client.subscribe("b"); client.subscribe("a"); client.start(); // Wait for the connection to be made, otherwise published messages are discarded. let internalId; client.on("open", () => { // Publish a message (any JSON serializable object) to a topic internalId = setInterval(() => { client.publish("a", { salutation: "hello!" }); }, 2000); }); // Add an error event handler to ignore connection errors client.on("error", () => {}); client.on("close", () => clearInterval(internalId)); setTimeout(() => { // Unsubscribe from a topic client.unsubscribe("b"); // ... or from all topics with a single call client.unsubscribeAll(); }, 5000); // you can add a listener for all message events client.on("message", (topic, data) => { console.log("message", topic, data); }); // ...or only from a specific topic client.on("message:a", (data) => { console.log("message from topic 'a'", data); }); // Finally, you can subscribe and listen to messages in a single call client.subscribe("c", (data) => { console.log("message from 'c'", data); }); ``` ## Development Run `npm install` to install dependencies. Run `npm run build` to build package. ================================================ FILE: packages/pubsub/examples/client.js ================================================ import { PubSubClient } from "../dist/index.js"; const client = new PubSubClient({ url: "ws://localhost:4000" }); // Subscribe to topics client.subscribe("b"); client.subscribe("a"); client.start(); // Wait for the connection to be made, otherwise published messages are discarded. let internalId; client.on("open", () => { // Publish a message (any JSON serializable object) to a topic internalId = setInterval(() => { client.publish("a", { salutation: "hello!" }); }, 2000); }); // Add an error event handler to ignore connection errors client.on("error", () => {}); client.on("close", () => clearInterval(internalId)); setTimeout(() => { // Unsubscribe from a topic client.unsubscribe("b"); // ... or from all topics with a single call client.unsubscribeAll(); }, 5000); // you can add a listener for all message events client.on("message", (topic, data) => { console.log("message", topic, data); }); // ...or only from a specific topic client.on("message:a", (data) => { console.log("message from topic 'a'", data); }); ================================================ FILE: packages/pubsub/examples/server.js ================================================ import { WebSocketServer } from "ws"; import { PubSubServer } from "../dist/server.js"; const wss = new WebSocketServer({ port: 4000 }); const server = new PubSubServer({ wss }); console.log(`PubSub server listening on`, wss.address()); ================================================ FILE: packages/pubsub/lib/client.ts ================================================ import WebSocket from "isomorphic-ws"; import debugModule from "debug"; import { EventEmitter } from "events"; import type { ServerMessage } from "./server.js"; const debug = debugModule("flok:pubsub:client"); type ClientMessageType = | "publish" | "subscribe" | "unsubscribe" | "unsubscribe-all" | "state"; type ClientEvent = | "start" | "stop" | "open" | "close" | "error" | "message" | `message:${string}`; export class PubSubClient { readonly url: string; reconnectTimeout: number = 1000; protected _ws: WebSocket; protected _started: boolean = false; protected _connected: boolean = false; protected _subscriptions: Set = new Set(); protected _clientId: string; protected _emitter: EventEmitter = new EventEmitter(); constructor({ url = "ws://localhost:3000/", reconnectTimeout = 1000, }: { url: string; reconnectTimeout?: number; }) { this.url = url; this.reconnectTimeout = reconnectTimeout; } start() { if (this._started) return; this._connect(); this._started = true; this._emitter.emit("start"); debug("started"); } stop() { if (!this._started) return; if (this._ws.readyState === WebSocket.OPEN) this._ws.close(); this._subscriptions.clear(); this._started = false; this._ws = null; this._emitter.emit("stop"); debug("stopped"); } destroy() { this._subscriptions.forEach((sub) => this.removeAllListeners(sub)); this.stop(); debug("destroyed"); } on(eventName: ClientEvent, cb: (...args: any[]) => void) { this._emitter.on(eventName, cb); } off(eventName: ClientEvent, cb: (...args: any[]) => void) { this._emitter.off(eventName, cb); } once(eventName: ClientEvent, cb: (...args: any[]) => void) { this._emitter.once(eventName, cb); } removeAllListeners(eventName: string) { this._emitter.removeAllListeners(eventName); } publish(topic: string, msg: any) { if (this._connected) this._send("publish", { topic, msg }); } subscribe(topic: string, cb?: (...args: any[]) => void) { if (this._connected) this._send("subscribe", { topic }); this._subscriptions.add(topic); if (cb) { const event: ClientEvent = `message:${topic}`; this.removeAllListeners(event); this.on(event, cb); } } unsubscribe(topic: string) { if (this._connected) this._send("unsubscribe", { topic }); this._subscriptions.delete(topic); this.removeAllListeners(`message:${topic}`); } unsubscribeAll() { if (this._connected) this._send("unsubscribe-all"); this._subscriptions.clear(); } get id() { return this._clientId; } protected _connect() { debug("create WebSocket on", this.url); // If on Node, we need to pass `rejectUnauthorized: false` to avoid "unable // to verify certificate" error. This is important when using a self-signed // SSL certificate. if (typeof window === "undefined") { this._ws = new WebSocket(this.url, { rejectUnauthorized: false }); } else { this._ws = new WebSocket(this.url); } this._ws.onopen = () => { if (!this._ws) return; debug("open"); this._connected = true; this._notifyState(); this._emitter.emit("open"); }; this._ws.onclose = () => { if (!this._ws) return; debug("close"); this._connected = false; if (this._started) setTimeout(() => this._connect(), this.reconnectTimeout); this._emitter.emit("close"); }; this._ws.onerror = (err: any) => { if (!this._ws) return; debug("error", err); this._emitter.emit("error", err); }; this._ws.onmessage = (event) => { if (!this._ws) return; const data: ServerMessage = JSON.parse(event.data.toString()); const { type, payload } = data; switch (type) { case "id": { debug("id", payload); const { id } = payload; this._clientId = id; break; } case "publish": { debug("message", payload); const { topic } = payload; this._emitter.emit("message", payload); this._emitter.emit(`message:${topic}`, payload); break; } default: { debug("ignoring unknown message", type); } } }; } protected _notifyState() { this._send("state", { topics: [...this._subscriptions] }); } protected _send( type: ClientMessageType, payload?: any, cb?: (err?: Error) => void, ) { const data = JSON.stringify({ type, payload }); this._ws.send(data, (err?: Error) => { debug("send", type); if (err) debug("error on send", err); cb && cb(err); }); } } ================================================ FILE: packages/pubsub/lib/index.ts ================================================ export * from "./client.js"; export * from "./server.js"; ================================================ FILE: packages/pubsub/lib/server.ts ================================================ import { WebSocketServer, type WebSocket } from "ws"; import { v1 as uuidv1 } from "uuid"; import debugModule from "debug"; const debug = debugModule("flok:pubsub:server"); export type PublishServerMessage = { type: "publish"; payload: { topic: string; message: object; publisher: string; fromMe: boolean; }; }; export type IdServerMessage = { type: "id"; payload: { id: string; }; }; export type ServerMessage = IdServerMessage | PublishServerMessage; export class PubSubServer { pingTimeout: number = 30000; protected _wss: WebSocketServer; protected _subscribers: { [topic: string]: Set } = {}; protected _clients: { [id: string]: WebSocket } = {}; protected _isAlive: { [id: string]: boolean } = {}; protected _pingIntervalId: any; constructor({ wss, pingTimeout = 30000, }: { wss: WebSocketServer; pingTimeout?: number; }) { this._wss = wss; this.pingTimeout = pingTimeout; this._addEventListeners(); this._setPingInterval(); } protected _handleListening(...args: any[]) { debug("listening", ...args); } protected _handleClose() { debug("closed"); clearInterval(this._pingIntervalId); } protected _handleError(err: Error) { debug("error", err); } protected _handleConnection(ws: WebSocket) { const id = uuidv1(); debug(`[${id}] connection`); this._clients[id] = ws; this._isAlive[id] = true; this._sendClientId(id); ws.on("message", (rawData) => { const data = JSON.parse(rawData.toString()); debug(`[${id}] message`, rawData.toString()); const { type, payload } = data; switch (type) { case "publish": { const { topic, msg } = payload; this._publish(topic, msg, id); break; } case "subscribe": { const { topic } = payload; this._subscribe(topic, id); break; } case "unsubscribe": { const { topic } = payload; this._unsubscribe(topic, id); break; } case "unsubscribe-all": { this._unsubscribeAll(id); break; } case "state": { const { topics } = payload; this._updateState(id, topics); break; } default: { debug("ignoring unknown message type", type); } } }); ws.on("error", (err) => { debug(`[${id}] error`, err); }); ws.on("pong", () => { this._isAlive[id] = true; }); ws.on("close", () => { debug(`[${id}] close`); // Remove ws from all subscribed topics this._unsubscribeAll(id); delete this._clients[id]; debug("clients after `close`:", Object.keys(this._clients)); }); } protected _addEventListeners() { this._wss.on("listening", this._handleListening.bind(this)); this._wss.on("connection", this._handleConnection.bind(this)); this._wss.on("close", this._handleClose.bind(this)); this._wss.on("error", this._handleError.bind(this)); } protected _setPingInterval() { this._pingIntervalId = setInterval(() => { Object.entries(this._clients).forEach(([id, ws]) => { if (!this._isAlive[id]) return ws.terminate(); this._isAlive[id] = false; ws.ping(); }); }, this.pingTimeout); } protected _sendClientId(id: string) { const dataObj: IdServerMessage = { type: "id", payload: { id }, }; const data = JSON.stringify(dataObj); this._clients[id].send(data, (err) => { if (!err) return; debug(`error sending id to client ${id}`, err); }); } protected _publish(topic: string, msg: object, publisher: string) { const subs = this._subscribers; if (!(topic in subs) || subs[topic].size === 0) return; subs[topic].forEach((id) => { const dataObj: PublishServerMessage = { type: "publish", payload: { topic, message: msg, publisher, fromMe: id === publisher }, }; const data = JSON.stringify(dataObj); this._clients[id].send(data, (err) => { if (!err) return; debug(`error publishing to client ${id}`, err); }); }); } protected _subscribe(topic: string, subscriber: string) { const subs = this._subscribers; if (!(topic in subs)) subs[topic] = new Set(); subs[topic].add(subscriber); debug("subscribers after `subscribe`:", this._subscribers); } protected _unsubscribe(topic: string, subscriber: string) { const subs = this._subscribers; if (subs[topic]) subs[topic].delete(subscriber); if (subs[topic] && subs[topic].size === 0) delete subs[topic]; debug("subscribers after `unsubscribe`:", this._subscribers); } protected _unsubscribeAll(subscriber: string) { Object.values(this._subscribers).forEach((subs) => { subs.delete(subscriber); }); this._deleteEmptySubscriberSets(); debug("subscribers after `unsubscribeAll`:", this._subscribers); } protected _deleteEmptySubscriberSets() { const topics = Object.keys(this._subscribers); topics.forEach((topic) => { if (this._subscribers[topic].size === 0) delete this._subscribers[topic]; }); } protected _updateState(subscriber: string, topics: string[]) { this._unsubscribeAll(subscriber); topics.forEach((topic) => this._subscribe(topic, subscriber)); } } ================================================ FILE: packages/pubsub/package.json ================================================ { "name": "@flok-editor/pubsub", "version": "1.3.0", "description": "Pub/Sub client-server, used for remote code execution and message passing on Flok", "author": "Damián Silvani ", "license": "GPL-3.0+", "type": "module", "files": [ "dist" ], "types": "./dist/index.d.ts", "module": "./dist/index.js", "main": "./dist/index.cjs", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" } }, "scripts": { "build": "tsc" }, "dependencies": { "bufferutil": "^4.0.7", "debug": "^4.3.4", "events": "^3.3.0", "isomorphic-ws": "^5.0.0", "utf-8-validate": "^6.0.3", "uuid": "^9.0.0", "ws": "^8.12.1" }, "devDependencies": { "@types/debug": "^4.1.7", "@types/node": "^18.14.6", "@types/uuid": "^9.0.1", "@types/ws": "^8.5.4", "prettier": "^3.4.2", "typescript": "^4.9.4" } } ================================================ FILE: packages/pubsub/tsconfig.json ================================================ { "compilerOptions": { "target": "ESNext", "module": "ESNext", "lib": ["ESNext", "DOM"], "moduleResolution": "nodenext", "strict": false, "sourceMap": true, "declaration": true, "allowSyntheticDefaultImports": true, "outDir": "dist" }, "include": ["lib"] } ================================================ FILE: packages/repl/bin/flok-repl.js ================================================ #!/usr/bin/env node import dotenv from "dotenv"; import process from "process"; import path from "path"; import fs from "fs"; import { Command } from "commander"; import { CommandREPL, replClasses } from "../dist/index.js"; import { fileURLToPath } from "url"; import debugModule from "debug"; const debug = debugModule("flok:repl"); dotenv.config(); const readConfig = (path) => { const raw = fs.readFileSync(path); return JSON.parse(raw.toString()); }; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const packageInfo = readConfig(path.resolve(__dirname, "../package.json")); const knownTypes = [ "command", ...Object.keys(replClasses).filter((repl) => repl !== "default"), ]; const program = new Command(); program.version(packageInfo.version); program .option("-t, --types ", "Type/s of REPL", ["command"]) .option("-H, --hub ", 'Server (or "hub") address', "ws://localhost:3000") .option("-s, --session-name ", "Session name", "default") .option("-n, --target-name ", "Use the specified target name") .option("-T, --tags ", "Tags for REPL messages") .option("--config ", "JSON configuration file") .option("--extra ", "Extra options in JSON") .option("--list-types", "List all known types of REPLs") .option("--path ", "Evaluation WebSockets server path", "/pubsub") .parse(process.argv); const opts = program.opts(); // Try to read config file (if --config was provided, or FLOK_CONFIG env var is defined) const configPath = opts.config || process.env.FLOK_CONFIG; const config = configPath ? readConfig(configPath) : {}; // Override config with command line options const options = ["types", "hub", "sessionName", "targetName", "tags", "path"]; options.forEach((opt) => { config[opt] = config[opt] || opts[opt]; }); const { hub, sessionName, targetName, tags, path: pubSubPath } = config; // Remove duplicates const types = [...new Set(config.types)]; // Prepare command and arguments const cmd = program.args[0]; const args = program.args.slice(1); // If asked to list types, print and exit if (opts.listTypes) { console.log("Known types:", knownTypes); process.exit(0); } const useDefaultREPL = types.some((type) => type === "command"); // If using default REPL and no command was specified, throw error if (useDefaultREPL && !cmd) { console.error( "You specified a 'command' type, but forgot to specify a REPL command (e.g.: flok-repl -- cat)", ); program.outputHelp(); process.exit(1); } // Check if all types are known if (!useDefaultREPL) { const unknownTypes = [ ...new Set(types.filter((type) => !knownTypes.includes(type))), ]; if (unknownTypes.length > 0) { console.error( `Unknown types: ${unknownTypes.join(", ")}. Must be one of:`, knownTypes, ); process.exit(1); } } // Extra options const { extra } = opts; let extraOptions = config.extra || {}; if (extra) { try { extraOptions = Object.assign(extraOptions, JSON.parse(extra)); } catch { console.error("Invalid extra options JSON object:", extra); process.exit(1); } } // Start... console.log("Hub address:", hub); console.log("Session name:", sessionName); if (targetName) console.log("Target name:", targetName); console.log("Types:", types); if (Object.keys(extraOptions).length > 0) console.log("Extra options:", extraOptions); types.forEach((type) => { const useDefaultREPL = type === "command"; // Set target based on name or type const target = targetName || (useDefaultREPL ? cmd : type); let replClient; if (useDefaultREPL) { replClient = new CommandREPL({ command: cmd, args: args, target, session: sessionName, tags, hub, pubSubPath, extraOptions, }); } else { const replClass = replClasses[type]; replClient = new replClass({ target, session: sessionName, tags, hub, pubSubPath, extraOptions, }); } replClient.start(); replClient.emitter.on("data", (data) => { const line = data.lines.join("\n"); if (line) { if (data.type === "stdin") { console.log(`< ${line}`); } else if (data.type === "stdout") { console.log(`> ${line}`); } else if (data.type === "stderr") { console.error(`> ${line}`); } } }); replClient.emitter.on("close", ({ code }) => { process.exit(code); }); }); ================================================ FILE: packages/repl/lib/index.ts ================================================ import { BaseREPL, BaseREPLContext, CommandREPL, CommandREPLContext, } from "./repl.js"; import TidalREPL from "./repl/tidal.js"; import SclangREPL, { RemoteSclangREPL } from "./repl/sclang.js"; import FoxDotREPL from "./repl/foxdot.js"; import RenardoREPL from "./repl/renardo.js"; import MercuryREPL from "./repl/mercury.js"; import SardineREPL from "./repl/sardine.js"; import DummyREPL from "./repl/dummy.js"; import path from "path"; import fs from "fs"; const replClasses = { default: CommandREPL, tidal: TidalREPL, sclang: SclangREPL, remote_sclang: RemoteSclangREPL, foxdot: FoxDotREPL, renardo: RenardoREPL, mercury: MercuryREPL, sardine: SardineREPL, dummy: DummyREPL }; function createREPLFor(repl: string, ctx: CommandREPLContext) { if (replClasses[repl]) { return new replClasses[repl](ctx); } const replClass = replClasses.default; return new replClass({ ...ctx, command: repl }); } function readPackageMetadata() { const packageJsonPath = path.resolve( __dirname, path.join("..", "package.json"), ); const rawBody = fs.readFileSync(packageJsonPath); const body = JSON.parse(rawBody.toString()); return body["flok"]; } export { replClasses, createREPLFor, readPackageMetadata, BaseREPL, BaseREPLContext, CommandREPL, CommandREPLContext, }; ================================================ FILE: packages/repl/lib/repl/dummy.ts ================================================ import { BaseREPL, BaseREPLContext } from "../repl.js"; import osc from "osc"; import debugModule from "debug"; const debug = debugModule("flok:repl:dummy"); const { UDPPort } = osc; // A dummy/free/open REPL // The repl doesn't have any specific language, it just forwards the // text to an assigned OSC port 3001 // The address used is /flok // $ flok-repl -t free // // Sends the code over OSC to port 3001 on localhost // Port can be assigned by choice // class DummyREPL extends BaseREPL { udpPort: typeof UDPPort; port: number; started: boolean; portReady: boolean; constructor(ctx: BaseREPLContext) { super(ctx); this.port = 3001; this.started = false; this.portReady = false; } start() { super.start(); this.udpPort = new UDPPort({ metadata: true, }); // Listen for incoming OSC messages. this.udpPort.on("message", function (oscMsg, timeTag, info) { debug("An OSC message just arrived!", oscMsg); debug("Remote info is: ", info); }); // Open the socket. this.udpPort.open(); // When the port is read, send an OSC message const that = this; this.udpPort.on("ready", function () { that.portReady = true; }); this.started = true; } write(body: string) { if (!this.portReady) { debug("UDP Port is not ready yet."); return; } const newBody = this.prepare(body); const obj = { address: "/flok", args: [ { type: "s", value: newBody, }, ], }; this.udpPort.send(obj, "127.0.0.1", this.port); const lines = newBody.split("\n"); this.emitter.emit("data", { type: "stdin", lines }); } } export default DummyREPL; ================================================ FILE: packages/repl/lib/repl/foxdot.ts ================================================ import { CommandREPL, CommandREPLContext } from "../repl.js"; class FoxDotREPL extends CommandREPL { constructor(ctx: CommandREPLContext) { super(ctx); this.command = this.commandPath(); this.args = ["-i", "-c", '"from FoxDot import *\nload_startup_file()"']; } // eslint-disable-next-line class-methods-use-this prepare(body: string): string { return `execute\(\"${body .replace(/(\n)/gm, "\\n") .replace(/(\")/gm, '\\"') .trim()}\"\)\n`; } commandPath(): string { const { python } = this.extraOptions; return python || "python"; } } export default FoxDotREPL; ================================================ FILE: packages/repl/lib/repl/mercury.ts ================================================ import { BaseREPL, BaseREPLContext } from "../repl.js"; import osc from "osc"; import debugModule from "debug"; const debug = debugModule("flok:repl:mercury"); const { UDPPort } = osc; // The Mercury REPL // $ flok-repl -t mercury // // Sends the code over OSC to port 4880 on localhost // Start the mercury_ide.maxproj in Max8 // Turn on the audio if you want to code sound only // Turn on the visuals if you want to code visuals as well // // When executing code it should automatically receive and parse // Mercury only runs full pages of code (previous code is deleted) // So always execute full page instead of per-line // class MercuryREPL extends BaseREPL { udpPort: typeof UDPPort; port: number; started: boolean; portReady: boolean; constructor(ctx: BaseREPLContext) { super(ctx); this.port = 4880; this.started = false; this.portReady = false; } start() { super.start(); this.udpPort = new UDPPort({ metadata: true, }); // Listen for incoming OSC messages. this.udpPort.on("message", function (oscMsg, timeTag, info) { debug("An OSC message just arrived!", oscMsg); debug("Remote info is: ", info); }); // Open the socket. this.udpPort.open(); // When the port is read, send an OSC message to, say, SuperCollider const that = this; this.udpPort.on("ready", function () { that.portReady = true; }); this.started = true; } write(body: string) { if (!this.portReady) { debug("UDP Port is not ready yet."); return; } const newBody = this.prepare(body); const obj = { address: "/mercury-code", args: [ { type: "s", value: newBody, }, ], }; this.udpPort.send(obj, "127.0.0.1", this.port); const lines = newBody.split("\n"); this.emitter.emit("data", { type: "stdin", lines }); } } export default MercuryREPL; ================================================ FILE: packages/repl/lib/repl/renardo.ts ================================================ import { CommandREPL, CommandREPLContext } from "../repl.js"; class RenardoREPL extends CommandREPL { constructor(ctx: CommandREPLContext) { super(ctx); this.command = this.commandPath(); this.args = ["-i", "-c", '"from renardo_lib import *"']; } // eslint-disable-next-line class-methods-use-this prepare(body: string): string { return `execute\(\"${body .replace(/(\n)/gm, "\\n") .replace(/(\")/gm, '\\"') .trim()}\"\)\n`; } commandPath(): string { const { python } = this.extraOptions; return python || "python"; } } export default RenardoREPL; ================================================ FILE: packages/repl/lib/repl/sardine.ts ================================================ import { CommandREPL, CommandREPLContext } from "../repl.js"; class SardineREPL extends CommandREPL { constructor(ctx: CommandREPLContext) { super(ctx); this.command = this.commandPath(); this.args = []; } commandPath(): string { const { python } = this.extraOptions; return python || "sardine"; } } export default SardineREPL; ================================================ FILE: packages/repl/lib/repl/sclang.ts ================================================ import { BaseREPL, CommandREPL, BaseREPLContext, CommandREPLContext, } from "../repl.js"; import os from "os"; import osc from "osc"; import debugModule from "debug"; const debug = debugModule("flok:repl:sclang"); const { UDPPort } = osc; class SclangREPL extends CommandREPL { constructor(ctx: CommandREPLContext) { super(ctx); this.command = this.commandPath(); } // eslint-disable-next-line class-methods-use-this prepare(body: string): string { const fixedBody = body .replace(/(\n\s*\)\s*\n)/gm, "\n);\n") .replace(/(\n)/gm, " ") .trim(); return `${fixedBody}\n`; } commandPath(): string { const { sclang } = this.extraOptions; return sclang || SclangREPL.defaultCommandPath(); } static defaultCommandPath(): string { switch (os.platform()) { case "darwin": return "/Applications/SuperCollider.app/Contents/MacOS/sclang"; case "linux": return "sclang"; default: throw "Unsupported platform"; } } } class RemoteSclangREPL extends BaseREPL { udpPort: typeof UDPPort; port: number; started: boolean; portReady: boolean; constructor(ctx: BaseREPLContext) { super(ctx); this.port = 57200; this.started = false; this.portReady = false; } start() { super.start(); this.udpPort = new UDPPort({ metadata: true, }); // Listen for incoming OSC messages. this.udpPort.on("message", function (oscMsg, timeTag, info) { debug("An OSC message just arrived!", oscMsg); debug("Remote info is: ", info); }); // Open the socket. this.udpPort.open(); // When the port is read, send an OSC message to, say, SuperCollider const that = this; this.udpPort.on("ready", function () { that.portReady = true; }); this.started = true; } write(body: string) { if (!this.portReady) { debug("UDP Port is not ready yet."); return; } const newBody = this.prepare(body); const obj = { address: "/flok", args: [ { type: "s", value: newBody, }, ], }; this.udpPort.send(obj, "127.0.0.1", this.port); const lines = newBody.split("\n"); this.emitter.emit("data", { type: "stdin", lines }); } } export { SclangREPL, RemoteSclangREPL }; export default SclangREPL; ================================================ FILE: packages/repl/lib/repl/tidal.ts ================================================ import { execSync } from "child_process"; import * as path from "path"; import { CommandREPL, CommandREPLContext } from "../repl.js"; import debugModule from "debug"; const debug = debugModule("flok:repl:tidal"); class TidalREPL extends CommandREPL { constructor(ctx: CommandREPLContext) { super(ctx); this.command = this.commandPath("ghci"); this.args = ["-ghci-script", this.bootScript()]; } prepare(body: string): string { let newBody = super.prepare(body); newBody = `:{\n${newBody}\n:}`; return newBody; } handleData(type: string, lines: string[]): string[] { return type == "stdout" ? lines.map((line) => line.replace(/(tidal> )+/i, "")) : lines; } bootScript(): string { const { bootScript } = this.extraOptions; return bootScript || this.defaultBootScript(); } defaultBootScript(): string { return path.join(this.dataDir(), "BootTidal.hs"); } dataDir(): string { const ghciCmd = this.commandPath("ghci"); try { const dataDir = execSync(`${ghciCmd} -e Paths_tidal.getDataDir`) .toString() .trim() .replace(/"/g, ""); debug("Data dir:", dataDir); return dataDir; } catch (err) { debug(`Failed to get tidal data dir`); debug( `You will need to specify the location of your TidalCycles bootloading script.\n` + `Read more: https://github.com/munshkr/flok/wiki/Failed-to-get-tidal-data-dir`, ); throw err; } } commandPath(cmd: string): string { const { ghci, useStack } = this.extraOptions; if (ghci) return ghci; return useStack ? `stack exec -- ${cmd}` : cmd; } } export default TidalREPL; ================================================ FILE: packages/repl/lib/repl.ts ================================================ import { ChildProcess, spawn } from "child_process"; import { EventEmitter } from "events"; import { PubSubClient } from "@flok-editor/pubsub"; import debugModule from "debug"; const debug = debugModule("flok:repl"); type Message = { body: string; userName: string; }; type BaseREPLContext = { target: string; session: string; tags: string[]; hub: string; pubSubPath: string; extraOptions?: { [option: string]: any }; }; type CommandREPLContext = BaseREPLContext & { command: string; args: string[]; }; abstract class BaseREPL { target: string; session: string; tags: string[]; hub: string; pubSubPath: string; extraOptions: { [option: string]: any }; emitter: EventEmitter; pubSub: PubSubClient; _buffers: { stdout: string; stderr: string }; constructor(ctx: BaseREPLContext) { const { target, session, tags, hub, pubSubPath, extraOptions } = ctx; this.target = target || "default"; this.session = session || "default"; this.tags = tags || []; this.hub = hub || "ws://localhost:3000"; this.pubSubPath = pubSubPath || "/pubsub"; this.extraOptions = extraOptions || {}; this.emitter = new EventEmitter(); this._connectToPubSubServer(); this._buffers = { stdout: "", stderr: "" }; } start() { // Subscribe to pub sub const { target, session } = this; this.pubSub.subscribe( `session:${session}:target:${target}:in`, ({ message }: { message: Message }) => { const { body } = message; this.write(body); }, ); } abstract write(body: string); // eslint-disable-next-line class-methods-use-this prepare(body: string): string { return body.trim(); } _connectToPubSubServer() { this.pubSub = new PubSubClient({ url: `${this.hub}${this.pubSubPath}` }); this.pubSub.start(); this.pubSub.on("error", (err) => { debug("error", err); }); this.pubSub.on("open", () => { debug("open"); }); } } class CommandREPL extends BaseREPL { command: string; args: string[]; repl: ChildProcess; constructor(ctx: CommandREPLContext) { const { target, session, tags, hub, pubSubPath, extraOptions } = ctx; super({ target, session, tags, hub, pubSubPath, extraOptions, }); const { command, args } = ctx; this.command = command; this.args = args; } start() { super.start(); // Spawn process const cmd = this.command; const args = this.args; debug(`Spawn '${cmd}' with args:`, args); this.repl = spawn(cmd, args, { shell: true }); // Handle stdout and stderr this.repl.stdout.on("data", (data: any) => { this._handleData(data, "stdout"); }); this.repl.stderr.on("data", (data: any) => { this._handleData(data, "stderr"); }); this.repl.on("close", (code: number) => { this.emitter.emit("close", { code }); debug(`Child process exited with code ${code}`); }); } write(body: string) { const newBody = this.prepare(body); this.repl.stdin.write(`${newBody}\n\n`); const lines = newBody.split("\n"); this.emitter.emit("data", { type: "stdin", lines }); } handleData(type: string, lines: string[]): string[] { return lines; } _handleData(data: any, type: string) { const { target, session, tags } = this; const newBuffer = this._buffers[type].concat(data.toString()); const rawLines = newBuffer.split("\n"); const basePath = `session:${session}:target:${target}`; this._buffers[type] = rawLines.pop(); const lines = this.handleData(type, rawLines); this.emitter.emit("data", { type, lines }); const mustPublish = lines.length > 0; if (mustPublish) { this.pubSub.publish(`${basePath}:out`, { target, type, body: lines, tags, }); } } } export { BaseREPL, BaseREPLContext, CommandREPL, CommandREPLContext }; ================================================ FILE: packages/repl/package.json ================================================ { "name": "flok-repl", "version": "1.3.0", "description": "REPL client for Flok", "author": "Damián Silvani ", "license": "GPL-3.0+", "type": "module", "files": [ "bin", "dist" ], "bin": "./bin/flok-repl.js", "types": "./dist/index.d.ts", "module": "./dist/index.js", "main": "./dist/index.cjs", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" } }, "scripts": { "build": "tsc" }, "dependencies": { "@flok-editor/pubsub": "^1.3.0", "command-exists": "^1.2.9", "commander": "^10.0.0", "debug": "^4.3.4", "dotenv": "^16.0.3", "glob": "^9.2.1", "osc": "^2.4.3" }, "devDependencies": { "@types/commander": "^2.12.2", "@types/debug": "^4.1.7", "@types/node": "^18.14.6", "prettier": "^3.4.2", "typescript": "^4.9.4" } } ================================================ FILE: packages/repl/tsconfig.json ================================================ { "compilerOptions": { "target": "ESNext", "module": "ESNext", "lib": ["ESNext", "DOM"], "moduleResolution": "nodenext", "strict": false, "sourceMap": true, "declaration": true, "allowSyntheticDefaultImports": true, "outDir": "dist" }, "include": ["lib"] } ================================================ FILE: packages/server/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: packages/server/bin/flok-server.js ================================================ #!/usr/bin/env node import process from "process"; import path from "path"; import fs from "fs"; import http from "http"; import { Command } from "commander"; import { fileURLToPath } from "url"; import withFlokServer from "@flok-editor/server-middleware"; const readConfig = (path) => { const raw = fs.readFileSync(path); return JSON.parse(raw.toString()); }; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const packageInfo = readConfig(path.resolve(__dirname, "../package.json")); const program = new Command(); program.version(packageInfo.version); program .option("-H, --host [HOST]", "Server host", "localhost") .option("-P, --port [PORT]", "Server port", 3000) .parse(process.argv); const opts = program.opts(); console.log(`> Flok server started. Listening on ${opts.host}:${opts.port}`); const server = http.createServer(); withFlokServer(server).listen(opts.port, opts.host); ================================================ FILE: packages/server/package.json ================================================ { "name": "flok-server", "version": "1.3.0", "description": "Flok server, handles WebSocket connections and WebRTC signaling", "author": "Damián Silvani ", "license": "GPL-3.0+", "type": "module", "files": [ "bin" ], "bin": "./bin/flok-server.js", "scripts": { "start": "node bin/flok-server.js" }, "dependencies": { "@flok-editor/server-middleware": "^1.3.0", "commander": "^10.0.1", "debug": "^4.3.4", "lib0": "^0.2.63", "y-protocols": "^1.0.5", "yjs": "^13.6.21" }, "devDependencies": { "prettier": "^3.4.2" } } ================================================ FILE: packages/server-middleware/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: packages/server-middleware/lib/index.ts ================================================ import url from "url"; import { WebSocketServer, type WebSocket } from "ws"; import http from "http"; import { PubSubServer } from "@flok-editor/pubsub"; import onYjsWsConnection from "./y-websocket-server.js"; import onSignalingWsConnection from "./signaling-server.js"; import debugModule from "debug"; const debug = debugModule("flok:server"); type FlokServer = http.Server & { _pubSubServer: PubSubServer }; export default function withFlokServer(server: http.Server): FlokServer { const topics: Map> = new Map(); const wss = new WebSocketServer({ noServer: true }); const docWss = new WebSocketServer({ noServer: true }); const pubsubWss = new WebSocketServer({ noServer: true }); const newServer = server as FlokServer; newServer.on("upgrade", (request, socket, head) => { const { pathname } = url.parse(request.url); if (pathname.startsWith("/signal")) { wss.handleUpgrade(request, socket, head, (...args: any[]) => { wss.emit("connection", ...args); }); } else if (pathname.startsWith("/doc")) { docWss.handleUpgrade(request, socket, head, (...args: any[]) => { docWss.emit("connection", ...args); }); } else if (pathname.startsWith("/pubsub")) { pubsubWss.handleUpgrade(request, socket, head, (...args: any[]) => { pubsubWss.emit("connection", ...args); }); } }); wss.on("connection", (conn: WebSocket) => { onSignalingWsConnection(conn, topics); }); docWss.on("connection", (conn: WebSocket, req: http.IncomingMessage) => { onYjsWsConnection(conn, req); }); // Prepare PubSub WebScoket server (pubsub) for code evaluation newServer._pubSubServer = new PubSubServer({ wss: pubsubWss }); return newServer; } ================================================ FILE: packages/server-middleware/lib/signaling-server.ts ================================================ import { map } from "lib0"; import debugModule from "debug"; const debug = debugModule("flok:server:signaling-server"); const wsReadyStateConnecting = 0; const wsReadyStateOpen = 1; const wsReadyStateClosing = 2; // eslint-disable-line const wsReadyStateClosed = 3; // eslint-disable-line const pingTimeout = 30000; export default (conn: any, topics: Map>) => { const subscribedTopics = new Set(); let closed = false; // Check if connection is still alive let pongReceived = true; const pingInterval = setInterval(() => { if (!pongReceived) { conn.close(); clearInterval(pingInterval); } else { pongReceived = false; try { conn.ping(); } catch (e) { conn.close(); } } }, pingTimeout); conn.on("pong", () => { pongReceived = true; }); conn.on("close", () => { subscribedTopics.forEach((topicName) => { const subs = topics.get(topicName) || new Set(); subs.delete(conn); if (subs.size === 0) { topics.delete(topicName); } }); subscribedTopics.clear(); closed = true; }); conn.on("message", (data: Buffer) => { const message = JSON.parse(data.toString()); if (message && message.type && !closed) { switch (message.type) { case "subscribe": /** @type {Array} */ (message.topics || []).forEach( (topicName: string) => { if (typeof topicName === "string") { // add conn to topic const topic = map.setIfUndefined( topics, topicName, () => new Set(), ); topic.add(conn); // add topic to conn subscribedTopics.add(topicName); } }, ); break; case "unsubscribe": /** @type {Array} */ (message.topics || []).forEach( (topicName: string) => { const subs = topics.get(topicName); if (subs) { subs.delete(conn); } }, ); break; case "publish": if (message.topic) { const receivers = topics.get(message.topic); if (receivers) { message.clients = receivers.size; receivers.forEach((receiver) => send(receiver, message)); } } break; case "ping": send(conn, { type: "pong" }); break; default: } } }); }; const send = (conn: WebSocket, message: object) => { if ( conn.readyState !== wsReadyStateConnecting && conn.readyState !== wsReadyStateOpen ) { conn.close(); } try { conn.send(JSON.stringify(message)); } catch (e) { conn.close(); } }; ================================================ FILE: packages/server-middleware/lib/y-websocket-server.ts ================================================ import { map, mutex, encoding, decoding } from "lib0"; import { Doc } from "yjs"; import * as awarenessProtocol from "y-protocols/awareness"; import * as syncProtocol from "y-protocols/sync"; import type http from "http"; import debugModule from "debug"; import type { WebSocket } from "ws"; const debug = debugModule("flok:server:y-websocket-server"); const wsReadyStateConnecting = 0; const wsReadyStateOpen = 1; const wsReadyStateClosing = 2; // eslint-disable-line const wsReadyStateClosed = 3; // eslint-disable-line // disable gc when using snapshots! const gcEnabled = process.env.GC !== "false" && process.env.GC !== "0"; const persistenceDir = process.env.YPERSISTENCE; /** * @type {{bindState: function(string,WSSharedDoc):void, writeState:function(string,WSSharedDoc):Promise}|null} */ let persistence = null; if (typeof persistenceDir === "string") { // @ts-ignore const LevelDbPersistence = require("y-leveldb").LevelDbPersistence; persistence = new LevelDbPersistence(persistenceDir); } const setPersistence = ( persistence_: { bindState: (arg0: string, arg1: WSSharedDoc) => void; writeState: (arg0: string, arg1: WSSharedDoc) => Promise; } | null, ) => { persistence = persistence_; }; const docs: Map = new Map(); const messageSync = 0; const messageAwareness = 1; // const messageAuth = 2 const updateHandler = (update: Uint8Array, origin: any, doc: WSSharedDoc) => { const encoder = encoding.createEncoder(); encoding.writeVarUint(encoder, messageSync); syncProtocol.writeUpdate(encoder, update); const message = encoding.toUint8Array(encoder); doc.conns.forEach((_, conn) => send(doc, conn, message)); }; export class WSSharedDoc extends Doc { name: string; mux: mutex.mutex; conns: Map>; awareness: awarenessProtocol.Awareness; constructor(name: string) { super({ gc: gcEnabled }); this.name = name; this.mux = mutex.createMutex(); /** * Maps from conn to set of controlled user ids. Delete all user ids from awareness when this conn is closed */ this.conns = new Map(); this.awareness = new awarenessProtocol.Awareness(this); this.awareness.setLocalState(null); /** * @param {{ added: Array, updated: Array, removed: Array }} changes * @param {Object | null} conn Origin is the connection that made the change */ const awarenessChangeHandler = ( { added, updated, removed, }: { added: number[]; updated: number[]; removed: number[] }, conn: any, ) => { const changedClients = added.concat(updated, removed); if (conn !== null) { const connControlledIDs = /** @type {Set} */ this.conns.get(conn); if (connControlledIDs !== undefined) { added.forEach((clientID) => { connControlledIDs.add(clientID); }); removed.forEach((clientID) => { connControlledIDs.delete(clientID); }); } } // broadcast awareness update const encoder = encoding.createEncoder(); encoding.writeVarUint(encoder, messageAwareness); encoding.writeVarUint8Array( encoder, awarenessProtocol.encodeAwarenessUpdate(this.awareness, changedClients), ); const buff = encoding.toUint8Array(encoder); this.conns.forEach((_, c) => { send(this, c, buff); }); }; this.awareness.on("change", awarenessChangeHandler); this.on("update", updateHandler); } } const messageListener = (conn: any, doc: WSSharedDoc, message: Uint8Array) => { const encoder = encoding.createEncoder(); const decoder = decoding.createDecoder(message); const messageType = decoding.readVarUint(decoder); switch (messageType) { case messageSync: encoding.writeVarUint(encoder, messageSync); syncProtocol.readSyncMessage(decoder, encoder, doc, null); if (encoding.length(encoder) > 1) { send(doc, conn, encoding.toUint8Array(encoder)); } break; case messageAwareness: { awarenessProtocol.applyAwarenessUpdate( doc.awareness, decoding.readVarUint8Array(decoder), conn, ); break; } } }; const closeConn = (doc: WSSharedDoc, conn: any) => { if (doc.conns.has(conn)) { const controlledIds: Set = doc.conns.get(conn); doc.conns.delete(conn); awarenessProtocol.removeAwarenessStates( doc.awareness, Array.from(controlledIds), null, ); if (doc.conns.size === 0 && persistence !== null) { // if persisted, we store state and destroy ydocument persistence.writeState(doc.name, doc).then(() => { doc.destroy(); }); docs.delete(doc.name); } } conn.close(); }; const send = (doc: WSSharedDoc, conn: any, m: Uint8Array) => { if ( conn.readyState !== wsReadyStateConnecting && conn.readyState !== wsReadyStateOpen ) { closeConn(doc, conn); } try { conn.send( m, /** @param {any} err */ (err) => { err != null && closeConn(doc, conn); }, ); } catch (e) { closeConn(doc, conn); } }; const pingTimeout = 30000; export const setupWSConnection = ( conn: WebSocket, req: http.IncomingMessage, { docName = req.url.slice(1).split("?")[0], gc = true }: any = {}, ) => { conn.binaryType = "arraybuffer"; // get doc, create if it does not exist yet const doc = map.setIfUndefined(docs, docName, () => { const doc = new WSSharedDoc(docName); doc.gc = gc; if (persistence !== null) { persistence.bindState(docName, doc); } docs.set(docName, doc); return doc; }); doc.conns.set(conn, new Set()); // listen and reply to events conn.on("message", (message: ArrayBuffer) => messageListener(conn, doc, new Uint8Array(message)), ); conn.on("close", () => { closeConn(doc, conn); }); // Check if connection is still alive let pongReceived = true; const pingInterval = setInterval(() => { if (!pongReceived) { if (doc.conns.has(conn)) { closeConn(doc, conn); } clearInterval(pingInterval); } else if (doc.conns.has(conn)) { pongReceived = false; try { conn.ping(); } catch (e) { closeConn(doc, conn); } } }, pingTimeout); conn.on("pong", () => { pongReceived = true; }); // send sync step 1 const encoder = encoding.createEncoder(); encoding.writeVarUint(encoder, messageSync); syncProtocol.writeSyncStep1(encoder, doc); send(doc, conn, encoding.toUint8Array(encoder)); const awarenessStates = doc.awareness.getStates(); if (awarenessStates.size > 0) { const encoder = encoding.createEncoder(); encoding.writeVarUint(encoder, messageAwareness); encoding.writeVarUint8Array( encoder, awarenessProtocol.encodeAwarenessUpdate( doc.awareness, Array.from(awarenessStates.keys()), ), ); send(doc, conn, encoding.toUint8Array(encoder)); } }; export default setupWSConnection; ================================================ FILE: packages/server-middleware/package.json ================================================ { "name": "@flok-editor/server-middleware", "version": "1.3.0", "description": "Server middleware for Flok, handles WebSocket connections and WebRTC signaling", "author": "Damián Silvani ", "license": "GPL-3.0+", "type": "module", "files": [ "bin", "dist" ], "types": "./dist/index.d.ts", "module": "./dist/index.js", "main": "./dist/index.cjs", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" } }, "scripts": { "build": "tsc" }, "dependencies": { "@flok-editor/pubsub": "^1.3.0", "debug": "^4.3.4" }, "devDependencies": { "@types/debug": "^4.1.7", "@types/node": "^18.14.6", "prettier": "^3.4.2", "typescript": "^4.9.4" }, "peerDependencies": { "lib0": "^0.2.63", "y-protocols": "^1.0.5", "yjs": "^13.6.21" } } ================================================ FILE: packages/server-middleware/tsconfig.json ================================================ { "compilerOptions": { "target": "ESNext", "module": "ESNext", "lib": ["ESNext", "DOM"], "moduleResolution": "nodenext", "strict": false, "sourceMap": true, "declaration": true, "allowSyntheticDefaultImports": true, "outDir": "dist" }, "include": ["lib"] } ================================================ FILE: packages/session/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: packages/session/lib/document.ts ================================================ import type { Session, EvalContext, EvalMode } from "./index.js"; import type * as Y from "yjs"; export class Document { id: string; session: Session; constructor(session: Session, id: string) { this.id = id; this.session = session; } get content(): string { return this.session.getTextString(this.id); } set content(newValue: string) { this.session.setTextString(this.id, newValue); } get target(): string { return this.session.getTarget(this.id); } set target(newValue: string) { this.session.setTarget(this.id, newValue); } getText(): Y.Text { return this.session.getText(this.id); } setTarget(newValue: string) { this.target = newValue; return this; } evaluate(body: string, context: EvalContext, mode: EvalMode = "default") { return this.session.evaluate(this.id, this.target, body, context, mode); } } export default Document; ================================================ FILE: packages/session/lib/index.ts ================================================ export * from "./session.js"; export * from "./document.js"; ================================================ FILE: packages/session/lib/session.ts ================================================ import type * as Y from "yjs"; import { uint32 } from "lib0/random"; import EventEmitter from "events"; import { IndexeddbPersistence } from "y-indexeddb"; import { WebrtcProvider } from "y-webrtc"; import { WebsocketProvider } from "y-websocket"; import { Awareness } from "y-protocols/awareness.js"; import { PubSubClient } from "@flok-editor/pubsub"; import { Doc } from "yjs"; import debugModule from "debug"; import { Document } from "./document.js"; const debug = debugModule("flok:session"); type Provider = "webrtc" | "websocket" | "indexeddb"; type SessionEvent = | "sync" | "eval" | "message" | "change" | `eval:${string}` | `message:${string}` | `change-target:${string}` | "ws:connect" | "ws:disconnect" | "pubsub:start" | "pubsub:stop" | "pubsub:open" | "pubsub:close" | "pubsub:error"; export interface UserColor { color: string; light: string; } export const userColors: UserColor[] = [ { color: "#30bced", light: "#30bced33" }, { color: "#6eeb83", light: "#6eeb8333" }, { color: "#ffbc42", light: "#ffbc4233" }, { color: "#ecd444", light: "#ecd44433" }, { color: "#ee6352", light: "#ee635233" }, { color: "#9ac2c9", light: "#9ac2c933" }, { color: "#8acb88", light: "#8acb8833" }, { color: "#1be7ff", light: "#1be7ff33" }, ]; export interface EvalContext { from: number | null; to: number | null; } export type EvalMode = | "default" // publish to :eval and :in topics (for REPL targets) | "web" // emit eval events directly and publish to :eval topic (for Web targets) | "webLocal"; // emit eval events directly, do not publish to :eval topic export interface EvalMessage extends EvalContext { docId: string; body: string; user: string; mode: EvalMode; } export interface SessionOptions { hostname?: string; port?: number; isSecure?: boolean; user?: string; providers?: Provider[]; extraSignalingServers?: string[]; } export class Session { hostname: string; port?: number; isSecure: boolean; name: string; yDoc: Doc; awareness: Awareness; _initialized: boolean = false; _synced: boolean = false; _wsConnected: boolean = false; _user: string; _userColor: UserColor; _providers: Provider[]; _extraSignalingServers: string[]; _idbProvider: IndexeddbPersistence; _webrtcProvider: WebrtcProvider; _wsProvider: WebsocketProvider; _pubSubClient: PubSubClient; _emitter: EventEmitter = new EventEmitter(); constructor(name: string, opts: SessionOptions = {}) { this.name = name; this.hostname = opts?.hostname || "localhost"; this.port = opts?.port; this.isSecure = opts?.isSecure || false; this._user = opts?.user || "Anonymous " + Math.floor(Math.random() * 100); this._userColor = userColors[uint32() % userColors.length]; this._providers = opts?.providers || ["webrtc", "websocket", "indexeddb"]; this._extraSignalingServers = opts?.extraSignalingServers || []; this._handleObserveSharedTypes = this._handleObserveSharedTypes.bind(this); } initialize() { if (this._initialized) return; this._prepareYjs(); this._preparePubSub(); this._initialized = true; this._emitter.emit("init"); debug("initialized"); } get user(): string { return this._user; } get userColor(): UserColor { return this._userColor; } set user(newUser: string) { this._user = newUser; this._updateUserStateField(); } set userColor(newUserColor: UserColor) { this._userColor = newUserColor; this._updateUserStateField(); } setActiveDocuments(items: { id: string; target?: string }[]) { const targets = this._yTargets(); const oldTargets = Object.fromEntries(targets.entries()); // Remove duplicates on items (duplicate ids) by creating an object/map const newTargets = Object.fromEntries( items.map(({ id, target }) => [id, target]), ); // Calculate ids to delete and ids to create const newIds = Object.keys(newTargets); const oldIds = Array.from(targets.keys()); const toDelete = oldIds.filter((id) => !newIds.includes(id)); const toAddOrUpdate = newIds.filter( (id) => !oldIds.includes(id) || oldTargets[id] !== newTargets[id], ); debug("toDelete", toDelete); debug("toAddOrUpdate", toAddOrUpdate); this.yDoc.transact(() => { toDelete.forEach((id) => targets.delete(id)); toAddOrUpdate.forEach((id) => targets.set(id, newTargets[id])); }); } getDocuments(): Document[] { return Array.from(this._yTargets().keys()).map( (id) => new Document(this, id), ); } getDocument(id: string): Document | null { if (!this._yTargets().has(id)) return; return new Document(this, id); } getTarget(id: string): string { return this._yTargets().get(id); } setTarget(id: string, target: string) { this._yTargets().set(id, target); } getText(id: string): Y.Text { return this._yText(id); } getTextString(id: string) { return this.getText(id).toString(); } setTextString(id: string, text: string) { const ytext = this._yText(id); if (ytext.toString() === text) return; this.yDoc.transact(() => { ytext.delete(0, ytext.length); ytext.insert(0, text); }); } evaluate( docId: string, target: string, body: string, context: EvalContext, mode: EvalMode = "default", ) { const msg: EvalMessage = { docId, body, user: this.user, mode, ...context, }; // If evaluating on browser, emit events directly if (mode === "web" || mode === "webLocal") { this._emitter.emit(`eval`, msg); this._emitter.emit(`eval:${target}`, msg); } // If not evaluating locally, publish to :eval topic if (mode !== "webLocal") { this._pubSubClient.publish( `session:${this.name}:target:${target}:eval`, msg, ); } } on(eventName: SessionEvent, cb: (...args: any[]) => void) { this._emitter.on(eventName, cb); } off(eventName: SessionEvent, cb: (...args: any[]) => void) { this._emitter.off(eventName, cb); } once(eventName: SessionEvent, cb: (...args: any[]) => void) { this._emitter.once(eventName, cb); } removeAllListeners(eventName?: SessionEvent) { this._emitter.removeAllListeners(eventName); } destroy() { this.removeAllListeners(); ["error", "open", "close"].forEach((e) => this._pubSubClient.removeAllListeners(e), ); this._synced = false; this._initialized = false; this._pubSubClient.destroy(); if (this._wsProvider && this._wsProvider.wsconnected) this._wsProvider.destroy(); if (this._webrtcProvider && !this._webrtcProvider.closed) this._webrtcProvider.destroy(); if (this._idbProvider) this._idbProvider.destroy(); this._yTargets().unobserve(this._handleObserveSharedTypes); this.yDoc.destroy(); this.awareness.destroy(); } get wsUrl() { const schema = this.isSecure ? `wss` : `ws`; return `${schema}://${this.hostname}${this.port ? `:${this.port}` : ""}`; } get synced() { return this._synced; } get wsConnected() { return this._wsConnected; } _prepareYjs() { this.yDoc = new Doc(); this.awareness = new Awareness(this.yDoc); this._updateUserStateField(); this._observeSharedTypes(); this._createProviders(); } _createProviders() { if (this._providers.includes("indexeddb")) { this._idbProvider = new IndexeddbPersistence(this.name, this.yDoc); this._idbProvider.on("synced", () => { if (!this._synced) { this._synced = true; this._emitter.emit("sync", "indexeddb"); debug("Synced first with IndexedDB"); } }); } if (this._providers.includes("webrtc")) { this._webrtcProvider = new WebrtcProvider(this.name, this.yDoc, { awareness: this.awareness, signaling: [`${this.wsUrl}/signal`, ...this._extraSignalingServers], }); this._webrtcProvider.on("synced", () => { if (!this._synced) { this._synced = true; this._emitter.emit("sync", "webrtc"); debug("Synced first with WebRTC"); } }); } if (this._providers.includes("websocket")) { this._wsProvider = new WebsocketProvider( `${this.wsUrl}/doc`, this.name, this.yDoc, { awareness: this.awareness }, ); this._wsProvider.on("synced", () => { if (!this._synced) { this._synced = true; this._emitter.emit("sync", "websocket"); debug("Synced first with WebSockets"); } }); this._wsProvider.on("status", ({ status }) => { if (status === "connected") { this._wsConnected = true; this._emitter.emit("ws:connect"); } else if (status === "disconnected") { this._wsConnected = false; this._emitter.emit("ws:disconnect"); } }); } } _preparePubSub() { this._pubSubClient = new PubSubClient({ url: `${this.wsUrl}/pubsub` }); this._pubSubClient.on("start", () => { this._emitter.emit("pubsub:start"); }); this._pubSubClient.on("stop", () => { this._emitter.emit("pubsub:stop"); }); this._pubSubClient.on("error", (err) => { debug("error on pubsub", err); this._emitter.emit("pubsub:error", err); }); this._pubSubClient.on("open", () => { this._emitter.emit("pubsub:open"); }); this._pubSubClient.on("close", () => { this._emitter.emit("pubsub:close"); }); this._pubSubClient.start(); } _subscribeToTarget(target: string) { if (!this._pubSubClient) return; // Subscribe to messages directed to a specific target this._pubSubClient.subscribe( `session:${this.name}:target:${target}:eval`, (args) => { debug(`session:${this.name}:target:${target}:eval`, args); const { fromMe, message } = args; const { mode } = message; // If mode is web or webLocal, and message is from me, do not emit // event because we already did it when calling .evaluate() if ((mode === "web" || mode === "webLocal") && fromMe) return; this._emitter.emit(`eval`, message); this._emitter.emit(`eval:${target}`, message); // If mode is web or webLocal, do not publish to :in topics (not a REPL target) if (mode === "web" || mode === "webLocal") return; // Notify to flok-repls this._pubSubClient.publish( `session:${this.name}:target:${target}:in`, message, ); }, ); this._pubSubClient.subscribe( `session:${this.name}:target:${target}:out`, (args) => { debug(`session:${this.name}:target:${target}:out`, args); this._emitter.emit(`message`, args); this._emitter.emit(`message:${target}`, args); }, ); // Subscribes to messages directed to ourselves this._pubSubClient.subscribe( `session:${this.name}:target:${target}:user:${this.user}:out`, (args) => { debug( `session:${this.name}:target:${target}:user:${this.user}:out`, args, ); this._emitter.emit(`message`, args); this._emitter.emit(`message:${target}`, args); }, ); } _unsubscribeTarget(target: string) { const topics = [ `session:${this.name}:target:${target}:eval`, `session:${this.name}:target:${target}:out`, `session:${this.name}:target:${target}:user:${this.user}:out`, ]; topics.forEach((topic) => this._pubSubClient.unsubscribe(topic)); } _updateUserStateField() { this.awareness.setLocalStateField("user", { name: this.user, color: this._userColor.color, colorLight: this._userColor.light, }); } _observeSharedTypes() { this._yTargets().observe(this._handleObserveSharedTypes); } protected _handleObserveSharedTypes(event: Y.YMapEvent) { const ymap = this._yTargets(); event.changes.keys.forEach((change, key) => { // If a target was added or updated, subscribe and emit change event if (change.action === "add" || change.action === "update") { const newValue = ymap.get(key); debug( `Document "${key}" was added or updated. New target: "${newValue}". ` + `Previous target: "${change.oldValue}".`, ); debug(`Subscribe to ${newValue}`); this._subscribeToTarget(newValue); this._emitter.emit(`change-target:${key}`, newValue, change.oldValue); } // If a target is not present anymore, unsubscribe on PubSub if (change.action === "update" || change.action === "delete") { const targets = Array.from(ymap.values()); if (!targets.includes(change.oldValue)) { debug(`Unsubscribe from ${change.oldValue}`); this._unsubscribeTarget(change.oldValue); } } }); this._emitter.emit("change", this.getDocuments()); } _yTargets(): Y.Map { return this.yDoc.getMap("targets"); } _yText(id: string): Y.Text { return this.yDoc.getText(`text:${id}`); } } export default Session; ================================================ FILE: packages/session/package.json ================================================ { "name": "@flok-editor/session", "version": "1.3.0", "description": "Flok Session package", "author": "Damián Silvani ", "license": "GPL-3.0+", "type": "module", "files": [ "dist" ], "types": "./dist/index.d.ts", "module": "./dist/index.js", "main": "./dist/index.cjs", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" } }, "scripts": { "build": "tsc" }, "dependencies": { "@flok-editor/pubsub": "^1.3.0", "debug": "^4.3.4", "events": "^3.3.0" }, "devDependencies": { "@types/debug": "^4.1.7", "prettier": "^3.4.2", "typescript": "^4.9.4" }, "peerDependencies": { "y-indexeddb": "^9.0.9", "y-protocols": "^1.0.5", "y-webrtc": "^10.2.4", "y-websocket": "^1.5.0", "yjs": "^13.6.21" } } ================================================ FILE: packages/session/tsconfig.json ================================================ { "compilerOptions": { "target": "ESNext", "module": "ESNext", "lib": ["ESNext", "DOM"], "moduleResolution": "nodenext", "strict": false, "sourceMap": true, "declaration": true, "allowSyntheticDefaultImports": true, "outDir": "dist" }, "include": ["lib"] } ================================================ FILE: packages/web/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? # Strudel public/assets/clockwork*.js ================================================ FILE: packages/web/.prettierignore ================================================ public src/lib/punctual.js ================================================ FILE: packages/web/bin/flok-web.js ================================================ #!/usr/bin/env node import process from "process"; import path from "path"; import fs from "fs"; import { Command } from "commander"; import { fileURLToPath } from "url"; import { startServer } from "../server.js"; const readConfig = (path) => { const raw = fs.readFileSync(path); return JSON.parse(raw.toString()); }; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const packageInfo = readConfig(path.resolve(__dirname, "../package.json")); const program = new Command(); program.version(packageInfo.version); program .option("-H, --host [HOST]", "Server host", "0.0.0.0") .option("-P, --port [PORT]", "Server port", 3000) .option("-s, --secure", "Serve on https (use SSL)", false) .option("--ssl-cert [PATH]", "Path to SSL certificate file (optional)") .option("--ssl-key [PATH]", "Path to SSL key file (optional)") .option("--static-dir [PATH]", "Path to static files (optional)") .parse(process.argv); const opts = program.opts(); if (!opts.sslKey) { opts.sslKey = path.resolve(__dirname, "../cert/key.pem"); } if (!opts.sslCert) { opts.sslCert = path.resolve(__dirname, "../cert/cert.pem"); } startServer({ mode: process.env.NODE_ENV || "production", hostname: opts.host, port: opts.port, secure: opts.secure, sslCert: opts.sslCert, sslKey: opts.sslKey, staticDir: opts.staticDir, }); ================================================ FILE: packages/web/cert/cert.pem ================================================ -----BEGIN CERTIFICATE----- MIIFbTCCA1WgAwIBAgIUD05r8PlDvPqVBEXaVtq85i18dPEwDQYJKoZIhvcNAQEL BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAgFw0yNDAxMDcxMjQ1MjJaGA8yMTIz MTIxNDEyNDUyMlowRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUx ITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCAiIwDQYJKoZIhvcN AQEBBQADggIPADCCAgoCggIBAKZbtZk+fzwc7V9G/59l+Lk625iH4XlWYBo249WA QHB3ti+cODz72VVh5TKHUEj9G5q+UIgZ0QP1MqFeUxdEYZ5tnAvNaJIr54OqKp9d njhfGFGFyILBDKfHsT4pxtJUjqxBQeO2Dr/vrAvy9KabGGSKoaUE75ylZ5xlGAmc +eS+Zrhs86C4ZvLJM1jJNaFjpS3N4c9Ly/YZ9GlpK+dXPRCCrIUbnNbqVCRaNlR7 MBwKmHGlUPVgFdZxEWKY8g5+6LR1XvaAcLQkNESDPrTEUn2KQmP0mvMZy4qI3Vqg dNQ7odSiPoIg79P/pn7VRtBPwe62khQH2jTMPxn7SZFnKOteIGdEj6c/Gj69PZgn oVON0zDquFB31u9Guiv00vNhVPdhKGLhQAo+79d9Z/XuSbR64VbHkpDeWQg9Gyy7 kjcEJuECmQNSf5qzIbY38sG1lpEzqpY+wsh/laKa+J3QBxE8cgdnnolPD3lHfThB MQlpQ4tVJrXxS4+KrnjIwEcNiAJaUj+EkyCimJzOxmBGnXNJ1PeEpzF1Z4yKlnBq cBXUvgNOJKIsFFmJd/JNvv8nMXuM9XKg1v4GewoutrIvbS8XVyT4lsQTUu0pa5Ce sxK4IZ55Svty20y+MiFW4SFu4UdroOtH7ELpQnOz9yHYHZ8k5ZZBeW2cgnUrgkjl u7plAgMBAAGjUzBRMB0GA1UdDgQWBBQ5g9DrmNU5JcBa7lHRe7N3kIYI7jAfBgNV HSMEGDAWgBQ5g9DrmNU5JcBa7lHRe7N3kIYI7jAPBgNVHRMBAf8EBTADAQH/MA0G CSqGSIb3DQEBCwUAA4ICAQB1iPaZMMTbZ37MUeWli3t3MNnH9gmjM8mB7SpcS5OS 0VXoxeX7ymoHf0GuOf54ccb+Bz8d7ispEITiESlHO6+TyDhj4j4ZnSdn+3S1t49Z PIYVvafjmZoY8EsrbTN6K+Ao1oQ2Kjmv0fC7o9hKfgSnbxiKxX1uVagjCATC/2FT KfGfeSEw38xV+VtmY/d0tuNs68ndt1PKCc1i1qZAKSGUUNetiW2+ruy+uwGHNNG5 dQvpCpM+5eW4TFhuUHhMqnKBtDwbQtfdZZvb0OXOPi14Sp9VIWnSkLa9fY1QbJwk 37aW9nif3RrCxpn2RO26v2/AK56bCc+D9ZPx/svbzDrJgA+Q8c4Uqas/l1SLaYyc +FGgYTfuTw/527hD9BGwyxQNX8018JdKxLH9841vy8o17WYedkwErdrtc9UFtarR gkZnI7qoaErOW489IdaTZVeixzgORQcHdAuYjSiXII0bZMfZRxg3tDguLrcSkgZQ psxD76aU7beLXNSv2Hog6UMsE/t2cleg/zJlb3FzG1O1aLeYUck2t0nALTJwbyyk Jz49ANnI2CU8xy34ZBpczUIZHREHZKzZixDsORL2W49j3lAjLw+a/bDCbVJ9b1a6 MqrpWsBoaoU5WRZMklL1bEJ2mjWfaY8lyb1crMkaWdVSwfA7VpposVhgtIsbAsoI LQ== -----END CERTIFICATE----- ================================================ FILE: packages/web/cert/key.pem ================================================ -----BEGIN PRIVATE KEY----- MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQCmW7WZPn88HO1f Rv+fZfi5OtuYh+F5VmAaNuPVgEBwd7YvnDg8+9lVYeUyh1BI/RuavlCIGdED9TKh XlMXRGGebZwLzWiSK+eDqiqfXZ44XxhRhciCwQynx7E+KcbSVI6sQUHjtg6/76wL 8vSmmxhkiqGlBO+cpWecZRgJnPnkvma4bPOguGbyyTNYyTWhY6UtzeHPS8v2GfRp aSvnVz0QgqyFG5zW6lQkWjZUezAcCphxpVD1YBXWcRFimPIOfui0dV72gHC0JDRE gz60xFJ9ikJj9JrzGcuKiN1aoHTUO6HUoj6CIO/T/6Z+1UbQT8HutpIUB9o0zD8Z +0mRZyjrXiBnRI+nPxo+vT2YJ6FTjdMw6rhQd9bvRror9NLzYVT3YShi4UAKPu/X fWf17km0euFWx5KQ3lkIPRssu5I3BCbhApkDUn+asyG2N/LBtZaRM6qWPsLIf5Wi mvid0AcRPHIHZ56JTw95R304QTEJaUOLVSa18UuPiq54yMBHDYgCWlI/hJMgopic zsZgRp1zSdT3hKcxdWeMipZwanAV1L4DTiSiLBRZiXfyTb7/JzF7jPVyoNb+BnsK LrayL20vF1ck+JbEE1LtKWuQnrMSuCGeeUr7cttMvjIhVuEhbuFHa6DrR+xC6UJz s/ch2B2fJOWWQXltnIJ1K4JI5bu6ZQIDAQABAoICAA2TRkpvEyrwoV45CPsU8ysK ZokX7YpdRhJdkFIH2TpUSoWwFdbEJoQVLQLmj+Kk5O/HwAKbOLc99xe7/sPTTLQE 9crwxCvJcWcJJ9lBZnvrJqzgYfBpmILIhOoxtovLYqkj2iCe5q06/asr9FL0LRVn SrGQqYz64m2cwk1mhe3oq7E5Eth2s8/0I0CHitzUqNIIDvk/kjFPBOblMjP6pn0G bNWf3ziafqtIwU47jz16j94WQ3kCkkWhjG2jVX1hVdQED+/Fo2zP14QPwbo2mxSr h6doeoyD+lwftxCCL4ZyJ06WvssXrPp7zjZjaRfuqkC0nU8NJP1R/YQ9QU+gP3Jz 0vslL6GK4tTAAa7QxEUG6uANfNo0+kDwsO7cj32qVkQ+W9fw5hRYKxWunyB8RXED alHMCSprgAsqPXsV22S60keF8dMKcq5pQ8cJi5Z6itBKMp8G4yLocp3LdOHLTA3n EXUva3fahyyvleNrslPJ9LvkzVjRhk91t7Gjc7CUgd6xSKbI2LbxTS9GTSo8V7oS idfnpmyRLZfIQAJ22pPJYnkiG6NT0dCruTkMNz6YBQs6UpzbWdq5Zn7UXGXoekLR 4cIcxcEBAAiZqPUsruqY4RGiud7szLQgDz13l+GU1H8GHLIbWjVmAviFD9VUsK7u JNqrF3Lm7WCurLBHxx6xAoIBAQDWnXos+D7AgTJBEnYVglAv/XCR6MrfwNjOvau7 Yg/cyGOm+cHEhjNu2swTgXjR4HA/L/6AzlETDgomsRfFGIpZbfwcqTotei88vVot Lec3SYvbq0Q7Rnwlhl+k/BzYO/L8WQfqgXAgdZ8Pc4Rag5j7XYYDoyiyUIK/+VjO 8iDE0HhT8H+l2lsGGi/YsB6Ir5Xjfeyv8nPC93PW/rcQosZPqCx2sAmCVNQH/VIG IdC/KF+g9UNY3aF88hAAwjRpgEOAXGY401z52agWL0qcnylM/LbvibBfApQTvXJ3 s0jZuQC0GBlxSD+beKZSlJ/THhvkk/4OcCWWHSONEegSHs0LAoIBAQDGcAUEsbNu fwaa4RbZGxkKvXvINHFm2wWrZyxJmoX9wUzaJ29LKEKBOPP45GzdUv5+7o7s0uAG iCLuv5toqpFfIz27LG+FogEBfQuPVZs0hY+7Co8FfPpryy5fvjcM9WBZySQ1qay2 ZvVGqHtXLiJLaIRiHNgqiOJ5kDOMBwQAOQN1qMhqI27G/q9tWpZNDq7DZm9Ib5vT RJYHRsrUS46ENhPk0lmAt9bO72NSg5SwPQjOCvJMcIzTAKMdJHFJE6GslprSiLoR MND2DpEturg4OmuqIz+nG4BWC9/A3Jrk5v2kBIBEuQn+sSwogBJdjcuvMTJWjIll KWgEz8gzL9xPAoIBAQDVo6fWkjwtd67mFhGUccePLjRcGyexO5DXpPoKK6DswFJr Cp74Gjui841JMY5rJoe2bvljkX4lgMlcINgvrLE0OwdIJLG0SbgyN7BH3zUW1VCz GLdwZkb5N92IKCwymOLWj24Q5E8REOWJBQ5Q6EVmnH/mqQm/D+RIZFgikedK5NeT f4oiOM55saHFi/SpTljgQB9YOvs/rwMSlzb3CYJuE1RHxg+BPR5g4axATHM3h2JC oUQsd1vlPDXv+2MfTr5jThe4I7efRCtOAj+8z7fWWo9kvmTi/3cWe3UycTdo/QAV RxQ0r54aDy1KcYb0KznK/gNergbMey9Do/qn5x9nAoIBADv8Mtgna4k0Zue8sS5x 7ZD8lIWBrOIdxUn6Bz48stJxc2zizNbYVbpAYCfVzT7eTsZKEPRwDn6K+pxXWYA7 R3SN76Q8G3426bzscukiRKeM1FUDLRbIn96j7eHNW1DUgArELej24JnG59AzMA27 iWxoLNSHyaSZ+nQq7hofKMt0cKJJokPLcDpBVQBmiNbEYHn65hrsehtUOVH7yWaB bJR00HC0UZACgrHNVaXk1rarzJSUZIhM4ZULNUOi94fSomXMpQKNiEmYCyLGZoZ/ Uh7VMiSdQSmfu5zHPB1N0pjtZrEFF00u7mGKZ0Ha7TJQocjUw1W8Z/AnoyUJNoia qCsCggEBALCIg1eg6S0TVn2kUYHHdSvfBaKQvvciKkggjA80Ijt3q0khz11zV36A +lLTraBqzPYc/v6Bfq8HG8Ku11pzV/S23Lx5DG4nai/0Qx346OLiquVctZQMJPi1 GUIBiF0gm+CMFXJQcS1zh2ylOR2MbTlkWR5qd97A1OqKtyd8aRac0WZ8O7Er/AKZ JAaQdMmyc4AHCpyvQbMwcFx4UEGj09kBCBI4a1MOrpl+CUeqBzV5nPswwhuEyS1Z J0I/5tcb1GTlkpj8GVwg2UlrgvAwhLE7RE1p85vZhXfBVEPd2lCScWZbZqHlGgJC PLab48CuoGIPiDPqxDddXkm1ikVYw3U= -----END PRIVATE KEY----- ================================================ FILE: packages/web/index.html ================================================ Flok
================================================ FILE: packages/web/package.json ================================================ { "name": "flok-web", "version": "1.3.0", "description": "Web server for Flok", "author": "Damián Silvani ", "license": "GPL-3.0+", "type": "module", "bin": "./bin/flok-web.js", "files": [ "bin", "dist", "cert", "server.js", "vite-express.js", "vite.config.ts" ], "scripts": { "dev": "cross-env NODE_ENV=development node ./bin/flok-web.js", "prebuild": "node script/prebuild.js", "build": "npm run prebuild && tsc && vite build", "start": "node ./bin/flok-web.js", "check": "tsc --noEmit", "lint": "prettier -c .", "format": "prettier -w ." }, "dependencies": { "@flok-editor/server-middleware": "^1.3.0", "@strudel/draw": "^1.2.0", "@uiw/codemirror-theme-andromeda": "^4.22.1", "@uiw/codemirror-theme-bespin": "^4.22.1", "@uiw/codemirror-theme-console": "^4.22.1", "@uiw/codemirror-theme-github": "^4.22.1", "@uiw/codemirror-theme-monokai": "^4.22.1", "@uiw/codemirror-theme-solarized": "^4.22.1", "@uiw/codemirror-theme-xcode": "^4.22.1", "commander": "^10.0.0", "compression": "^1.7.4", "express": "^4.18.2", "picocolors": "^1.0.0" }, "devDependencies": { "@codemirror/lang-javascript": "^6.2.1", "@codemirror/lang-python": "^6.1.3", "@codemirror/state": "^6.4.0", "@codemirror/view": "^6.23.0", "@flok-editor/cm-eval": "^1.3.0", "@flok-editor/lang-tidal": "^1.3.0", "@flok-editor/lang-punctual": "^1.3.0", "@flok-editor/session": "^1.3.0", "@radix-ui/react-dialog": "^1.1.4", "@radix-ui/react-dropdown-menu": "^2.1.4", "@radix-ui/react-label": "^2.1.1", "@radix-ui/react-menubar": "^1.1.4", "@radix-ui/react-popover": "^1.1.4", "@radix-ui/react-select": "^2.1.4", "@radix-ui/react-toast": "^1.2.4", "@radix-ui/react-toggle": "^1.1.1", "@radix-ui/react-tooltip": "^1.1.6", "@replit/codemirror-vim": "^6.2.1", "@strudel/codemirror": "^1.2.0", "@strudel/core": "^1.2.0", "@strudel/midi": "^1.2.0", "@strudel/mini": "^1.2.0", "@strudel/osc": "^1.2.0", "@strudel/serial": "^1.2.0", "@strudel/soundfonts": "^1.2.0", "@strudel/tonal": "^1.2.0", "@strudel/transpiler": "^1.2.0", "@strudel/webaudio": "^1.2.0", "@types/express": "^4.17.21", "@types/p5": "^1.7.6", "@types/react": "^18.2.43", "@types/react-dom": "^18.2.17", "@typescript-eslint/eslint-plugin": "^6.14.0", "@typescript-eslint/parser": "^6.14.0", "@uiw/codemirror-themes": "^4.22.0", "@uiw/react-codemirror": "^4.19.11", "@vitejs/plugin-react": "^4.2.1", "autoprefixer": "^10.4.14", "class-variance-authority": "^0.4.0", "clsx": "^1.2.1", "cmdk": "^0.2.0", "codemirror": "^6.0.1", "cross-env": "^7.0.3", "eslint": "^8.55.0", "eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-refresh": "^0.4.5", "hydra-synth": "^1.3.29", "lucide-react": "^0.128.0", "mercury-engine": "^1.3.1", "p5": "^1.9.0", "postcss": "^8.4.21", "prettier": "^3.4.2", "react": "^19.0.0", "react-dom": "^19.0.0", "react-helmet-async": "^1.3.0", "react-router-dom": "^6.9.0", "tailwind-merge": "^1.10.0", "tailwindcss": "^3.2.7", "tailwindcss-animate": "^1.0.5", "typescript": "^5.3.3", "unique-names-generator": "^4.7.1", "unplugin-fonts": "^1.1.1", "vite": "^5.0.12", "vite-plugin-node-polyfills": "^0.19.0", "y-codemirror.next": "github:munshkr/y-codemirror.next#dee71ac8d65bc640db60a188b916d1a0147a9439", "y-indexeddb": "^9.0.9", "y-protocols": "^1.0.5", "y-webrtc": "^10.2.5", "y-websocket": "^1.5.0", "yjs": "^13.6.21" } } ================================================ FILE: packages/web/postcss.config.cjs ================================================ module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, }; ================================================ FILE: packages/web/script/prebuild.js ================================================ // This script is executed before the build process starts. It can be used to // do some pre-build tasks like copying files, etc. that are required for the // build process. import { existsSync, mkdirSync, readdirSync, copyFileSync } from "fs"; import { fileURLToPath } from "url"; import { resolve, dirname } from "path"; // Strudel // * mkdir -p public/assets // * cp ../../node_modules/@strudel/core/dist/assets/clockworker--*.js to /public/assets/ const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const publicAssetsDir = resolve(__dirname, "../public/assets"); const strudelAssetsDir = resolve( __dirname, "../../../node_modules/@strudel/core/dist/assets", ); if (!existsSync(publicAssetsDir)) { mkdirSync(publicAssetsDir, { recursive: true }); } const files = readdirSync(strudelAssetsDir).filter((file) => file.startsWith("clockworker--"), ); files.forEach((file) => { const src = resolve(strudelAssetsDir, file); const dest = resolve(publicAssetsDir, file); copyFileSync(src, dest); }); ================================================ FILE: packages/web/server.js ================================================ import withFlokServer from "@flok-editor/server-middleware"; import express from "express"; import compression from "compression"; import fs from "fs"; import http from "http"; import https from "https"; import { networkInterfaces } from "os"; import pc from "picocolors"; import process from "process"; import ViteExpress from "./vite-express.js"; import { fileURLToPath } from "url"; import path from "path"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); function info(msg) { const timestamp = new Date().toLocaleString("en-US").split(",")[1].trim(); console.log( `${pc.dim(timestamp)} ${pc.bold(pc.cyan("[flok-web]"))} ${pc.green(msg)}`, ); } export async function startServer({ onReady, staticDir, ...opts }) { try { const app = express(); app.use(compression()); if (staticDir) { info(`Serving extra static files at ${pc.gray(staticDir)}`); app.use(express.static(staticDir)); } let viteServer; if (opts.secure) { info( `Using SSL certificate at ${pc.gray(opts.sslCert)} (key at ${pc.gray(opts.sslKey)})`, ); const key = fs.readFileSync(opts.sslKey); const cert = fs.readFileSync(opts.sslCert); viteServer = https.createServer({ key, cert }, app); } else { viteServer = http.createServer(app); } ViteExpress.config({ mode: opts?.mode || "development", inlineViteConfig: { root: path.resolve(__dirname), }, viteConfigFile: path.resolve(__dirname, "vite.config.ts"), vitePort: opts.port, }); ViteExpress.bind(app, viteServer); const server = withFlokServer(viteServer); server.listen( opts.port, onReady || (() => { const netResults = getPossibleIpAddresses(); const schema = opts.secure ? "https" : "http"; info(`Listening on ${schema}://localhost:${opts.port}`); if (netResults.length > 1) { info("If on LAN, try sharing with your friends one of these URLs:"); Object.entries(netResults).map(([k, v]) => { info(`\t${k}: ${schema}://${v}:${opts.port}`); }); } else { info( `If on LAN, try sharing with your friends ${schema}://${Object.values(netResults)[0]}:${opts.port}`, ); } }), ); } catch (err) { console.error(err); process.exit(1); } } const getPossibleIpAddresses = () => { const nets = networkInterfaces(); const results = Object.create(null); // Or just '{}', an empty object for (const name of Object.keys(nets)) { for (const net of nets[name]) { // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses if (net.family === "IPv4" && !net.internal) { if (!results[name]) { results[name] = []; } results[name].push(net.address); } } } return results; }; ================================================ FILE: packages/web/src/assets/fonts/BigBlue/LICENSE.TXT ================================================ Attribution-ShareAlike 4.0 International ======================================================================= Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More_considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= Creative Commons Attribution-ShareAlike 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part; and b. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply. c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. b. ShareAlike. In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. ================================================ FILE: packages/web/src/assets/fonts/BigBlue/stylesheet.css ================================================ @font-face { font-family: "BigBlue TerminalPlus"; src: url("BigBlue_TerminalPlus.woff2") format("woff2"), url("BigBlue_TerminalPlus.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 80%; } @font-face { font-family: "BigBlue Terminal 437TT"; src: url("BigBlue_Terminal_437TT.woff2") format("woff2"), url("BigBlue_Terminal_437TT.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 80%; } ================================================ FILE: packages/web/src/assets/fonts/FiraCode/README.txt ================================================ Installing ========== Windows ------- In the ttf folder, double-click each font file, click “Install font”; to install all at once, select all files, right-click, and choose “Install” OR Use https://chocolatey.org: choco install firacode macOS ----- In the downloaded TTF folder: 1. Select all font files 2. Right click and select `Open` (alternatively `Open With Font Book`) 3. Select "Install Font" OR Use http://brew.sh: `brew tap homebrew/cask-fonts` `brew install font-fira-code` Ubuntu Zesty (17.04), Debian Stretch (9) or newer ------------------------------------------------- 1. Make sure that the `universe` (for Ubuntu) or `contrib` (for Debian) repository is enabled (see https://askubuntu.com/questions/148638/how-do-i-enable-the-universe-repository or https://wiki.debian.org/SourcesList#Component) 2. Install `fonts-firacode` package either by executing `sudo apt install fonts-firacode` in the terminal or via GUI tool (like “Software Center”) Arch Linux ---------- Fira Code package is available in the official repository: https://www.archlinux.org/packages/community/any/ttf-fira-code/. Variant of Fira Code package is available in the AUR: https://aur.archlinux.org/packages/otf-fira-code-git/. Gentoo ------ emerge -av media-fonts/fira-code Fedora ------ To install, perform the following commands: dnf install fira-code-fonts Solus ----- Fira Code package is available in the official repository: `font-firacode-ttf` and `font-firacode-otf`. They can be installed by running: sudo eopkg install font-firacode-ttf font-firacode-otf Void linux ---------- xbps-install font-firacode Linux Manual Installation ------------------------- With most desktop-oriented distributions, double-clicking each font file in the ttf folder and selecting “Install font” should be enough. If it isn’t, create and run `download_and_install.sh` script: #!/usr/bin/env bash fonts_dir="${HOME}/.local/share/fonts" if [ ! -d "${fonts_dir}" ]; then echo "mkdir -p $fonts_dir" mkdir -p "${fonts_dir}" else echo "Found fonts dir $fonts_dir" fi for type in Bold Light Medium Regular Retina; do file_path="${HOME}/.local/share/fonts/FiraCode-${type}.ttf" file_url="https://github.com/tonsky/FiraCode/blob/master/distr/ttf/FiraCode-${type}.ttf?raw=true" if [ ! -e "${file_path}" ]; then echo "wget -O $file_path $file_url" wget -O "${file_path}" "${file_url}" else echo "Found existing file $file_path" fi; done echo "fc-cache -f" fc-cache -f More details: https://github.com/tonsky/FiraCode/issues/4 FreeBSD ------- Using pkg(8): pkg install firacode OR Using ports: cd /usr/ports/x11-fonts/firacode && make install clean Enabling ligatures ================== Atom ---- To change your font to Fira Code, open Atom's preferences (`cmd + ,` on a Mac, `ctrl + ,` on PC), make sure the "Settings" tab is selected, or the "Editor" in Atom 1.10+, and scroll down to "Editor Settings". In the "Font Family" field, enter `Fira Code`. If you wish to specify a font weight, for example, Light, use `Fira Code Light` as a font name (Windows) or `FiraCode-Light` (macOS). Ligatures are enabled by default in Atom 1.9 and above. VS Code ------- To open the settings editor, first from the File menu choose Preferences, Settings or use keyboard shortcut `Ctrl + ,` (Windows) or `Cmd + ,` (macOS). To enable FiraCode in the settings editor, under "Commonly Used", expand the "Text Editor" settings and then click on "Font". In the "Font Family" input box type `Fira Code`, replacing any content. Tick the check box "Enables/Disables font ligatures" under "Font Ligatures" to enable the special ligatures. If you wish to specify a font weight, for example, Light, use `Fira Code Light` as a font name (Windows) or `FiraCode-Light` (macOS). IntelliJ products ----------------- 1. Enable in Settings → Editor → Font → Enable Font Ligatures 2. Select `Fira Code` as "Primary font" under Settings → Editor → Font Additionally, if a Color Scheme is selected: 3. Enable in Settings → Editor → Color Scheme → Color Scheme Font → Enable Font Ligatures 4. Select Fira Code as "Primary font" under Settings → Editor → Color Scheme → Color Scheme Font BBEdit, TextWrangler -------------------- Run in your terminal: defaults write com.barebones.bbedit "EnableFontLigatures_Fira Code" -bool YES Source: https://www.barebones.com/support/bbedit/ExpertPreferences.html Brackets -------- 1. From the `View` menu choose `Themes....` 2. Paste `'Fira Code'`, at the beginning of `Font Family` Emacs ----- There are a few options when it comes down to using ligatures in Emacs. They are listed in order of preferred to less-preferred. Pick one! 1. Using composition mode in Emacs Mac port If you're using the latest Mac port of Emacs (https://bitbucket.org/mituharu/emacs-mac by Mitsuharu Yamamoto) for macOS, you can use: (mac-auto-operator-composition-mode) This is generally the easiest solution, but can only be used on macOS. 2. Using prettify-symbols These instructions are pieced together by https://github.com/Triavanicus, taking some pieces from https://github.com/minad/hasklig-mode. This method requires you to install the Fira Code Symbol font, made by https://github.com/siegebell: https://github.com/tonsky/FiraCode/issues/211#issuecomment-239058632 (defun fira-code-mode--make-alist (list) "Generate prettify-symbols alist from LIST." (let ((idx -1)) (mapcar (lambda (s) (setq idx (1+ idx)) (let* ((code (+ #Xe100 idx)) (width (string-width s)) (prefix ()) (suffix '(?\s (Br . Br))) (n 1)) (while (< n width) (setq prefix (append prefix '(?\s (Br . Bl)))) (setq n (1+ n))) (cons s (append prefix suffix (list (decode-char 'ucs code)))))) list))) (defconst fira-code-mode--ligatures '("www" "**" "***" "**/" "*>" "*/" "\\\\" "\\\\\\" "{-" "[]" "::" ":::" ":=" "!!" "!=" "!==" "-}" "--" "---" "-->" "->" "->>" "-<" "-<<" "-~" "#{" "#[" "##" "###" "####" "#(" "#?" "#_" "#_(" ".-" ".=" ".." "..<" "..." "?=" "??" ";;" "/*" "/**" "/=" "/==" "/>" "//" "///" "&&" "||" "||=" "|=" "|>" "^=" "$>" "++" "+++" "+>" "=:=" "==" "===" "==>" "=>" "=>>" "<=" "=<<" "=/=" ">-" ">=" ">=>" ">>" ">>-" ">>=" ">>>" "<*" "<*>" "<|" "<|>" "<$" "<$>" "\\)" #Xe113) ("[^-]\\(->\\)" #Xe114) ("\\(->>\\)" #Xe115) ("\\(-<\\)" #Xe116) ("\\(-<<\\)" #Xe117) ("\\(-~\\)" #Xe118) ("\\(#{\\)" #Xe119) ("\\(#\\[\\)" #Xe11a) ("\\(##\\)" #Xe11b) ("\\(###\\)" #Xe11c) ("\\(####\\)" #Xe11d) ("\\(#(\\)" #Xe11e) ("\\(#\\?\\)" #Xe11f) ("\\(#_\\)" #Xe120) ("\\(#_(\\)" #Xe121) ("\\(\\.-\\)" #Xe122) ("\\(\\.=\\)" #Xe123) ("\\(\\.\\.\\)" #Xe124) ("\\(\\.\\.<\\)" #Xe125) ("\\(\\.\\.\\.\\)" #Xe126) ("\\(\\?=\\)" #Xe127) ("\\(\\?\\?\\)" #Xe128) ("\\(;;\\)" #Xe129) ("\\(/\\*\\)" #Xe12a) ("\\(/\\*\\*\\)" #Xe12b) ("\\(/=\\)" #Xe12c) ("\\(/==\\)" #Xe12d) ("\\(/>\\)" #Xe12e) ("\\(//\\)" #Xe12f) ("\\(///\\)" #Xe130) ("\\(&&\\)" #Xe131) ("\\(||\\)" #Xe132) ("\\(||=\\)" #Xe133) ("[^|]\\(|=\\)" #Xe134) ("\\(|>\\)" #Xe135) ("\\(\\^=\\)" #Xe136) ("\\(\\$>\\)" #Xe137) ("\\(\\+\\+\\)" #Xe138) ("\\(\\+\\+\\+\\)" #Xe139) ("\\(\\+>\\)" #Xe13a) ("\\(=:=\\)" #Xe13b) ("[^!/]\\(==\\)[^>]" #Xe13c) ("\\(===\\)" #Xe13d) ("\\(==>\\)" #Xe13e) ("[^=]\\(=>\\)" #Xe13f) ("\\(=>>\\)" #Xe140) ("\\(<=\\)" #Xe141) ("\\(=<<\\)" #Xe142) ("\\(=/=\\)" #Xe143) ("\\(>-\\)" #Xe144) ("\\(>=\\)" #Xe145) ("\\(>=>\\)" #Xe146) ("[^-=]\\(>>\\)" #Xe147) ("\\(>>-\\)" #Xe148) ("\\(>>=\\)" #Xe149) ("\\(>>>\\)" #Xe14a) ("\\(<\\*\\)" #Xe14b) ("\\(<\\*>\\)" #Xe14c) ("\\(<|\\)" #Xe14d) ("\\(<|>\\)" #Xe14e) ("\\(<\\$\\)" #Xe14f) ("\\(<\\$>\\)" #Xe150) ("\\( Settings Add before "ignored_packages": "font_face": "Fira Code", "font_options": ["subpixel_antialias"], If you want enable antialias, add in font_options: "gray_antialias" Visual Studio ------------- 1. Launch Visual Studio (2015 or later). 2. Launch the Options dialog by opening the "Tools" menu and selecting "Options". 3. In the Options dialog, under the "Environment" category, you'll find "Fonts and Colors". Click on that. You'll see a combo-box on the right hand side of the dialog labelled "Font". Select "Fira Code" from that combo-box. 4. Click "OK" to dismiss. 5. Restart Visual Studio. Now, most FiraCode ligatures will work. A notable exception is the hyphen-based ligatures (e.g. the C++ dereference '->'). See https://github.com/tonsky/FiraCode/issues/422 for details. Troubleshooting =============== See https://github.com/tonsky/FiraCode/wiki/Troubleshooting ================================================ FILE: packages/web/src/assets/fonts/FiraCode/stylesheet.css ================================================ @font-face { font-family: "Fira Code VF"; src: url("FiraCode-VF.woff2") format("woff2-variations"), url("woff/FiraCode-VF.woff") format("woff-variations"); /* font-weight requires a range: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Fonts/Variable_Fonts_Guide#Using_a_variable_font_font-face_changes */ font-weight: 300 700; font-style: normal; size-adjust: 87%; } ================================================ FILE: packages/web/src/assets/fonts/IBM Plex Mono/stylesheet.css ================================================ @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-Thin.woff2") format("woff2"), url("IBMPlexMono-Thin.woff") format("woff"); font-weight: 100; font-style: normal; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-Regular.woff2") format("woff2"), url("IBMPlexMono-Regular.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-Bold.woff2") format("woff2"), url("IBMPlexMono-Bold.woff") format("woff"); font-weight: bold; font-style: normal; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-LightItalic.woff2") format("woff2"), url("IBMPlexMono-LightItalic.woff") format("woff"); font-weight: 300; font-style: italic; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-ExtraLightItalic.woff2") format("woff2"), url("IBMPlexMono-ExtraLightItalic.woff") format("woff"); font-weight: 200; font-style: italic; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-SemiBold.woff2") format("woff2"), url("IBMPlexMono-SemiBold.woff") format("woff"); font-weight: 600; font-style: normal; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-Italic.woff2") format("woff2"), url("IBMPlexMono-Italic.woff") format("woff"); font-weight: normal; font-style: italic; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-ThinItalic.woff2") format("woff2"), url("IBMPlexMono-ThinItalic.woff") format("woff"); font-weight: 100; font-style: italic; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-SemiBoldItalic.woff2") format("woff2"), url("IBMPlexMono-SemiBoldItalic.woff") format("woff"); font-weight: 600; font-style: italic; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-Light.woff2") format("woff2"), url("IBMPlexMono-Light.woff") format("woff"); font-weight: 300; font-style: normal; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-MediumItalic.woff2") format("woff2"), url("IBMPlexMono-MediumItalic.woff") format("woff"); font-weight: 500; font-style: italic; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-Medium.woff2") format("woff2"), url("IBMPlexMono-Medium.woff") format("woff"); font-weight: 500; font-style: normal; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-BoldItalic.woff2") format("woff2"), url("IBMPlexMono-BoldItalic.woff") format("woff"); font-weight: bold; font-style: italic; font-display: swap; size-adjust: 90%; } @font-face { font-family: "IBM Plex Mono"; src: url("IBMPlexMono-ExtraLight.woff2") format("woff2"), url("IBMPlexMono-ExtraLight.woff") format("woff"); font-weight: 200; font-style: normal; font-display: swap; size-adjust: 90%; } ================================================ FILE: packages/web/src/assets/fonts/JGS/stylesheet.css ================================================ @font-face { font-family: "jgs7"; src: url("jgs7.woff2") format("woff2"), url("jgs7.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 105%; } @font-face { font-family: "jgs"; src: url("jgs.woff2") format("woff2"), url("jgs.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 105%; } @font-face { font-family: "jgs_Font"; src: url("jgs_Font.woff2") format("woff2"), url("jgs_Font.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 105%; } @font-face { font-family: "jgs5"; src: url("jgs5.woff2") format("woff2"), url("jgs5.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 105%; } ================================================ FILE: packages/web/src/assets/fonts/JetBrains/stylesheet.css ================================================ @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-SemiBoldItalic.woff2") format("woff2"), url("JetBrainsMonoNL-SemiBoldItalic.woff") format("woff"); font-weight: 600; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-ExtraBoldItalic.woff2") format("woff2"), url("JetBrainsMono-ExtraBoldItalic.woff") format("woff"); font-weight: bold; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-MediumItalic.woff2") format("woff2"), url("JetBrainsMonoNL-MediumItalic.woff") format("woff"); font-weight: 500; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-LightItalic.woff2") format("woff2"), url("JetBrainsMono-LightItalic.woff") format("woff"); font-weight: 300; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-LightItalic.woff2") format("woff2"), url("JetBrainsMonoNL-LightItalic.woff") format("woff"); font-weight: 300; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-ExtraBold.woff2") format("woff2"), url("JetBrainsMono-ExtraBold.woff") format("woff"); font-weight: bold; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-ThinItalic.woff2") format("woff2"), url("JetBrainsMono-ThinItalic.woff") format("woff"); font-weight: 100; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-ExtraBold.woff2") format("woff2"), url("JetBrainsMonoNL-ExtraBold.woff") format("woff"); font-weight: bold; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-ExtraLight.woff2") format("woff2"), url("JetBrainsMonoNL-ExtraLight.woff") format("woff"); font-weight: 200; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-MediumItalic.woff2") format("woff2"), url("JetBrainsMono-MediumItalic.woff") format("woff"); font-weight: 500; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-Regular.woff2") format("woff2"), url("JetBrainsMono-Regular.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-ExtraBoldItalic.woff2") format("woff2"), url("JetBrainsMonoNL-ExtraBoldItalic.woff") format("woff"); font-weight: bold; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-Italic.woff2") format("woff2"), url("JetBrainsMonoNL-Italic.woff") format("woff"); font-weight: normal; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-ExtraLightItalic.woff2") format("woff2"), url("JetBrainsMono-ExtraLightItalic.woff") format("woff"); font-weight: 200; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-Medium.woff2") format("woff2"), url("JetBrainsMono-Medium.woff") format("woff"); font-weight: 500; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-Italic.woff2") format("woff2"), url("JetBrainsMono-Italic.woff") format("woff"); font-weight: normal; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-BoldItalic.woff2") format("woff2"), url("JetBrainsMonoNL-BoldItalic.woff") format("woff"); font-weight: bold; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-ExtraLight.woff2") format("woff2"), url("JetBrainsMono-ExtraLight.woff") format("woff"); font-weight: 200; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-SemiBoldItalic.woff2") format("woff2"), url("JetBrainsMono-SemiBoldItalic.woff") format("woff"); font-weight: 600; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-Thin.woff2") format("woff2"), url("JetBrainsMono-Thin.woff") format("woff"); font-weight: 100; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-SemiBold.woff2") format("woff2"), url("JetBrainsMono-SemiBold.woff") format("woff"); font-weight: 600; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-SemiBold.woff2") format("woff2"), url("JetBrainsMonoNL-SemiBold.woff") format("woff"); font-weight: 600; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-Thin.woff2") format("woff2"), url("JetBrainsMonoNL-Thin.woff") format("woff"); font-weight: 100; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-Regular.woff2") format("woff2"), url("JetBrainsMonoNL-Regular.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-ExtraLightItalic.woff2") format("woff2"), url("JetBrainsMonoNL-ExtraLightItalic.woff") format("woff"); font-weight: 200; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-BoldItalic.woff2") format("woff2"), url("JetBrainsMono-BoldItalic.woff") format("woff"); font-weight: bold; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-ThinItalic.woff2") format("woff2"), url("JetBrainsMonoNL-ThinItalic.woff") format("woff"); font-weight: 100; font-style: italic; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-Light.woff2") format("woff2"), url("JetBrainsMonoNL-Light.woff") format("woff"); font-weight: 300; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono NL"; src: url("JetBrainsMonoNL-Bold.woff2") format("woff2"), url("JetBrainsMonoNL-Bold.woff") format("woff"); font-weight: bold; font-style: normal; font-display: swap; size-adjust: 85%; } @font-face { font-family: "JetBrains Mono"; src: url("JetBrainsMono-Bold.woff2") format("woff2"), url("JetBrainsMono-Bold.woff") format("woff"); font-weight: bold; font-style: normal; font-display: swap; size-adjust: 85%; } ================================================ FILE: packages/web/src/assets/fonts/Monocraft/stylesheet.css ================================================ @font-face { font-family: "Monocraft Nerd Font"; src: url("MonocraftNerdFontComplete-.woff2") format("woff2"), url("MonocraftNerdFontComplete-.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 80%; } ================================================ FILE: packages/web/src/assets/fonts/OpenDyslexic/stylesheet.css ================================================ @font-face { font-family: "OpenDyslexic"; font-style: normal; font-weight: 400; src: local("OpenDyslexic"), url("OpenDyslexic-Regular.woff") format("woff"); } @font-face { font-family: "OpenDyslexic"; font-style: italic; font-weight: 400; src: local("OpenDyslexic"), url("OpenDyslexic-Italic.woff") format("woff"); } @font-face { font-family: "OpenDyslexic"; font-style: normal; font-weight: 700; src: local("OpenDyslexic"), url("OpenDyslexic-Bold.woff") format("woff"); } @font-face { font-family: "OpenDyslexic"; font-style: italic; font-weight: 700; src: local("OpenDyslexic"), url("OpenDyslexic-BoldItalic.woff") format("woff"); } @font-face { font-family: "OpenDyslexic3"; font-style: normal; font-weight: 400; src: local("OpenDyslexic3"), url("OpenDyslexic3-Regular.woff") format("woff"); } @font-face { font-family: "OpenDyslexicAlta"; font-style: normal; font-weight: 400; src: local("OpenDyslexicAlta"), url("OpenDyslexicAlta-Regular.woff") format("woff"); } @font-face { font-family: "OpenDyslexicMono"; font-style: normal; font-weight: 400; src: local("OpenDyslexicMono"), url("OpenDyslexicMono-Regular.woff") format("woff"); } @font-face { font-family: "OpenDyslexicAlta"; font-style: italic; font-weight: 400; src: local("OpenDyslexicAlta"), url("OpenDyslexicAlta-Italic.woff") format("woff"); } @font-face { font-family: "OpenDyslexic3"; font-style: normal; font-weight: 700; src: local("OpenDyslexic3"), url("OpenDyslexic3-Bold.woff") format("woff"); } @font-face { font-family: "OpenDyslexicAlta"; font-style: normal; font-weight: 700; src: local("OpenDyslexicAlta"), url("OpenDyslexicAlta-Bold.woff") format("woff"); } @font-face { font-family: "OpenDyslexicAlta"; font-style: italic; font-weight: 700; src: local("OpenDyslexicAlta"), url("OpenDyslexicAlta-BoldItalic.woff") format("woff"); } ================================================ FILE: packages/web/src/assets/fonts/RobotoMono/LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: packages/web/src/assets/fonts/RobotoMono/stylesheet.css ================================================ @font-face { font-family: "Roboto Mono"; src: url("RobotoMono-Regular.woff2") format("woff2"), url("RobotoMono-Regular.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 90%; } ================================================ FILE: packages/web/src/assets/fonts/StepsMono/COPYRIGHT.md ================================================ Copyright (c) 2013-2014, Raphaël Bastide Copyright (c) 2013-2014, Jean-Baptiste Morizot ================================================ FILE: packages/web/src/assets/fonts/StepsMono/LICENSE.txt ================================================ Copyright (c) 2014, Jean-Baptiste Morizot, (http://cargocollective.com/jbmrz), Raphaël Bastide (http://raphaelbastide.com/) with Reserved Font Name "Steps Mono". This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL SIL Open Font License v1.1 ==================================================== Preamble ---------- The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. Definitions ------------- `"Font Software"` refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. `"Reserved Font Name"` refers to any names specified as such after the copyright statement(s). `"Original Version"` refers to the collection of Font Software components as distributed by the Copyright Holder(s). `"Modified Version"` refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. `"Author"` refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. Permission & Conditions ------------------------ Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1. Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2. Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3. No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4. The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5. The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. Termination ----------- This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. ================================================ FILE: packages/web/src/assets/fonts/StepsMono/stylesheet.css ================================================ @font-face { font-family: "Steps Mono"; src: url("Steps-Mono-Thin.woff2") format("woff2"), url("Steps-Mono-Thin.woff") format("woff"); font-weight: 100; font-style: normal; font-display: swap; size-adjust: 100%; } @font-face { font-family: "Steps-Mono"; src: url("Steps-Mono-Mono.woff2") format("woff2"), url("Steps-Mono-Mono.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 95%; } ================================================ FILE: packages/web/src/assets/fonts/SyneMono/OFL.txt ================================================ Copyright 2017 The Syne Project Authors (https://gitlab.com/bonjour-monde/fonderie/syne-typeface) This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: https://openfontlicense.org ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ----------------------------------------------------------- PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. ================================================ FILE: packages/web/src/assets/fonts/SyneMono/stylesheet.css ================================================ @font-face { font-family: "Syne Mono"; src: url("SyneMono-Regular.woff2") format("woff2"), url("SyneMono-Regular.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 95%; } ================================================ FILE: packages/web/src/assets/fonts/UbuntuMono/UFL.txt ================================================ ------------------------------- UBUNTU FONT LICENCE Version 1.0 ------------------------------- PREAMBLE This licence allows the licensed fonts to be used, studied, modified and redistributed freely. The fonts, including any derivative works, can be bundled, embedded, and redistributed provided the terms of this licence are met. The fonts and derivatives, however, cannot be released under any other licence. The requirement for fonts to remain under this licence does not require any document created using the fonts or their derivatives to be published under this licence, as long as the primary purpose of the document is not to be a vehicle for the distribution of the fonts. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this licence and clearly marked as such. This may include source files, build scripts and documentation. "Original Version" refers to the collection of Font Software components as received under this licence. "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Copyright Holder(s)" refers to all individuals and companies who have a copyright ownership of the Font Software. "Substantially Changed" refers to Modified Versions which can be easily identified as dissimilar to the Font Software by users of the Font Software comparing the Original Version with the Modified Version. To "Propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification and with or without charging a redistribution fee), making available to the public, and in some countries other activities as well. PERMISSION & CONDITIONS This licence does not grant any rights under trademark law and all such rights are reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to propagate the Font Software, subject to the below conditions: 1) Each copy of the Font Software must contain the above copyright notice and this licence. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine- readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 2) The font name complies with the following: (a) The Original Version must retain its name, unmodified. (b) Modified Versions which are Substantially Changed must be renamed to avoid use of the name of the Original Version or similar names entirely. (c) Modified Versions which are not Substantially Changed must be renamed to both (i) retain the name of the Original Version and (ii) add additional naming elements to distinguish the Modified Version from the Original Version. The name of such Modified Versions must be the name of the Original Version, with "derivative X" where X represents the name of the new work, appended to that name. 3) The name(s) of the Copyright Holder(s) and any contributor to the Font Software shall not be used to promote, endorse or advertise any Modified Version, except (i) as required by this licence, (ii) to acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with their explicit written permission. 4) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this licence, and must not be distributed under any other licence. The requirement for fonts to remain under this licence does not affect any document created using the Font Software, except any version of the Font Software extracted from a document created using the Font Software may only be distributed under this licence. TERMINATION This licence becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. ================================================ FILE: packages/web/src/assets/fonts/UbuntuMono/stylesheet.css ================================================ @font-face { font-family: "Ubuntu Mono"; src: url("UbuntuMono-Bold.woff2") format("woff2"), url("UbuntuMono-Bold.woff") format("woff"); font-weight: bold; font-style: normal; font-display: swap; size-adjust: 105%; } ================================================ FILE: packages/web/src/assets/fonts/VT323/OFL.txt ================================================ Copyright 2011, The VT323 Project Authors (peter.hull@oikoi.com) This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: https://openfontlicense.org ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ----------------------------------------------------------- PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. ================================================ FILE: packages/web/src/assets/fonts/VT323/demo.html ================================================ Transfonter demo

VT323 Regular

.your-style {
    font-family: 'VT323';
    font-weight: normal;
    font-style: normal;
}
<link rel="preload" href="VT323-Regular.woff2" as="font" type="font/woff2" crossorigin>

abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789.:,;()*!?'@#<>$%&^+-=~

The quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog.

================================================ FILE: packages/web/src/assets/fonts/VT323/stylesheet.css ================================================ @font-face { font-family: "VT323"; src: url("VT323-Regular.woff2") format("woff2"), url("VT323-Regular.woff") format("woff"); font-weight: normal; font-style: normal; font-display: swap; size-adjust: 120%; } ================================================ FILE: packages/web/src/components/commands-button.tsx ================================================ import { Button, ButtonProps } from "./ui/button"; import { Command } from "lucide-react"; export const CommandsButton = (props: ButtonProps) => ( ); ================================================ FILE: packages/web/src/components/configure-dialog.tsx ================================================ import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Input, InputProps } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { defaultTarget, knownTargets } from "@/settings.json"; import { DialogProps } from "@radix-ui/react-dialog"; import { ChangeEvent, FormEvent, useEffect, useMemo, useState } from "react"; import { ReplsInfo } from "./repls-info"; function TargetsInput(props: InputProps) { return (
Known targets are:
    {knownTargets.map((t) => (
  • {t}
  • ))}
); } interface ConfigureDialogProps extends DialogProps { targets: string[]; sessionName: string; sessionUrl: string; userName: string; OS: string; onAccept?: (targets: string[]) => void; } export function ConfigureDialog({ targets, sessionName, sessionUrl, userName, OS, onAccept, ...props }: ConfigureDialogProps) { const [targetsValue, setTargetsValue] = useState(""); useEffect(() => { if (!props.open) { setTargetsValue(""); } }, [props.open]); const newTargets = useMemo( () => targetsValue .split(",") .map((t) => t.trim()) .filter((t) => knownTargets.includes(t)), [targetsValue], ); const newOrCurrentTargets = newTargets.length > 0 ? newTargets : targets; const handleSubmit = (e: FormEvent) => { e.preventDefault(); setTargetsValue(newOrCurrentTargets.join(", ")); if (onAccept) { if (newOrCurrentTargets.length === 0) newOrCurrentTargets.push(defaultTarget); console.log("new targets", newOrCurrentTargets); onAccept(newOrCurrentTargets); } props.onOpenChange && props.onOpenChange(false); }; const handleChange = (e: ChangeEvent) => { setTargetsValue(e.target.value.replace(/,\s*/g, ", ").trim()); }; return (
Configure Layout Enter a list of targets, separated by comma. {newOrCurrentTargets.length > 0 && ( )}
); } ================================================ FILE: packages/web/src/components/display-settings-dialog.tsx ================================================ import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { DisplaySettings, sanitizeDisplaySettings, } from "@/lib/display-settings"; import { DialogProps } from "@radix-ui/react-dialog"; import { FormEvent, useState } from "react"; interface DisplaySettingsDialogProps extends DialogProps { settings: DisplaySettings; onAccept: (settings: DisplaySettings) => void; } export default function DisplaySettingsDialog({ settings, onAccept, ...props }: DisplaySettingsDialogProps) { const [unsavedSettings, setUnsavedSettings] = useState({ ...settings }); const sanitizeAndSetUnsavedSettings = (settings: DisplaySettings) => setUnsavedSettings(sanitizeDisplaySettings(settings)); const handleSubmit = (e: FormEvent) => { e.preventDefault(); onAccept(unsavedSettings); props.onOpenChange && props.onOpenChange(false); }; return (
Change display settings
sanitizeAndSetUnsavedSettings({ ...unsavedSettings, canvasPixelSize: parseInt(e.target.value, 10), }) } />
sanitizeAndSetUnsavedSettings({ ...unsavedSettings, showCanvas: e.target.checked, }) } />
sanitizeAndSetUnsavedSettings({ ...unsavedSettings, enableFft: e.target.checked, }) } />

You need to reload the page to apply changes to fft

); } ================================================ FILE: packages/web/src/components/editor.tsx ================================================ import "../assets/fonts/IBM Plex Mono/stylesheet.css"; import "../assets/fonts/BigBlue/stylesheet.css"; import "../assets/fonts/Monocraft/stylesheet.css"; import "../assets/fonts/JetBrains/stylesheet.css"; import "../assets/fonts/JGS/stylesheet.css"; import "../assets/fonts/StepsMono/stylesheet.css"; import "../assets/fonts/FiraCode/stylesheet.css"; import "../assets/fonts/SyneMono/stylesheet.css"; import "../assets/fonts/VT323/stylesheet.css"; import "../assets/fonts/RobotoMono/stylesheet.css"; import "../assets/fonts/UbuntuMono/stylesheet.css"; import "../assets/fonts/OpenDyslexic/stylesheet.css"; import { useQuery } from "@/hooks/use-query"; import { langByTarget as langByTargetUntyped, panicCodes as panicCodesUntyped, targetsWithDocumentEvalMode, noAutoIndent, webTargets, } from "@/settings.json"; import { javascript } from "@codemirror/lang-javascript"; import { python } from "@codemirror/lang-python"; import { EditorState, Prec } from "@codemirror/state"; import { EditorView, keymap, lineNumbers as lineNumbersExtension, } from "@codemirror/view"; import { evalKeymap, flashField, remoteEvalFlash } from "@flok-editor/cm-eval"; import { tidal } from "@flok-editor/lang-tidal"; import { punctual } from "@flok-editor/lang-punctual"; import type { Document } from "@flok-editor/session"; import { highlightExtension } from "@strudel/codemirror"; import CodeMirror, { ReactCodeMirrorProps, ReactCodeMirrorRef, } from "@uiw/react-codemirror"; import { vim } from "@replit/codemirror-vim"; import React, { useEffect, useState } from "react"; import { yCollab } from "y-codemirror.next"; import { UndoManager } from "yjs"; import themes from "@/lib/themes"; import { toggleLineComment, insertNewline } from "@codemirror/commands"; const defaultLanguage = "javascript"; const langByTarget = langByTargetUntyped as { [lang: string]: string }; const langExtensionsByLanguage: { [lang: string]: any } = { javascript: javascript, python: python, tidal: tidal, punctual: punctual, }; const panicCodes = panicCodesUntyped as { [target: string]: string }; const panicKeymap = ( doc: Document, keys: string[] = ["Cmd-.", "Ctrl-.", "Alt-."], ) => { const panicCode = panicCodes[doc.target]; return panicCode ? keymap.of([ ...keys.map((key) => ({ key, run() { doc.evaluate(panicCode, { from: null, to: null }); return true; }, })), ]) : []; }; // extra keymaps const extraKeymap = () => { return keymap.of([ // fixes the Cmd/Alt-/ issue for Spanish keyboards { key: "Shift-Cmd-7", run: toggleLineComment }, { key: "Shift-Alt-7", run: toggleLineComment }, { key: "Alt-/", run: toggleLineComment }, { key: "Ctrl-/", run: toggleLineComment }, ]); }; // overwrites the default insertNewlineAndIndent command on Enter const autoIndentKeymap = (doc: Document) => { // if any of the targets is part of the noAutoIndent setting in settings.json const noIndent = noAutoIndent.includes(doc.target); // overwrite the Enter with insertNewline return noIndent ? Prec.high(keymap.of([{ key: "Enter", run: insertNewline }])) : []; }; interface FlokSetupOptions { readOnly?: boolean; } const flokSetup = ( doc: Document, { readOnly = false }: FlokSetupOptions = {}, ) => { const text = doc.getText(); const undoManager = new UndoManager(text); const defaultMode = targetsWithDocumentEvalMode.includes(doc.target) ? "document" : "block"; const web = webTargets.includes(doc.target); return [ flashField(), remoteEvalFlash(doc), Prec.high(evalKeymap(doc, { defaultMode, web })), panicKeymap(doc), extraKeymap(), autoIndentKeymap(doc), yCollab(text, doc.session.awareness, { undoManager, hideCaret: readOnly, showLocalCaret: true, }), ]; }; export interface EditorSettings { theme: string; fontFamily: string; lineNumbers: boolean; wrapText: boolean; vimMode: boolean; } export interface EditorProps extends ReactCodeMirrorProps { document?: Document; extensionSettings?: any; settings?: EditorSettings; ref: React.RefObject; } export const Editor = ({ document, settings, ref, ...props }: EditorProps) => { const [mounted, setMounted] = useState(false); const query = useQuery(); // useEffect only runs on the client, so now we can safely show the UI useEffect(() => { // Make sure query parameters are set before loading the editor if (!query) return; setMounted(true); }, [query]); if (!mounted || !document) { return null; } const { theme, fontFamily, lineNumbers, wrapText, vimMode } = { theme: "dracula", fontFamily: "IBM Plex Mono", lineNumbers: false, wrapText: false, vimMode: false, ...settings, }; const readOnly = !!query.get("readOnly"); const language: string = langByTarget[document.target] || defaultLanguage; const languageExtension = langExtensionsByLanguage[language] || null; const extensions = [ EditorView.theme({ "&": { fontFamily: fontFamily, }, ".cm-content": { fontFamily: fontFamily, }, ".cm-gutters": { fontFamily: fontFamily, "margin-right": "10px", }, ".cm-line": { "font-size": "105%", "font-weight": "600", background: "rgba(0, 0, 0, 0.7)", "max-width": "fit-content", padding: "0px", }, ".cm-activeLine": { "background-color": "rgba(0, 0, 0, 1) !important", }, "& .cm-scroller": { minHeight: "100vh", }, ".cm-ySelectionInfo": { opacity: "1", fontFamily: fontFamily, color: "black", padding: "3px 4px", fontSize: "0.8rem", "font-weight": "bold", top: "1.25em", "z-index": "1000", }, }), flokSetup(document, { readOnly }), languageExtension ? languageExtension() : [], highlightExtension, readOnly ? EditorState.readOnly.of(true) : [], lineNumbers ? lineNumbersExtension() : [], vimMode ? vim() : [], wrapText ? EditorView.lineWrapping : [], ]; // If it's read-only, put a div in front of the editor so that the user // can't interact with it. return ( <> {readOnly &&
} ); }; ================================================ FILE: packages/web/src/components/evaluate-button.tsx ================================================ import { Button, ButtonProps } from "./ui/button"; import { Play } from "lucide-react"; import { cn } from "@/lib/utils"; export const EvaluateButton = (props: ButtonProps) => ( ); ================================================ FILE: packages/web/src/components/hydra-canvas.tsx ================================================ import React from "react"; import { cn } from "@/lib/utils"; import { DisplaySettings } from "@/lib/display-settings"; interface HydraCanvasProps { fullscreen?: boolean; displaySettings: DisplaySettings; ref: React.RefObject; } const HydraCanvas = ({ fullscreen, displaySettings, ref, }: HydraCanvasProps) => ( ); export default React.memo(HydraCanvas); ================================================ FILE: packages/web/src/components/icons.tsx ================================================ import { Laptop, Moon, SunMedium, type Icon as LucideIcon } from "lucide-react"; export type Icon = LucideIcon; export const Icons = { sun: SunMedium, moon: Moon, laptop: Laptop, }; ================================================ FILE: packages/web/src/components/messages-panel.tsx ================================================ import { FloatingPanel } from "@/components/ui/floating-panel"; import { cn } from "@/lib/utils"; import { Message } from "@/routes/session"; import { useEffect, useMemo, useRef } from "react"; import { FloatingPanelButton, FloatingPanelToggle, } from "@/components/ui/floating-panel"; import { View, EyeOff, X } from "lucide-react"; type ExtMessage = Message & { sameTarget: boolean }; interface MessagesPanelProps { className?: string; messages: Message[]; autoShowMessages: boolean; hideMessagesOnEval: boolean; onAutoShowToggleClick?: (pressed: boolean) => void; onHideMessagesOnEvalClick?: (pressed: boolean) => void; onClearMessagesClick?: () => void; } export function MessagesPanel({ className, messages, autoShowMessages, hideMessagesOnEval, onAutoShowToggleClick, onHideMessagesOnEvalClick, onClearMessagesClick, }: MessagesPanelProps) { const containerRef = useRef(null); // Scroll container to the end automatically when there are new messages useEffect(() => { if (!containerRef.current) return; const container = containerRef.current; container.scrollTop = container.scrollHeight; }, [containerRef, messages]); // Include `sameTarget` prop to know if a message is from the same target as // the previous message. const messagesPrev = useMemo(() => { let res: ExtMessage[] = []; for (let i = 0; i < messages.length; i++) { const curMessage = messages[i]; const prevMessage = i > 0 && messages[i - 1]; res.push({ ...curMessage, sameTarget: prevMessage && prevMessage.target === curMessage.target, }); } return res; }, [messages]); return (
} className={className} >
    {messagesPrev.map(({ sameTarget, target, body, type, tags }, i) => (
  • {!sameTarget && (
    {[target, ...tags].map((key) => ( {key} ))}
    )} {body.map((line, j) => (
                    {line}
                  
    ))}
  • ))}
); } ================================================ FILE: packages/web/src/components/mosaic.tsx ================================================ import { ReactNode, useMemo, cloneElement } from "react"; import { cn } from "@/lib/utils"; interface MosaicProps { className: string; items: ReactNode[]; } export function Mosaic({ className, items }: MosaicProps) { const itemsByRows = (items: ReactNode[]) => { let rows: ReactNode[][] = []; switch (items.length) { case 0: rows = []; break; case 1: case 2: rows = [items]; break; case 3: rows = [items.slice(0, 2), [items[2]]]; break; case 4: rows = [items.slice(0, 2), items.slice(2, 4)]; break; case 5: rows = [items.slice(0, 3), items.slice(3, 5)]; break; case 6: rows = [items.slice(0, 3), items.slice(3, 6)]; break; case 7: rows = [items.slice(0, 4), items.slice(4, 7)]; break; case 8: rows = [items.slice(0, 4), items.slice(4, 8)]; break; default: console.warn("More than 8 slots are not supported right now"); rows = [items.slice(0, 4), items.slice(4, 8)]; } return rows; }; const rows = useMemo(() => itemsByRows(items), [items]); const halfHeight = rows.length > 1; return (
{rows.map((rowItems, i) => (
{rowItems.map((item: any, j: number) => (
{cloneElement(item, { halfHeight })}
))}
))}
); } ================================================ FILE: packages/web/src/components/pane.tsx ================================================ import { EvaluateButton } from "@/components/evaluate-button"; import TargetSelect from "@/components/target-select"; import { cn } from "@/lib/utils"; import type { Document } from "@flok-editor/session"; import { PropsWithChildren } from "react"; interface PaneProps extends PropsWithChildren { document: Document; halfHeight?: boolean; onTargetChange: (document: Document, target: string) => void; onEvaluateButtonClick: (document: Document) => void; } export const Pane = ({ children, document, halfHeight, onTargetChange, onEvaluateButtonClick, }: PaneProps) => (
onTargetChange(document, target)} /> {children} onEvaluateButtonClick(document)} />
); ================================================ FILE: packages/web/src/components/punctual-canvas.tsx ================================================ import React from "react"; import { cn } from "@/lib/utils"; import { DisplaySettings } from "@/lib/display-settings"; interface PunctualCanvasProps { fullscreen?: boolean; displaySettings: DisplaySettings; ref: React.RefObject; } const PunctualCanvas = ({ fullscreen, displaySettings, ref, }: PunctualCanvasProps) => ( ); export default React.memo(PunctualCanvas); ================================================ FILE: packages/web/src/components/repls-button.tsx ================================================ import { Button, ButtonProps } from "./ui/button"; export const ReplsButton = (props: ButtonProps) => ( ); ================================================ FILE: packages/web/src/components/repls-dialog.tsx ================================================ import { ReplsInfo } from "@/components/repls-info"; import { Dialog, DialogContent, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { DialogProps } from "@radix-ui/react-dialog"; interface ReplsDialogProps extends DialogProps { targets: string[]; sessionUrl: string; sessionName: string; userName: string; OS: string; } export function ReplsDialog({ targets, sessionUrl, sessionName, userName, OS, ...props }: ReplsDialogProps) { return ( REPL Configuration ); } ================================================ FILE: packages/web/src/components/repls-info.tsx ================================================ import { Button } from "@/components/ui/button"; import { Check, Copy } from "lucide-react"; import { useState } from "react"; import { Link } from "react-router-dom"; import { webTargets } from "@/settings.json"; interface ReplsInfoProps { targets: string[]; sessionUrl: string; sessionName: string; userName: string; OS: string; } export function ReplsInfo({ targets, sessionUrl, sessionName, userName, OS, }: ReplsInfoProps) { const [copied, setCopied] = useState(false); const replTargets = targets.filter((t) => !webTargets.includes(t)); if (replTargets.length === 0) return null; const terminalSpec = OS === "windows" ? "PowerShell " : ""; const lineSeparator = OS === "windows" ? `\`` : `\\`; const replCommand = `npx flok-repl@latest -H ${sessionUrl} ${lineSeparator}\n` + ` -s ${sessionName} ${lineSeparator}\n` + ` -t ${replTargets.join(" ")} ${lineSeparator}\n` + ` -T user:${userName}`; const copyToClipboard = () => { setCopied(true); setTimeout(() => setCopied(false), 1000); navigator.clipboard.writeText(replCommand); }; return (

This session has one or more targets that need an external REPL process to run on your computer. To run code executed on these targets, you will need to run flok-repl on a {terminalSpec}terminal, like this:

          {replCommand}
        

For more information, read{" "} here .

); } ================================================ FILE: packages/web/src/components/session-command-dialog.tsx ================================================ "use client"; import { CommandDialog, CommandDialogProps, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, Command, CommandSeparator, CommandShortcut, } from "@/components/ui/command"; import { changeLogUrl, repoUrl } from "@/settings.json"; import themes from "@/lib/themes"; import fonts from "@/lib/fonts"; import { Edit2, FilePlus, TextCursorIcon, WrapText, ArrowLeft, Github, FileDigit, Type, Minus, Plus, Palette, Settings, Share, Monitor, } from "lucide-react"; import { Link } from "react-router-dom"; import { useState } from "react"; import { EditorSettings } from "./editor"; import { DisplaySettings } from "@/lib/display-settings"; interface SessionCommandDialogProps extends CommandDialogProps { editorSettings: EditorSettings; onEditorSettingsChange: (settings: EditorSettings) => void; displaySettings: DisplaySettings; onDisplaySettingsChange: (settings: DisplaySettings) => void; onSessionChangeUsername: () => void; onSessionNew: () => void; onSessionShareUrl: () => void; onLayoutAdd: () => void; onLayoutRemove: () => void; onLayoutConfigure: () => void; onEditorChangeDisplaySettings: () => void; } export default function SessionCommandDialog({ editorSettings, displaySettings, onEditorSettingsChange, ...props }: SessionCommandDialogProps) { const { fontFamily, theme, vimMode, lineNumbers, wrapText } = editorSettings; const [pages, setPages] = useState([]); const wrapHandler = (callback: () => void) => { return () => { const { onOpenChange } = props; callback(); if (onOpenChange) onOpenChange(false); }; }; const wrapHandlerWithValue = (callback: (value: any) => void, data: any) => { return () => { const { onOpenChange } = props; callback(data); if (onOpenChange) onOpenChange(false); }; }; const fontSelection = (font: string) => { setPages([]); wrapHandler(() => onEditorSettingsChange({ ...editorSettings, fontFamily: font, }), )(); }; const themeSelection = (theme: string) => { setPages([]); wrapHandler(() => onEditorSettingsChange({ ...editorSettings, theme, }), )(); }; const page = pages[pages.length - 1]; return ( No results found. {!page && ( <> Change Username New Share URL {/* Open Open Recent Save As... */} Configure ⌃P Add Pane Remove Pane setPages([...pages, "fonts"])}> Change Font Family: {fontFamily} setPages([...pages, "themes"])}> Change Theme: {themes[theme]?.name} onEditorSettingsChange({ ...editorSettings, lineNumbers: !lineNumbers, }), )} > {lineNumbers ? "Hide" : "Show"} Line Numbers onEditorSettingsChange({ ...editorSettings, wrapText: !wrapText, }), )} > {wrapText ? "Disable" : "Enable"} Word Wrapping onEditorSettingsChange({ ...editorSettings, vimMode: !vimMode, }), )} > {vimMode ? "Disable" : "Enable"} Vim Mode Change display settings {/* Quickstart ⌘H Show All Commands ⌘K */} Show Release Notes Go to GitHub )} {page === "fonts" && ( setPages([])} key="fontMenu"> Back to menu {Object.entries(fonts).map(([fontKey, fontValue]) => ( onEditorSettingsChange({ ...editorSettings, fontFamily: fontValue, }) } onSelect={wrapHandlerWithValue(fontSelection, fontValue)} key={fontKey} > {fontKey} ))} )} {page === "themes" && ( // setPages([])} key="themeMenu"> Back to menu {Object.entries(themes).map(([key, { name }]) => ( onEditorSettingsChange({ ...editorSettings, theme: key }) } onSelect={wrapHandlerWithValue(themeSelection, key)} key={key} > {name} ))} {/* */} )} Tip: Press +J or Ctrl+J to open or close this prompt ); } ================================================ FILE: packages/web/src/components/session-menu.tsx ================================================ "use client"; import { Menubar, MenubarContent, MenubarItem, MenubarMenu, MenubarSeparator, MenubarShortcut, MenubarTrigger, MenubarSub, MenubarSubTrigger, MenubarSubContent, } from "@/components/ui/menubar"; import { Link } from "react-router-dom"; import { repoUrl, changeLogUrl } from "@/settings.json"; interface MenuProps { onSessionConfigure?: (e: Event) => void; onSessionChangeUsername?: (e: Event) => void; onSessionNew?: (e: Event) => void; onViewLayoutAdd?: (e: Event) => void; onViewLayoutRemove?: (e: Event) => void; } export default function SessionMenu({ onSessionConfigure, onSessionChangeUsername, onSessionNew, onViewLayoutAdd, onViewLayoutRemove, }: MenuProps) { return ( Session Configure⌘C Change username New Open Open Recent Save As... View Layout Add Remove Help Quickstart ⌘H Show All Commands ⌘K Show Release Notes Go to GitHub ); } ================================================ FILE: packages/web/src/components/share-url-dialog.tsx ================================================ import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { DialogProps } from "@radix-ui/react-dialog"; import { Check, Copy } from "lucide-react"; import { useState } from "react"; interface ConfigureDialogProps extends DialogProps { url: string; onAccept?: (targets: string[]) => void; } export function ShareUrlDialog({ url, ...props }: ConfigureDialogProps) { const [copied, setCopied] = useState(false); const copyToClipboard = () => { setCopied(true); setTimeout(() => setCopied(false), 1000); navigator.clipboard.writeText(url); }; return ( Share Session Copy the URL below and share it with your friends. This URL contains a copy of the current session layout and code.
              {url}
            
); } ================================================ FILE: packages/web/src/components/status-bar.tsx ================================================ import { Slash, CheckCircle2, CircleEllipsis, Check, RefreshCw, LucideProps, HelpCircle, Mail, } from "lucide-react"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { cn } from "@/lib/utils"; import { PropsWithChildren, ReactElement, cloneElement } from "react"; export type PubSubState = "disconnected" | "connected" | "connecting"; export type SyncState = "syncing" | "synced" | "partiallySynced"; interface StateAttributes { [state: string]: { icon: ReactElement; color: string; tooltip?: string; }; } const connectionStates: StateAttributes = { disconnected: { tooltip: "Disconnected from server", color: "red", icon: , }, connecting: { tooltip: "Connecting to server...", color: "orange", icon: , }, connected: { tooltip: "Connected to server", color: "lightgreen", icon: , }, }; const syncStates: StateAttributes = { syncing: { tooltip: "Syncing session...", color: "orange", icon: , }, synced: { tooltip: "Session synced", color: "lightgreen", icon: , }, partiallySynced: { tooltip: "Session synced, but disconnected from server", color: "orange", icon: , }, }; function ConnectionIndicator({ color, tooltip, icon, }: { color: string; tooltip?: string; icon: ReactElement; }) { return ( {cloneElement(icon, { size: 12, color, className: "mr-1", })} {tooltip && (

{tooltip}

)}
); } interface MessagesCounterProps extends PropsWithChildren { tooltip?: string; } function MessagesCounter({ children, tooltip }: MessagesCounterProps) { return ( {children} {tooltip && (

{tooltip}

)}
); } function PubSubIndicator({ state }: { state: PubSubState }) { return ; } function SyncIndicator({ state }: { state: SyncState }) { return ; } function MessagesPanelToggle({ onClick }: { onClick?: () => void }) { return ( ); } export function StatusBar({ className, pubSubState, syncState, messagesCount, onExpandClick, }: { className?: string; pubSubState?: PubSubState; syncState?: SyncState; messagesCount?: number; onExpandClick?: () => void; }) { return (
{pubSubState && (
)} {syncState && (
)}
{messagesCount && messagesCount > 0 ? ( {messagesCount} ) : null}
); } ================================================ FILE: packages/web/src/components/target-select.tsx ================================================ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { SelectProps, SelectTriggerProps } from "@radix-ui/react-select"; import { knownTargets } from "@/settings.json"; interface TargetSelectProps extends SelectProps { triggerProps: SelectTriggerProps; } export default function TargetSelect({ triggerProps, ...props }: TargetSelectProps) { return ( ); } ================================================ FILE: packages/web/src/components/ui/button.tsx ================================================ import * as React from "react"; import { VariantProps, cva } from "class-variance-authority"; import { cn } from "../../lib/utils"; const buttonVariants = cva( "active:scale-95 inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-slate-400 focus:ring-offset-2 dark:hover:bg-slate-800 dark:hover:text-slate-100 disabled:opacity-50 dark:focus:ring-slate-400 disabled:pointer-events-none dark:focus:ring-offset-slate-900 data-[state=open]:bg-slate-100 dark:data-[state=open]:bg-slate-800", { variants: { variant: { default: "bg-slate-900 text-white hover:bg-slate-700 dark:bg-slate-50 dark:text-slate-900", destructive: "bg-red-500 text-white hover:bg-red-600 dark:hover:bg-red-600", outline: "bg-transparent border border-slate-200 hover:bg-slate-100 dark:border-slate-700 dark:text-slate-100", subtle: "bg-slate-100 text-slate-900 hover:bg-slate-200 dark:bg-slate-700 dark:text-slate-100", ghost: "bg-transparent hover:bg-slate-100 dark:hover:bg-slate-800 dark:text-slate-100 dark:hover:text-slate-100 data-[state=open]:bg-transparent dark:data-[state=open]:bg-transparent", link: "bg-transparent dark:bg-transparent underline-offset-4 hover:underline text-slate-900 dark:text-slate-100 hover:bg-transparent dark:hover:bg-transparent", }, size: { default: "h-10 py-2 px-4", sm: "h-9 px-2 rounded-md", lg: "h-11 px-8 rounded-md", }, }, defaultVariants: { variant: "default", size: "default", }, }, ); export interface ButtonProps extends React.ButtonHTMLAttributes, VariantProps { ref?: React.Ref; } const Button = ({ className, variant, size, ref, ...props }: ButtonProps) => { return ( {tooltip && (

{tooltip}

)} ); } export interface FloatingPanelToggleProps extends ToggleProps { tooltip?: string; } export function FloatingPanelToggle({ children, tooltip, className, ...props }: FloatingPanelToggleProps) { return ( {children} {tooltip && (

{tooltip}

)}
); } type Size = { width: number; height: number; }; type Position = { x: number; y: number; }; function clamp(n: number): number { return Math.min(Math.max(n, 0), 1); } export interface FloatingPanelProps extends PropsWithChildren { className?: string; id: string; header?: string; headerToolbar?: ReactNode; defaultSize?: Size; defaultPosition?: Position; } export function FloatingPanel({ children, className, id, header, headerToolbar, defaultSize = { width: 0.4, height: 0.4, }, defaultPosition = { x: 0.55, y: 0.55, }, }: FloatingPanelProps) { const [resizeTriggered, setResizeTriggered] = useState(false); const headerClassName = useMemo(() => `${id}-header`, [id]); const sizeSettingId = useMemo(() => `panel:${id}:size`, [id]); const posSettingId = useMemo(() => `panel:${id}:position`, [id]); // Size and position are relative to window.innerWidth and window.innerHeight const [size, setSize] = useState(store.get(sizeSettingId, defaultSize)); const [position, setPosition] = useState( store.get(posSettingId, defaultPosition), ); // Save position and size useEffect(() => store.set(sizeSettingId, size), [size]); useEffect(() => store.set(posSettingId, position), [position]); // Resize trigger event useEffect(() => { const resizeHandler = () => setResizeTriggered((r) => !r); window.addEventListener("resize", resizeHandler); return () => window.removeEventListener("resize", resizeHandler); }, []); const absSize = useMemo( () => ({ width: clamp(size.width) * innerWidth, height: clamp(size.height) * innerHeight, }), [size, resizeTriggered], ); const absPosition = useMemo( () => ({ x: clamp(position.x) * innerWidth, y: clamp(position.y) * innerHeight, }), [position, resizeTriggered], ); return ( e.preventDefault()} onDragStop={(_e, d) => { const { x, y } = d; setPosition({ x: clamp(x / innerWidth), y: clamp(y / innerHeight), }); }} onResizeStop={(_e, _direction, ref, _delta, position) => { setSize({ width: clamp(+ref.style.width.replace("px", "") / innerWidth), height: clamp(+ref.style.height.replace("px", "") / innerHeight), }); setPosition({ x: clamp(position.x / innerWidth), y: clamp(position.y / innerHeight), }); }} >
{header} {headerToolbar}
{children}
); } ================================================ FILE: packages/web/src/components/ui/input.tsx ================================================ import * as React from "react"; import { cn } from "@/lib/utils"; export interface InputProps extends React.InputHTMLAttributes { ref?: React.Ref; } const Input = ({ className, ref, ...props }: InputProps) => { return ( ); }; Input.displayName = "Input"; export { Input }; ================================================ FILE: packages/web/src/components/ui/label.tsx ================================================ "use client"; import * as React from "react"; import * as LabelPrimitive from "@radix-ui/react-label"; import { cn } from "@/lib/utils"; const Label = ({ className, ref, ...props }: React.ComponentProps) => ( ); Label.displayName = LabelPrimitive.Root.displayName; export { Label }; ================================================ FILE: packages/web/src/components/ui/menubar.tsx ================================================ import * as React from "react"; import * as MenubarPrimitive from "@radix-ui/react-menubar"; import { Check, ChevronRight, Circle } from "lucide-react"; import { cn } from "../../lib/utils"; const MenubarMenu = MenubarPrimitive.Menu; const MenubarGroup = MenubarPrimitive.Group; const MenubarPortal = MenubarPrimitive.Portal; const MenubarSub = MenubarPrimitive.Sub; const MenubarRadioGroup = MenubarPrimitive.RadioGroup; const Menubar = ({ className, ref, ...props }: React.ComponentProps) => ( ); Menubar.displayName = MenubarPrimitive.Root.displayName; const MenubarTrigger = ({ className, ref, ...props }: React.ComponentProps) => ( ); MenubarTrigger.displayName = MenubarPrimitive.Trigger.displayName; const MenubarSubTrigger = ({ className, inset, children, ref, ...props }: React.ComponentProps & { inset?: boolean; }) => ( {children} ); MenubarSubTrigger.displayName = MenubarPrimitive.SubTrigger.displayName; const MenubarSubContent = ({ className, ref, ...props }: React.ComponentProps) => ( ); MenubarSubContent.displayName = MenubarPrimitive.SubContent.displayName; const MenubarContent = ({ className, align = "start", ref, ...props }: React.ComponentProps) => ( ); MenubarContent.displayName = MenubarPrimitive.Content.displayName; const MenubarItem = ({ className, inset, ref, ...props }: React.ComponentProps & { inset?: boolean; }) => ( ); MenubarItem.displayName = MenubarPrimitive.Item.displayName; const MenubarCheckboxItem = ({ className, children, checked, ref, ...props }: React.ComponentProps) => ( {children} ); MenubarCheckboxItem.displayName = MenubarPrimitive.CheckboxItem.displayName; const MenubarRadioItem = ({ className, children, ref, ...props }: React.ComponentProps) => ( {children} ); MenubarRadioItem.displayName = MenubarPrimitive.RadioItem.displayName; const MenubarLabel = ({ className, inset, ref, ...props }: React.ComponentProps & { inset?: boolean; }) => ( ); MenubarLabel.displayName = MenubarPrimitive.Label.displayName; const MenubarSeparator = ({ className, ref, ...props }: React.ComponentProps) => ( ); MenubarSeparator.displayName = MenubarPrimitive.Separator.displayName; const MenubarShortcut = ({ className, ...props }: React.HTMLAttributes) => { return ( ); }; MenubarShortcut.displayname = "MenubarShortcut"; export { Menubar, MenubarMenu, MenubarTrigger, MenubarContent, MenubarItem, MenubarSeparator, MenubarLabel, MenubarCheckboxItem, MenubarRadioGroup, MenubarRadioItem, MenubarPortal, MenubarSubContent, MenubarSubTrigger, MenubarGroup, MenubarSub, MenubarShortcut, }; ================================================ FILE: packages/web/src/components/ui/popover.tsx ================================================ "use client"; import * as React from "react"; import * as PopoverPrimitive from "@radix-ui/react-popover"; import { cn } from "@/lib/utils"; const Popover = PopoverPrimitive.Root; const PopoverTrigger = PopoverPrimitive.Trigger; const PopoverContent = ({ className, align = "center", sideOffset = 4, ref, ...props }: React.ComponentProps) => ( ); PopoverContent.displayName = PopoverPrimitive.Content.displayName; export { Popover, PopoverTrigger, PopoverContent }; ================================================ FILE: packages/web/src/components/ui/select.tsx ================================================ "use client"; import * as React from "react"; import * as SelectPrimitive from "@radix-ui/react-select"; import { Check, ChevronDown } from "lucide-react"; import { cn } from "@/lib/utils"; const Select = SelectPrimitive.Root; const SelectGroup = SelectPrimitive.Group; const SelectValue = SelectPrimitive.Value; const SelectTrigger = ({ className, children, ref, ...props }: React.ComponentProps) => ( {children} ); SelectTrigger.displayName = SelectPrimitive.Trigger.displayName; const SelectContent = ({ className, children, ref, ...props }: React.ComponentProps) => ( {children} ); SelectContent.displayName = SelectPrimitive.Content.displayName; const SelectLabel = ({ className, ref, ...props }: React.ComponentProps) => ( ); SelectLabel.displayName = SelectPrimitive.Label.displayName; const SelectItem = ({ className, children, ref, ...props }: React.ComponentProps) => ( {children} ); SelectItem.displayName = SelectPrimitive.Item.displayName; const SelectSeparator = ({ className, ref, ...props }: React.ComponentProps) => ( ); SelectSeparator.displayName = SelectPrimitive.Separator.displayName; export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectLabel, SelectItem, SelectSeparator, }; ================================================ FILE: packages/web/src/components/ui/toast.tsx ================================================ import * as React from "react"; import * as ToastPrimitives from "@radix-ui/react-toast"; import { VariantProps, cva } from "class-variance-authority"; import { X } from "lucide-react"; import { cn } from "../../lib/utils"; const ToastProvider = ToastPrimitives.Provider; const ToastViewport = ({ className, ref, ...props }: React.ComponentProps) => ( ); ToastViewport.displayName = ToastPrimitives.Viewport.displayName; const toastVariants = cva( "data-[swipe=move]:transition-none grow-1 group relative pointer-events-auto flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full mt-4 data-[state=closed]:slide-out-to-right-full dark:border-slate-700 last:mt-0 sm:last:mt-4", { variants: { variant: { default: "bg-white border-slate-200 dark:bg-slate-800 dark:border-slate-700", warning: "group warning bg-yellow-700 text-white border-yellow-600 dark:border-yellow-600", destructive: "group destructive bg-red-700 text-white border-red-600 dark:border-red-600", }, }, defaultVariants: { variant: "default", }, }, ); const Toast = ({ className, variant, ref, ...props }: React.ComponentProps & VariantProps) => { return ( ); }; Toast.displayName = ToastPrimitives.Root.displayName; const ToastAction = ({ className, ref, ...props }: React.ComponentProps) => ( ); ToastAction.displayName = ToastPrimitives.Action.displayName; const ToastClose = ({ className, ref, ...props }: React.ComponentProps) => ( ); ToastClose.displayName = ToastPrimitives.Close.displayName; const ToastTitle = ({ className, ref, ...props }: React.ComponentProps) => ( ); ToastTitle.displayName = ToastPrimitives.Title.displayName; const ToastDescription = ({ className, ref, ...props }: React.ComponentProps) => ( ); ToastDescription.displayName = ToastPrimitives.Description.displayName; type ToastProps = React.ComponentPropsWithoutRef; type ToastActionElement = React.ReactElement; export { type ToastProps, type ToastActionElement, ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction, }; ================================================ FILE: packages/web/src/components/ui/toaster.tsx ================================================ import { useToast } from "../../hooks/use-toast"; import { Toast, ToastClose, ToastDescription, ToastProvider, ToastTitle, ToastViewport, } from "../../components/ui/toast"; export function Toaster() { const { toasts } = useToast(); return ( {toasts.map(function ({ id, title, description, action, ...props }) { return (
{title && {title}} {description && ( {description} )}
{action}
); })}
); } ================================================ FILE: packages/web/src/components/ui/toggle.tsx ================================================ "use client"; import * as React from "react"; import * as TogglePrimitive from "@radix-ui/react-toggle"; import { VariantProps, cva } from "class-variance-authority"; import { cn } from "@/lib/utils"; const toggleVariants = cva( "inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors data-[state=on]:bg-slate-200 dark:hover:bg-slate-800 dark:data-[state=on]:bg-slate-700 focus:outline-none dark:text-slate-100 focus:ring-2 focus:ring-slate-400 focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 dark:focus:ring-offset-slate-900 hover:bg-slate-100 dark:hover:text-slate-100 dark:data-[state=on]:text-slate-100", { variants: { variant: { default: "bg-transparent", outline: "bg-transparent border border-slate-200 hover:bg-slate-100 dark:border-slate-700", }, size: { default: "h-10 px-3", sm: "h-9 px-2.5", lg: "h-11 px-5", }, }, defaultVariants: { variant: "default", size: "default", }, }, ); const Toggle = ({ className, variant, size, ref, ...props }: React.ComponentProps & VariantProps) => ( ); Toggle.displayName = TogglePrimitive.Root.displayName; export { Toggle, toggleVariants }; ================================================ FILE: packages/web/src/components/ui/tooltip.tsx ================================================ "use client"; import * as React from "react"; import * as TooltipPrimitive from "@radix-ui/react-tooltip"; import { cn } from "@/lib/utils"; const TooltipProvider = TooltipPrimitive.Provider; const Tooltip = ({ ...props }) => ; Tooltip.displayName = TooltipPrimitive.Tooltip.displayName; const TooltipTrigger = TooltipPrimitive.Trigger; const TooltipContent = ({ className, sideOffset = 4, ref, ...props }: React.ComponentProps) => ( ); TooltipContent.displayName = TooltipPrimitive.Content.displayName; export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }; ================================================ FILE: packages/web/src/components/username-dialog.tsx ================================================ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogFooter, DialogTitle, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { DialogProps } from "@radix-ui/react-dialog"; import { useState, FormEvent, useEffect } from "react"; interface UsernameDialogProps extends DialogProps { name?: string; defaultValue?: string; onAccept?: (name: string) => void; } export default function UsernameDialog({ name, onAccept, ...props }: UsernameDialogProps) { const [nameValue, setNameValue] = useState(""); const handleSubmit = (e: FormEvent) => { e.preventDefault(); if (onAccept && nameValue) { onAccept(nameValue); } props.onOpenChange && props.onOpenChange(false); }; useEffect(() => { if (!props.open) setNameValue(""); }, [props.open]); return (
Change user name It will be shown below your cursor.
setNameValue(e.target.value.trim())} />
); } ================================================ FILE: packages/web/src/components/web-target-iframe.tsx ================================================ import { useQuery } from "@/hooks/use-query"; import { EvalMessage, Session } from "@flok-editor/session"; import { useEffect, useRef, useState } from "react"; import { DisplaySettings } from "@/lib/display-settings"; export interface WebTargetIframeProps { target: string; session: Session | null; displaySettings: DisplaySettings; } export const WebTargetIframe = ({ target, session, displaySettings, }: WebTargetIframeProps) => { const ref = useRef(null); const query = useQuery(); const noWebEval = query.get("noWebEval")?.split(",") || []; const [firstEval, setFirstEval] = useState(true); // Check if we should load the target if (noWebEval.includes(target) || noWebEval.includes("*")) { return null; } // Handle evaluation messages from session useEffect(() => { if (!session || !ref.current) return; const handler = (msg: EvalMessage) => { const payload = { type: "eval", body: msg, }; ref.current?.contentWindow?.postMessage(payload, "*"); setFirstEval(false); }; session.on(`eval:${target}`, handler); return () => { session.off(`eval:${target}`, handler); }; }, [session, ref]); // Handle user interactions useEffect(() => { const handleUserInteraction = () => { if (!ref.current) return; const interactionMessage = { type: "user-interaction" }; ref.current.contentWindow?.postMessage(interactionMessage, "*"); setFirstEval(false); }; window.addEventListener("click", handleUserInteraction); window.addEventListener("keydown", handleUserInteraction); return () => { window.removeEventListener("click", handleUserInteraction); window.removeEventListener("keydown", handleUserInteraction); }; }, [ref]); // Post display settings to iframe when the settings change, or when the // first eval occurs. The latter is a bit of a hack that prevents us from // having to detect when the iframe is ready to receive messages (adding // `ref` to the useEffect() dependencies doesn't do the trick), and it may // break if flok begins eval'ing on load (currently nothing is eval'd on // load). useEffect(() => { const message = { type: "settings", body: { displaySettings }, }; ref.current?.contentWindow?.postMessage(message, "*"); }, [displaySettings, firstEval]); return (