KScript docs
EN

The language

Packages

KScript.Core (everything above) is always there. Everything else comes from a package, imported at the top of the script, so a script only loads what it uses: a terminal script never loads the web server.

<import package="KScript.Terminal" />
<import package="KScript.Math" as="math" /> <!-- commands stay under the prefix: @math.sqrt(2) -->
<import path="lib/strings.kscript" as="str" /> <!-- another script's top-level functions and constants -->
<import names="slugify" path="lib/strings.kscript" />
<!-- … -->
import KScript.Terminal
import KScript.Math as math // commands stay under the prefix: @math.sqrt(2)
import "lib/strings.kscript" as str // another script's top-level functions and constants
import slugify from "lib/strings.kscript"
// …

Only .kscript and .ks.xml files can be imported. A function the script declares itself wins over an imported one of the same name, and an imported const stays a constant.

Package What it adds
KScript.Terminal input(into, type, default, secret) (type can be email, handle, uuid or password), picker (a file or folder path), menu(options, multiple), progress(into, total) with ->advance(), confirm, pause, clear, @color(text, color: 'green'), @bold, @dim, @underline, @terminal_width(), @is_terminal() (no when output is piped), echo(format: markdown), and the kscript command line's own look: info, success, warn, alert(type: error), heading, detail(name), bullets(items), task(name) { }, table(rows, columns, header, align) (see Terminal output)
KScript.Math @sqrt @round(x, digits: 2) @clamp(x, min: 0, max: 10) @logarithm @sin @cos @atan2 @hypot @gcd @factorial @random(low: 1, high: 6) @random_bytes(16, format: hex) @pick @shuffle @sum @average @median @stdev @variance @mode @percentile(values, 95), $pi $e
KScript.IO @read_text @read_lines @read_json @write_text @append_text @write_json @files(folder, pattern: '*.txt', recursive) @folders @file(path) @exists @join_path(base: $dir, ['a', 'b.txt']) @known_folder(downloads), @move(from, to) @copy(from, to) @delete(path) @create_folder(path). File values have the fields .name .extension .mime .size .modified… and the methods ->read_text() ->read_bytes() ->read_json(as:) ->sha256() ->write_text(text) ->copy_to(path) ->move_to(path) ->delete().
KScript.Net Sends HTTP requests with @api(url, options: { method, headers, body, timeout }), or the shorthands post:, put:, patch:, delete:, bearer:, timeout:, retries:, as:, encoding: (json, form or multipart) and query:. The response has .status, .is_ok, .text, ->convert(from: json) and ->check(). Also provides @download(url, to) and @query_string. A path such as '/api/notes' asks the project's own routes. See Calling your own API.
KScript.Markdown @markdown(text) and @read_markdown(path) (html, title, meta from front matter), ->convert(from: markdown, to: html)
KScript.Web Renders pages with layouts, components and live blocks for kscript serve. Pages have KScript.IO, KScript.Markdown and KScript.Web without importing them.
KScript.AI @llm(prompt, system, schema, tools, model, max_tokens), llm(into, system, schema, tools, model, max_tokens), @chat(system) with ->ask() .history ->reset(), and @fake_llm(replies) for tests. Claude, with the key from ANTHROPIC_API_KEY (see Language models).
KScript.Style Stylesheets written in KScript (.ks.css, .ks.scss, .ks.sass); @up, @down, @between, @rem, @fluid, @adjust_lightness, @lighten, @darken, @mix, @alpha, @contrast_color, @css_var, @css_vars; @stylesheet(path, vars) (see Stylesheets).
KScript.Http Routes, controllers and middleware for kscript serve: a Routes { } file holds Get Post Put Patch Delete Any Route Resource Group Middleware. Controllers use @view, @response, @redirect, @abort and @route. See Routes, controllers and middleware.
KScript.Storage The app's own folders, in the right place on each platform: @storage(config) (also data, cache, state, logs) with ->read ->read_json ->write ->write_json ->read_bytes ->write_bytes ->file ->move ->copy ->append ->list ->delete ->folder ->path_of, plus @app_name() and @app_folders(). See App folders.
KScript.Cache $cache (in memory) and @cache(file) with ->get ->set ->remember(key, fn, ttl: 10m) ->has ->remove ->increment ->ttl ->keys ->clear. See Caching.
KScript.Data Stores records with model, queries them with a query builder, and manages schema changes with Migration and kscript db migrate. See Databases.
KScript.Queue Declares background work with job, queues it with ->dispatch() and runs it with kscript worker. Its Schedule runs tasks at set times. See Queues and jobs and Scheduling tasks.
KScript.Mail Sends email with @send_mail(to:, subject:, html:|text:|view:) over SMTP, to the log or to a fake, now or with queue from kscript worker. @fake_mail() keeps it for tests. See Mail.
KScript.Auth Sign-in for kscript serve apps: @register, @attempt, @login, @logout, @user(), @is_signed_in(), $session (->get ->set ->flash …), @users(), @csrf_field(), @reset_token, @reset_password, @api_token, and the auth and guest middleware. See Sign-in.
KScript.Document Document(template: paper, to: "paper.pdf") { } with Section, Paragraph, List, Table, Figure, Math, Bibliography and more; Letter and Invoice; ->save ->pages ->words ->markdown ->latex ->html. See Documents.
KScript.UI Desktop windows: a Window { } block opens one. Column Row Grid Text Button TextBox CheckBox Select Slider Box Spacer Timer, @close_window(). See Desktop apps.
KScript.Test test, describe, before_each, after_each, expect, expect_error, capture, @assert, @fail, @run_script, @check_script. Test files import it on their own (see Testing scripts).

Using something from a package that isn't imported stops with input is part of KScript.Terminal. Add import KScript.Terminal at the top of the script., and the editor offers to add the import. A package is named only in an import: a statement is never written with the KScript. prefix (input, not KScript.input), and nothing is imported silently, job and dispatch included (import KScript.Queue). A project can import packages for every script in kscript.json (below).

Cryptographically secure random bytes

@random_bytes(count, format: hex) reads entropy from the operating system. Give it a whole byte count from 1 to 65536. Lowercase hex uses two characters per byte. The base64url format uses URL-safe characters and omits padding. Both formats are independent of @random_seed().

<import package="KScript.Math" />

<let name="key" value="@random_bytes(16)" /> <!-- 32 hex characters -->
<let name="url_token" value="@random_bytes(16, format: base64url)" /> <!-- 22 characters -->
import KScript.Math

$key = @random_bytes(16)                        // 32 hex characters
$url_token = @random_bytes(16, format: base64url) // 22 characters

Names of statements and arguments

Statements and their arguments follow one set of rules in every package, and kscript check and the test suite hold the built-in ones to them:

Rule Examples
A statement that does something, or declares something, is a lower snake_case word. input, table, before_each, expect_error, log_provider
Statements that describe a window, route table or document in KScript.UI, KScript.Http and KScript.Document use PascalCase. In KScript.Data, Migration and its schema steps also use PascalCase. Button, Routes, Get, Section, Migration, CreateTable
Arguments are snake_case. No name has a hyphen. max_tokens, must_exist, on_click, new_page
into: is the variable that receives a result. input(into: name), llm(into: reply), capture(into: out)
to: is where something goes: a file, a URL, a controller. It never names a variable. Get(path: /, to: @home), Post(path: /notes, to: @notes.add)
path: is the file a statement reads or acts on. import(path: "lib.kscript"), <include path="_nav.html">, <layout path="_layout.html">
at is a position, as in for item at i in $list. menu(into: choice, at: i)
A function is named as @name, as it is in an expression. spawn(fn: @job), llm(tools: [@order_status]), Get(to: @people.show)

Three kinds of name are not functions and stay bare: a controller (Resource(to: people) is the name a script is imported as), the names in a middleware list ([log, throttle:30, my_check], where built-ins, groups and functions share one list), and a variable or type being declared. In XML the same arguments are attributes with the same names, and a function is written without the @ (<spawn fn="job" />); kscript convert adds and removes it.

In a page, on-click and the other handlers sit on HTML tags (<button on-click="$count += 1">), so they keep HTML's hyphen. On KScript's own elements, such as Button, the argument is on_click.

A name from before these rules is an error that says the new one ('to' is now into.), and kscript check --fix renames it. Letting a statement be assigned ($name = input "Name? ") is not part of the language yet.

Terminal output

KScript.Terminal prints the same way the kscript commands do, so a script's output looks like the rest of the tool. Colours are only used at a terminal: piped output, files and tests get the same text without them, and NO_COLOR, FORCE_COLOR, --ansi and --no-ansi work as they do for kscript itself.

<import package="KScript.Terminal" />

<let name="people" value="[{ name: 'Joan', age: 82 }, { name: 'Sam', age: 9 }]" />
<heading>Report</heading>
<detail name="People">{ $people->count() }</detail>
<task name="Adding up">
  <let name="total" value="1 + 2" />
</task>
<table rows="$people" />
<info>Wrote [report.txt].</info>
<alert type="error">The file [data.csv] is empty.</alert>
import KScript.Terminal

$people = [{ name: 'Joan', age: 82 }, { name: 'Sam', age: 9 }]
heading "Report"
detail(name: 'People') "{ $people->count() }"
task(name: 'Adding up') {
  $total = 1 + 2
}
table(rows: $people)
info "Wrote [report.txt]."
alert(type: error) "The file [data.csv] is empty."
Text
Report
  People .................................................... 2
  Adding up .......................................... 2ms DONE
  ┌──────┬─────┐
  │ name │ age │
  ├──────┼─────┤
  │ Joan │  82 │
  │ Sam  │   9 │
  └──────┴─────┘
   INFO  Wrote [report.txt].
   ERROR  The file [data.csv] is empty.

[bracketed] parts of a label are shown in bold. alert(type: error) writes to stderr. Numbers in a table line up on the right; align: ['left', 'right'] sets each column.

Work done in steps gets a progress bar. progress(into: bar, total: n) shows it with its text as the label, and $bar->advance() moves it on one step (or ->advance(5) for five). At a terminal it is redrawn in place; piped output and tests get one line, like a task's, when it reaches the total:

<import package="KScript.Terminal" />

<let name="files" value="['a.csv', 'b.csv', 'c.csv']" />
<progress into="bar" total="$files->count()">Importing</progress>
<for each="_file" in="$files">
  <do>$bar->advance()</do>
</for>
import KScript.Terminal

$files = ['a.csv', 'b.csv', 'c.csv']
progress(into: bar, total: $files->count()) "Importing"
for _file in $files {
  $bar->advance()
}

menu(multiple: true) lets the answer pick several choices, such as 1, 3, and stores a list of them in the menu's order (and at: a list of their positions).

Edit this page on GitHub