KScript docs
EN

Projects and kscript.json

Generating files: kscript make

kscript make <type> <name> creates a file where the project keeps that kind of file, makes any folder it needs, and writes scripts in the project's format. kscript make commands lists every type with its options and examples, and so does kscript make --list; kscript make <type> --help shows one.

CommandWhat it does
kscript make route usersAdds Get(path: /users, to: @users.index) to routes/web.kscript, and makes controllers/users.kscript with index()
kscript make route "users/{id}" --where "id: int"Get(…, to: @users.show), and adds show(id) to the controller.
kscript make route users --method post --apiPost(…, to: @users.store) in routes/api.kscript, served under /api.
kscript make route people --resource --apiResource(path: /people, to: people), with all five functions.
kscript make route about --view aboutGet(path: /about, view: "about"), and views/about.html.
kscript make controller people --resourceControllers/people.kscript: index, show, store, update, destroy.
kscript make request NewPerson --fields "name: string, age?: int"Requests/new-person.kscript, a typed body.
kscript make middleware secure-headersMiddleware/secure-headers.kscript.
kscript make view people/show --vars personViews/people/show.html, for @view('people/show', person: $p)
kscript make component Hero --props title,sub-title_components/hero.kscript, used as <hero title="…" sub-title="…" />.
kscript make component NoteCard --for window --props titleComponents/note-card.kscript, drawn in a window as NoteCard(title: …)
kscript make component PostCard --model Post --inject_components/post-card.kscript, takes the route's post with @inject(can: read)
kscript make page about --title "About us"About.html, wrapped in _layout.html (created if missing)
kscript make page "people/[id]"People/[id].html, with $id read from the URL.
kscript make css theme --primary "#3355ff"Styles/theme.ks.css, served as /styles/theme.css.
kscript make type Repo --fields "name: string, stars: int from stargazers_count"Types/repo.kscript.
kscript make enum Size --values small,medium,largeTypes/size.kscript.
kscript make native Sku --pattern "/^[A-Z]{3}-\d{4}$/"Natives/sku.kscript: works in every script without an import.
kscript make module pricing --fns subtotal,totalLib/pricing.kscript.
kscript make window settingsSettings.kscript, a desktop window.
kscript make document annual-reportDocuments/annual-report.kscript, a PDF and Word document.
kscript make config stagingKscript.staging.json, settings for the staging environment.
kscript make test checkoutTests/checkout.test.kscript.
kscript make error PaymentFailed --status 402 --fields "order: int"Errors/payment-failed.kscript.
kscript make extension date --methods api_date,is_paydayExtensions/date.kscript: extend date { fn api_date() … }.
kscript make policy PostPolicies/post.kscript: policy for Post { fn update(user, post) … }.
kscript make auth --apiSign up, sign in, resets and API tokens (see Sign-in)
kscript makeList every type.

Leave out the name at a terminal and kscript make asks for it: kscript make page asks what the page should be called and then, because no options were given either, asks about each of the page's options. A yes/no option such as --timestamps is a yes/no question, and pressing Enter skips any other option. Give any option and only the name is asked. With -n (--no-interaction), or when the input or output isn't a terminal, nothing is asked and a missing name is an error.

The files it makes have the functions each kind needs already written, with a // TODO: comment (<!-- TODO: --> in HTML) saying what to put in them. A controller's show(id) says to find the record and answer 404 when there is none, and a job's handle() says to do the work there. The files pass kscript check and kscript fmt --check as they are.

A route goes in routes/web.kscript, or routes/api.kscript with --api. A project that already keeps routes.kscript or api.kscript at the top, or lists its route files in http.routes, gets the route there instead. The route file imports the controller, and the route is refused if the file already has one for the same method and path. struct and record are other names for type, and fn and function for module: there is a generator for every kind of thing a script can declare (functions, constants, enums and types).

An option's value is checked before anything is written. kscript make job Send --tries abc, make error E --status abc, make document d --template nope and make route "a b/{id}" each stop with a message saying what the value should be, and exit with 2. kscript make project does the same for an option its template doesn't have, and lists the ones it has. make document --template takes paper, report, plain, letter or invoice.

kscript make puts each kind of file in its own folder, and makes the folder the first time it is needed, so a project only has the folders it uses:

Text
my-app/
  kscript.json     settings, including "paths"
  schedule.kscript tasks that run at set times (make schedule)
  Makefile
  .env             secrets (make env); never served
  routes/          web.kscript (served at /) and api.kscript (served at /api)
  controllers/     make controller, make route
  middleware/      make middleware
  requests/        make request
  views/           make view
  _components/     make component (folders starting with _ are never served)
  _layouts/        make layout (the default _layout.html stays at the top)
  _partials/       make partial
  styles/          make css
  lib/             make module, const, cache, storage and logger
  types/           make type, make enum
  models/          make model
  policies/        make policy: who may create, read, update and delete a model's records
  natives/         make native: types every script gets without an import
  extensions/      make extension: methods every script gets (extend date { … })
  errors/          make error
  jobs/            make job
  documents/       make document
  locales/         make locale
  data/            JSON that stores and caches write
  scripts/         make script
  tests/           make test

One type per file. Each type, model, enum and error type has a file of its own, named after it (OrderStatus in types/order-status.kscript), and the files that use it import it:

<!-- models/order.kscript -->
<import package="KScript.Data" />
<import path="../types/order-status.kscript" />

<model name="Order">
  <field name="status" type="OrderStatus" default="'open'" />
</model>
// models/order.kscript
import KScript.Data
import "../types/order-status.kscript"

model Order {
  status: OrderStatus = 'open'
}

The generators and project templates all work this way, and in a project kscript check warns (KS6008) about a file that declares a second type, saying where to move it. A script outside a project, run on its own, can keep its types with it. A component can hold the types, enums, errors and models that only it uses inside its own block.

Two things are found without an import. Native types in natives/ work in every script (they are part of the language, like email). And a model's field can name another model in the models folder (paths.models) without importing it, because two models that link to each other (author: User in one, posts: Post[] in the other) would otherwise import each other, and circular imports aren't allowed. That lookup is only for the types of model fields: a controller or script that uses User still imports models/user.kscript.

Pages stay where they are, because a page's path is its URL. Desktop windows (make window) go at the top, next to desktop.kscript. Move any folder with paths in kscript.json:

JSON
{
  "paths": { "controllers": "app/controllers", "styles": "assets/css", "views": "app/views" }
}

The names are routes, controllers, middleware, requests, views, components, layouts, partials, styles, lib, types, models, errors, storage, jobs, windows, locales, logging, data, scripts and tests. paths.views is also where @view() looks, unless http.views says otherwise. kscript serve finds routes/web.kscript and routes/api.kscript by itself; a route file anywhere else needs listing in http.routes. Paths are relative to the project folder. Pages look in paths.components, which defaults to _components/.

Names can be written any way (HeroBanner, hero-banner, hero_banner) and files are named in kebab case. Options: --dir <project> (default: the project's site root inside a project, otherwise the current folder), --force to replace an existing file, --dry-run to print the file instead of writing it. Every other --key value (or --key=value, or a bare --flag for true) is passed to the template.

Scripts and tests are written as .kscript files. --syntax xml writes .ks.xml instead, and "make": { "syntax": "xml" } in kscript.json makes that the project's default.

Your own templates. Templates live in the project's _templates/ folder, which kscript serve never serves. kscript make templates copies the built-in ones there to edit. A file there replaces the built-in template of the same name (_templates/component.kscript), and any other file adds a type: _templates/card.html gives kscript make card Profile.

HTML page
--- make
description: A card with an optional image
to: _components/{{ kebab }}-card.html
hint: Use it in a page: <{{ kebab }}-card />
---
<article class="card {{ variant ?? plain }}">
{{#if image}}
  <img src="{$image}" alt="">
{{/if}}
{{#each props}}
  <p>{${{ item | var }}}</p>
{{/each}}
  <slot />
</article>
  • The --- make header is optional: to is where the file goes (default: the name with the template's extension), hint is printed afterwards, description shows in kscript make. category, usage, example: lines (as many as you like) and --option: what it does lines fill in its entry in kscript make --list, and $defaults: actions=index gives options a default. $checks: tries=int; level=debug|info|warn refuses a value that would not work before anything is written: a list of choices, or int, number, status, duration, durations, fields, names, assignments, locale or file (a file in the project); name= checks the name itself. base: project makes to relative to the project folder (where kscript.json is) rather than the site root, as the test template does.
  • {{ name }} is the name as typed; {{ kebab }}, {{ snake }}, {{ pascal }}, {{ camel }} and {{ title }} are its other spellings; {{ dir }} is its folder (blog/ for blog/first-post), {{ path }} is folder and kebab name, {{ url }} its page URL, and {{ params }} lists [id] segments. {{ paths.controllers }} and the other paths are the project's folders, {{ up }} leads from the new file back to the project folder (../ for lib/x.kscript), and {{ ext }} is .kscript or .ks.xml.
  • {{ value | kebab }} applies a filter (kebab snake pascal camel title var lower upper trim quoted code; var turns sub-title into the sub_title a component sees, quoted writes the value as a string, in 'single quotes' unless it needs double ones, and code puts any "text" in code someone typed that fills nothing in into 'single quotes'), and {{ value ?? fallback }} gives a default.
  • {{#if value}} … {{else}} … {{/if}}, {{#unless value}}, {{#if value is text}}, {{#if value in a, b}}, {{#if list has text}}, and {{#each value}} … {{ item }} … {{/each}} over a comma-separated list ({{ index }}, {{ first }} and {{ last }} are set). A block tag on its own line leaves no blank line behind.
  • Single braces are left alone, so KScript's {$value} is written as is.