KScript docs
EN

kscript make commands

kscript make <type> <name> makes a file where the project keeps that kind of file, and makes any folder it needs. Scripts are written in the project's format (.kscript unless make.syntax in kscript.json says xml). kscript make --list prints this list, and kscript make <type> --help prints one entry.

Every type comes from a template. kscript make templates copies them to the project's _templates folder, where you can change what they make or add types of your own. Add --dry-run to any command to see what it would make, and --force to replace a file. In a new project, make route name=users runs kscript make route users (see Projects).

CommandWhat it makes
kscript make routeA route, added to routes.kscript (or api.kscript with --api), with its controller made if it's missing
kscript make controllerA controller in controllers/: functions that answer routes
kscript make requestA typed request body in requests/: a controller parameter typed with it only sees data of that shape
kscript make middlewareMiddleware in middleware/: a function that runs around routes, and can stop a request or change its response
kscript make viewA view in views/ that a controller renders with @view('name', …)
kscript make mailAn email's view in views/mail/, sent with @send_mail(..., view: 'mail/name') from KScript.Mail
kscript make pageAn HTML page; its path is its URL (people/[id] matches /people/42)
kscript make markdownA Markdown page with front matter (title, layout)
kscript make layoutA page layout; pages use it with <layout path="…" title="…">
kscript make componentA component type with a render method: an HTML tag in a page, or a statement in a window, a document or the terminal
kscript make partialA piece of HTML in _partials/ that pages insert with <include path="…">
kscript make cssA stylesheet in KScript (.ks.css) in styles/ that compiles to .css; kscript serve compiles it on each request
kscript make scriptA KScript script in scripts/, run with kscript <file>
kscript make moduleA library of functions in lib/ that scripts, pages, controllers and tests import
kscript make typeA type in types/ that checks data and turns it into a record (API responses, JSON files, request bodies)
kscript make nativeA native type in natives/: a value of your own, like email or handle, that its validator checks wherever it is used and that can be written without quotes. Every script in the project can use it without an import
kscript make modelA model in models/: a type whose records are kept in a database table, with a query builder (User->where(...))
kscript make migrationA migration in database/migrations to write by hand: steps that change the tables, run by kscript db migrate. kscript db diff writes one from the models instead
kscript make seederA seeder in database/seeders: a script that fills the database with records, run by kscript db seed
kscript make enumAn enum in types/: a set of named values that typed parameters and fields only accept
kscript make errorAn error type in errors/, thrown with throw Name(...) and caught with catch Name as e
kscript make constConstants in lib/: values that never change, shared by every script that imports the file
kscript make storageA JSON file store in lib/: all, find, save and remove for a list of records kept in data/
kscript make cacheA file cache in lib/: remember a slow result (an API call, a big file) for some minutes
kscript make jobA queued job in jobs/: dispatch it with Name(...)->dispatch(), and kscript worker runs it, retrying when it fails
kscript make scheduleThe schedule file, schedule.kscript, with a first task: kscript schedule work runs its tasks at their times
kscript make eventAn event in events/: something that happened, dispatched with @dispatch_event() to every listener
kscript make listenerA listener in listeners/: functions that run when an event is dispatched with @dispatch_event()
kscript make extensionMethods added to a type, such as date or list, in extensions/: every script in the project gets them
kscript make policyA policy in policies/: who may create, read, update and delete a model's records, asked with @can and @authorize
kscript make windowA desktop window (Window, from KScript.UI): a native app on macOS, Windows and Linux
kscript make documentA document script in documents/ that writes a PDF and a Word file (KScript.Document)
kscript make configSettings for $config: config.kscript for values that need code, or kscript.<env>.json for one environment
kscript make envA .env file of NAME=value secrets: .env, or .env.<env> for one environment; never served
kscript make localeTranslations for one language in locales/, for @t('key') in scripts and pages
kscript make loggerA log provider in lib/: a function that gets every log entry at or above a level
kscript make testA test file in tests/, run with kscript test

#Routes and APIs

#kscript make route

Shell
kscript make route <path> [--method get|post|put|patch|delete] [--api] [--to controller.action] [--resource] [--view name] [--name route.name]

A route, added to routes.kscript (or api.kscript with --api), with its controller made if it's missing

OptionDescription
--methodThe HTTP method: get (the default), post, put, patch, delete, options or any
--apiAdd it to api.kscript, served under /api with JSON errors, instead of routes.kscript
--toThe controller function that answers it, such as people.list. By default the path picks it: users gives users.index, users/{id} gives users.show, and --method post gives users.store
--controllerThe controller to use or make, such as admin/users (default: the path without its {parameters})
--actionThe controller function (default from the method: index or show, store, update, destroy)
--resourceAdd Resource(path: …, to: …) for index, show, store, update and destroy, and make a resource controller
--viewAnswer with this view (made in views/ if it's missing) instead of a controller
--nameA name for @route('name')
--whereRules for the parameters, such as "id: int"
Example
Shell
kscript make route users
kscript make route "users/{id}" --where "id: int"
kscript make route users --method post --api
kscript make route people --resource --api
kscript make route about --view about
kscript make route reports/export --to reports.export

#kscript make controller

Shell
kscript make controller <name> [--resource] [--model Post] [--actions index,export]

A controller in controllers/: functions that answer routes

OptionDescription
--resourceWrite index, show, store, update and destroy, for Resource(path: /people, to: people)
--modelFill the resource actions in with a model's records (Post->paginate, ->find_or_fail, ->create, ->update and ->delete); implies --resource
--actionsThe functions to write, comma separated (default index)
Example
Shell
kscript make controller people --resource
kscript make controller reports --actions index,export
kscript make controller admin/users --resource
kscript make controller posts --model Post

#kscript make request

Shell
kscript make request <Name> [--fields "name: string, age?: int"]

A typed request body in requests/: a controller parameter typed with it only sees data of that shape

OptionDescription
--fieldsThe fields, comma separated, as name: type (? for optional, = for a default). Default: name: string
Example
Shell
kscript make request NewPerson --fields "name: string, age?: int, role?: string"
kscript make request orders/NewOrder --fields "product: string, quantity: int = 1"

#kscript make middleware

Shell
kscript make middleware <name> [--header X-Name] [--before]

Middleware in middleware/: a function that runs around routes, and can stop a request or change its response

OptionDescription
--beforeWrite a check that can turn a request away before the controller runs
--headerAdd this header to every response (default X-Handled-By)
Example
Shell
kscript make middleware secure-headers --header X-Frame-Options
kscript make middleware admin-only --before

#kscript make view

Shell
kscript make view <name> [--vars person,team] [--layout _layout.html] [--title "Title"]

A view in views/ that a controller renders with @view('name', …)

OptionDescription
--varsThe values the controller passes, comma separated; each is shown in the view
--layoutThe layout it uses (default _layout.html)
--titleThe page title (default from the name)
Example
Shell
kscript make view people/show --vars person
kscript make view home --title "Welcome"

#kscript make mail

Shell
kscript make mail <name> [--vars name,link] [--subject "Subject"]

An email's view in views/mail/, sent with @send_mail(..., view: 'mail/name') from KScript.Mail

OptionDescription
--varsThe values the email shows, comma separated; @send_mail passes them as data
--subjectThe subject the hint sends it with (default from the name)
Example
Shell
kscript make mail welcome --vars name
kscript make mail orders/shipped --vars name,order_id,link

#Pages and styles

#kscript make page

Shell
kscript make page <path> [--title "Title"] [--layout _layout.html]

An HTML page; its path is its URL (people/[id] matches /people/42)

OptionDescription
--titleThe page title (default from the name)
--layoutThe layout it uses (default _layout.html, made if it is missing)
Example
Shell
kscript make page about --title "About us"
kscript make page "people/[id]"

#kscript make markdown

Shell
kscript make markdown <path> [--title "Title"] [--layout _layout.html]

A Markdown page with front matter (title, layout)

OptionDescription
--titleThe page title (default from the name)
--layoutThe layout it uses (default _layout.html)
Example
Shell
kscript make markdown blog/first-post
kscript make markdown docs/setup --layout _layouts/docs.html

#kscript make layout

Shell
kscript make layout <name> [--css a.css,b.css] [--lang en]

A page layout; pages use it with <layout path="…" title="…">

OptionDescription
--cssStylesheets to link, comma separated
--langThe page language (default en)
Example
Shell
kscript make layout blog --css /site.css
kscript make layout docs --lang fr

#kscript make component

Shell
kscript make component <Name> [--for window|terminal|document] [--model Model [--inject [ability]]] [--fields title,body] [--model-update binding [--autosave]] [--props title,image] [--live]

A component type with a render method: an HTML tag in a page, or a statement in a window, a document or the terminal

OptionDescription
--forDraw it in a window, a document or the terminal instead of a page
--modelBind to an existing model, e.g. --model Note, and take a row as its input
--injectTake the route's record with @inject(can: read), so a page needn't pass it. Supply another ability, e.g. --inject update
--model-updateUse an existing ModelUpdate route to save edits
--fieldsModel fields to display or edit, comma separated. Defaults to the fields of a known ModelUpdate route
--autosaveSave after typing pauses (500ms by default). Supply a delay, e.g. --autosave 750ms
--propsExtra inputs, comma separated
--liveAdd an interactive live block
Example
Shell
kscript make component Hero --props title,subtitle
kscript make component OrderDetails --live
kscript make component NoteCard --for window --props title,body

#kscript make partial

Shell
kscript make partial <name>

A piece of HTML in _partials/ that pages insert with <include path="…">

Example
Shell
kscript make partial footer
kscript make partial blog/sidebar

#kscript make css

Shell
kscript make css <name> [--primary "#3355ff"] [--theme theme.json]

A stylesheet in KScript (.ks.css) in styles/ that compiles to .css; kscript serve compiles it on each request

OptionDescription
--primaryThe main colour (default #3355ff)
--themeRead colours from this JSON file instead, such as theme.json with { "colors": { "primary": "…" } }
Example
Shell
kscript make css site
kscript make css css/theme --primary "#0a7"
kscript make css brand --theme theme.json

#Scripts and data

#kscript make script

Shell
kscript make script <name> [--syntax kscript|xml]

A KScript script in scripts/, run with kscript <file>

OptionDescription
--syntaxkscript or xml (default the project's make.syntax)
Example
Shell
kscript make script tidy-downloads
kscript make script tools/backup --syntax xml

#kscript make module

Shell
kscript make module <name> [--fns greet,farewell]

A library of functions in lib/ that scripts, pages, controllers and tests import

OptionDescription
--fnsThe functions to write, comma separated (default one named after the file)
Example
Shell
kscript make module pricing --fns subtotal,tax,total
kscript make module text/slugs

#kscript make type

Shell
kscript make type <Name> [--fields "name: string, stars: int from stargazers_count"] [--sample data/repo.json]

A type in types/ that checks data and turns it into a record (API responses, JSON files, request bodies)

OptionDescription
--fieldsThe fields, comma separated, as name: type, with ? for optional, = for a default and from for another key. Default: name: string
--sampleTake the fields from a saved example of the data instead
Example
Shell
kscript make type Repo --fields "name: string, stars: int from stargazers_count, topics: string[] = []"
kscript make type Order --sample data/order.json

#kscript make native

Shell
kscript make native <Name> [--base string] [--pattern "/^[A-Z]{3}-\d{4}$/"] [--min 3] [--max 30] [--one-of a,b] [--not a,b] [--normalize "$value->trim()"] [--validate "test, 'message'"] [--value ".group(1)->to_int()"]

A native type in natives/: a value of your own, like email or handle, that its validator checks wherever it is used and that can be written without quotes. Every script in the project can use it without an import

OptionDescription
--baseThe type it is made from: string, int, float, number, a native type such as email, url, domain, slug or country, or another of your types (default string)
--patternA regex the whole value must match, such as "/^[A-Z]{3}-\d{4}$/i"
--minThe smallest number, or the shortest text or list
--maxThe largest number, or the longest text or list
--one-ofThe only values allowed, comma separated
--notValues that are never allowed, comma separated
--normalizeAn expression that tidies the value, as $value, before it is checked, such as "$value->trim()->upper()"
--validateAny other check, with the message to show when it fails: "test, 'message'"
--valueWhat a value reads as wherever it is used, worked out once every rule has passed, such as ".group(1)->to_int()"
Example
Shell
kscript make native Sku --pattern '/^[A-Z]{3}-\d{4}$/' --normalize '$value->trim()->upper()'
kscript make native Percent --base int --min 0 --max 100
kscript make native CompanySite --base url --validate '$value.host->ends_with("example.com"), "Use a company site"'
kscript make native Username --base handle --max 16 --not @admin,@root
kscript make native Multiplier --pattern '/^x(\d+)$/' --value '.group(1)->to_int()'

#kscript make model

Shell
kscript make model <Name> [--fields "name: string, email: email"] [--timestamps] [--soft-deletes] [--component] [--policy] [--migration] [--controller] [--seeder] [--all]

A model in models/: a type whose records are kept in a database table, with a query builder (User->where(...))

OptionDescription
--fieldsThe fields, comma separated, as name: type, with ? for optional and = for a default. Default: name: string
--timestampsExtend Timestamps: created_at and updated_at, set when records are saved
--soft-deletesExtend SoftDeletes: mark records deleted instead of removing them, so they can be restored
--componentAlso create a component that takes a row of this model as record
--policyAlso create its policy in policies/, which @can and @authorize ask
--migrationAlso write the migration that makes its table, with kscript db diff
--controllerAlso create a resource controller filled in with the model (kscript make controller --model)
--seederAlso create a seeder in database/seeders that makes some of its records
--allAll of --component, --policy, --migration, --controller and --seeder
Example
Shell
kscript make model User --fields "name: string, email: email, password: password" --timestamps
kscript make model BlogPost --fields "title: string, body: string, published: bool = false" --soft-deletes
kscript make model Note --fields "title: string, body: string" --component
kscript make model Post --fields "title: string, body: string" --timestamps --all

#kscript make migration

Shell
kscript make migration <name>

A migration in database/migrations to write by hand: steps that change the tables, run by kscript db migrate. kscript db diff writes one from the models instead

Example
Shell
kscript make migration add_bio_to_users
kscript make migration backfill_slugs

#kscript make seeder

Shell
kscript make seeder <name> [--model Post]

A seeder in database/seeders: a script that fills the database with records, run by kscript db seed

OptionDescription
--modelThe model it makes records of: it is imported, ready for Post->create(...)
Example
Shell
kscript make seeder users
kscript make seeder posts --model Post

#kscript make enum

Shell
kscript make enum <Name> [--values small,medium,large]

An enum in types/: a set of named values that typed parameters and fields only accept

OptionDescription
--valuesThe values, comma separated (default one, two, three)
Example
Shell
kscript make enum Size --values small,medium,large
kscript make enum OrderStatus --values pending,paid,shipped,cancelled

#kscript make error

Shell
kscript make error <Name> [--status 402] [--extends Validation] [--message "..."] [--fields "order: int, reason?: string"]

An error type in errors/, thrown with throw Name(...) and caught with catch Name as e

OptionDescription
--statusThe HTTP status a KScript.Http route answers with when nothing catches it, such as 402
--extendsThe error type it is a kind of, such as NotFound or Validation (default Error)
--messageThe message, with the fields as variables: 'No order {$id}' (default the name in words)
--fieldsThe fields, comma separated, as name: type, with ? for optional and = for a default
Example
Shell
kscript make error PaymentFailed --status 402 --fields "order: int, reason?: string"
kscript make error OrderNotFound --extends NotFound --message 'No order {$id}' --fields "id: int"

#kscript make const

Shell
kscript make const <name> [--values "max_items = 10, site_name = 'Shop'"]

Constants in lib/: values that never change, shared by every script that imports the file

OptionDescription
--valuesThe constants, comma separated, as name = value (default an example)
Example
Shell
kscript make const limits --values "max_items = 10, page_size = 25"
kscript make const app --values "name = 'Shop', version = '1.0'"

#kscript make storage

Shell
kscript make storage <name> [--file data/people.json]

A JSON file store in lib/: all, find, save and remove for a list of records kept in data/

OptionDescription
--fileThe JSON file it keeps the records in (default data/<name>.json)
Example
Shell
kscript make storage people
kscript make storage orders --file data/shop/orders.json

#kscript make cache

Shell
kscript make cache <name> [--minutes 10] [--file data/cache.json]

A file cache in lib/: remember a slow result (an API call, a big file) for some minutes

OptionDescription
--minutesHow long a value is kept (default 10)
--fileThe JSON file it keeps values in (default data/<name>.json)
Example
Shell
kscript make cache api-cache --minutes 30
kscript make cache reports --file data/report-cache.json

#kscript make job

Shell
kscript make job <Name> [--fields "user_id: int, email: email"] [--queue mail] [--tries 5] [--backoff "10s, 1m, 5m"] [--timeout 30s]

A queued job in jobs/: dispatch it with Name(...)->dispatch(), and kscript worker runs it, retrying when it fails

OptionDescription
--fieldsThe fields, comma separated, as name: type, with ? for optional and = for a default (default: none)
--queueThe queue it goes on (default: default)
--triesHow many attempts it gets before it counts as failed (default: 3)
--backoffHow long to wait before each retry, such as "10s, 1m, 5m" (default: exponential)
--timeoutThe longest one attempt may run, such as 30s or 5m (default: 60s)
Example
Shell
kscript make job SendWelcome --fields "user_id: int, email: email" --queue mail --tries 5
kscript make job reports/BuildReport --fields "month: int" --timeout 5m

#kscript make schedule

Shell
kscript make schedule <task> [--every 1h | --cron "0 3 * * *"]

The schedule file, schedule.kscript, with a first task: kscript schedule work runs its tasks at their times

OptionDescription
--everyHow often the task runs, in whole minutes, such as 5m or 1h (default: 1h)
--cronWhen it runs instead, as a cron schedule, such as "0 3 * * *" for 03:00 each day
Example
Shell
kscript make schedule prune-sessions --every 1h
kscript make schedule nightly-report --cron "0 3 * * *"

#kscript make event

Shell
kscript make event <Name> [--fields "order_id: int, total: number"]

An event in events/: something that happened, dispatched with @dispatch_event() to every listener

OptionDescription
--fieldsThe fields, comma separated, as name: type, with ? for optional and = for a default (default: none)
Example
Shell
kscript make event OrderPlaced --fields "order_id: int, total: number"
kscript make event UserSignedUp --fields "user_id: int"

#kscript make listener

Shell
kscript make listener <Event>

A listener in listeners/: functions that run when an event is dispatched with @dispatch_event()

Example
Shell
kscript make listener OrderPlaced
kscript make listener UserSignedUp

#kscript make extension

Shell
kscript make extension <type> [--methods api_date,is_payday]

Methods added to a type, such as date or list, in extensions/: every script in the project gets them

OptionDescription
--methodsThe methods to start with, comma separated. Each returns $this until you fill it in
Example
Shell
kscript make extension date --methods api_date,is_payday
kscript make extension text/string --methods slug
kscript make extension list --methods second

#kscript make policy

Shell
kscript make policy <Model>

A policy in policies/: who may create, read, update and delete a model's records, asked with @can and @authorize

Example
Shell
kscript make policy BlogPost
kscript make policy User

#Desktop apps

#kscript make window

Shell
kscript make window <name> [--title "Title"] [--width 480] [--height 360]

A desktop window (Window, from KScript.UI): a native app on macOS, Windows and Linux

OptionDescription
--titleThe window title (default from the name)
--widthThe width (default 480)
--heightThe height (default 360)
Example
Shell
kscript make window settings --width 400 --height 300
kscript make window windows/about --title "About this app"

#Documents

#kscript make document

Shell
kscript make document <name> [--template paper|report|plain|letter|invoice] [--syntax kscript|xml]

A document script in documents/ that writes a PDF and a Word file (KScript.Document)

OptionDescription
--templateThe look: paper, report, plain, letter or invoice (default paper)
--syntaxkscript or xml (default the project's make.syntax)
Example
Shell
kscript make document annual-report --template report
kscript make document papers/gliders

#Settings

#kscript make config

Shell
kscript make config <base|environment>

Settings for $config: config.kscript for values that need code, or kscript.<env>.json for one environment

Example
Shell
kscript make config base
kscript make config staging

#kscript make env

Shell
kscript make env <base|environment> [--keys API_TOKEN,DATABASE_URL]

A .env file of NAME=value secrets: .env, or .env.<env> for one environment; never served

OptionDescription
--keysThe variable names to add, comma separated (default API_TOKEN)
Example
Shell
kscript make env base --keys API_TOKEN,DATABASE_URL
kscript make env staging

#kscript make locale

Shell
kscript make locale <locale> [--keys hello,goodbye]

Translations for one language in locales/, for @t('key') in scripts and pages

OptionDescription
--keysKeys to add, comma separated, each with its name as the text to translate
Example
Shell
kscript make locale fr
kscript make locale en-GB --keys welcome,sign_in

#kscript make logger

Shell
kscript make logger <name> [--level warn]

A log provider in lib/: a function that gets every log entry at or above a level

OptionDescription
--levelThe lowest level it gets: trace, debug, info, warn (the default), error or fatal
Example
Shell
kscript make logger alerts --level error
kscript make logger audit --level info

#Tests

#kscript make test

Shell
kscript make test <name> [--syntax kscript|xml]

A test file in tests/, run with kscript test

OptionDescription
--syntaxkscript or xml (default the project's make.syntax)
Example
Shell
kscript make test checkout
kscript make test api/people