Skip to Content
defold-typescript
Get startedGuidesAPILibraries
Toolchain & workflow

Agent runbooks

Harness-neutral procedures for driving defold-typescript from an automated agent. defold-typescript is a CLI published to npm (run with bunx) plus a types package; it ships no harness-specific skill or command assets, so the durable interface for an agent is the CLI verbs themselves and their machine-readable --json output. Every runbook below works from any harness: run the command, read the JSON envelope on stdout, gate on ok.

Each one-shot command (init, build, resolve) prints a single JSON object when given --json. The envelope is always one of two shapes:

{ "command": "<verb>", "ok": true, "written": ["<path>", "..."] }
{ "command": "<verb>", "ok": false, "error": "<message>" }

The agent branches on ok: on true, read written for the paths the command created or updated, leaving out a file that already held the same bytes; on false, read error for the failure reason. Some verbs add fields to the success envelope (noted per runbook), but command, ok, and either written or error are always present.

Verbs that shell out keep the contract by capturing their children rather than interleaving them: under --json, upgrade pipes the output of both the delegated CLI and the package-manager install into the envelope, surfacing it in output when a child fails, so the whole of stdout stays a single parseable document.

Machine-readable output

Every command accepts --json. The one-shot commands (init, build, setup-debug, defold) print a single JSON object to stdout, terminated by a newline; watch streams newline-delimited JSON (one object per line):

bunx @defold-typescript/cli build --json
# {"command":"build","ok":true,"written":["src/main.ts.script", "src/util.lua", ...],"warnings":[]}

A failure flips ok to false and carries an error string instead of written. On build, warnings carries the sourceless-orphan lines, the scene-resource-mismatch lines, the unreachable-address lines and the cross-world-address lines (empty when there are none). Optional fields (defoldVersion, defoldChannel, apiSurface, materializedSurface, unreachableAddresses, crossWorldAddresses, editorCompile, editorRun, …) appear only when they apply.

unreachableAddresses is the structured half of the unreachable-address findings, so you never parse the English warnings line to learn which file and which fragment:

bunx @defold-typescript/cli build --json
# {"command":"build","ok":true,"written":[...],
#  "warnings":["src/main.ts: no `.go` or `.collection` in this project declares a component with the id \"nobody\", …"],
#  "unreachableAddresses":[{"file":"src/main.ts","fragment":"nobody","message":"no `.go` or `.collection` in this project declares …"}]}

Read the absent field together with warnings, never on its own. The field is omitted — not emitted as [] — both when the project has no unreachable addresses and when the check could not run at all. Only warnings separates the two: a suppressed check contributes a line beginning unreachable-address check did not run:, naming the holes in the component-id universe (an unparseable scene, or a dependency resolve has not materialized). Treating an absent unreachableAddresses as "no unreachable addresses" is wrong whenever that line is present.

crossWorldAddresses is the same for the cross-world-address findings — an address naming a proxy world at a slot that resolves in the caller's own world (see build):

bunx @defold-typescript/cli build --json
# {"command":"build","ok":true,"written":[...],
#  "warnings":["src/main.ts: this address names the world \"mylevel\", but `go.get_position` resolves it in …"],
#  "crossWorldAddresses":[{"file":"src/main.ts","address":"mylevel:/enemy","socket":"mylevel","message":"this address names the world \"mylevel\", …"}]}

It follows the identical absent-versus-empty contract: the field is omitted — never [] — both when nothing was found and when the check had nothing to run against, because the project's scenes host no script the walk could resolve. There is no suppression line for this check; its silence is per file, so an absent field means only that no finding survived that per-file honesty rule.

lualibRequiredBy lists the outputs whose Lua requires the TypeScript runtime helper bundle (lualib_bundle), sorted and project-relative: scripts, modules, companions, the timers runtime and bundled library modules. A project that avoids the bundle reads it instead of scanning its output folder:

bunx @defold-typescript/cli build --json
# {"command":"build","ok":true,"written":[],"warnings":[],"lualibRequiredBy":["src/util.lua"],...}

Unlike the address findings, it is always present on a successful build and is [] when nothing requires the bundle. It covers every output the build produced, including files this run left unchanged and so left out of written.

removed lists the runtime files the build deleted because nothing requires them any more, sorted and project-relative. It is always present on a successful build and is [] when the build deleted none.

watch is long-running, so --json streams newline-delimited JSON (NDJSON) — one object per line, one line per event. The full lifecycle reads start → build → rebuild* → sceneTypes* → resolve* → stop:

bunx @defold-typescript/cli watch --json
# {"command":"watch","event":"start","ok":true,"written":[]}
# {"command":"watch","event":"build","ok":true,"written":[...],"warnings":[]}
# {"command":"watch","event":"rebuild","ok":true,"written":[...],"changed":["src/main.ts"],"removed":[],"warnings":[]}
# {"command":"watch","event":"rebuild","ok":false,"error":"..."}
# {"command":"watch","event":"sceneTypes","ok":true,"written":[],"warnings":[]}
# {"command":"watch","event":"resolve","ok":true,"written":[]}
# {"command":"watch","event":"editorCompile","ok":true,"written":[],"editorCompile":{"outcome":"compiled","success":true,"issues":[]}}
# {"command":"watch","event":"stop","ok":true,"written":[]}

build, rebuild, and sceneTypes events carry warnings and the same optional unreachableAddresses and crossWorldAddresses arrays, under the identical absent-versus-empty rule, so a watching agent sees an address break on the edit that broke it — including a .go/.collection save that broke it, which emits sceneTypes alone and no rebuild. The first build event of a session is the exception, and so is the sceneTypes event that follows it: both run before or as part of the scene walk, so the check starts from the first rebuild or the first sceneTypes a scene save produces.

A resolve event is emitted whenever a game.project save or a Defold library fetch (a rewritten .internal/lib/dependencies.json) re-resolves the extension surface (re-materializing .defold-types/extensions/ from the declared [dependencies] URLs). An editorVersion event — editor, target, and targetSource (pin, detected, or default) — is emitted when an editor attached after startup runs a version other than the one the watch targets; it is diagnostic only and never changes the exit status. Under watch --editor-compile, each compile the editor answers emits an editorCompile event whose editorCompile object is exactly the one build --editor-compile reports; a failed compile sets ok: false and error, and never stops the watch. start arrives once, before the initial full build — the process is up and listening. stop arrives once on graceful shutdown. A failed startup (missing tsconfig.json, etc.) emits start then exits non-zero with no stop line; a rebuild that fails emits an ok: false line to stdout too, so a line-reader sees one uninterrupted stream — failures never split off to stderr. Read each line as it arrives and react per event. Without --json, stdout stays the human wrote N files: … output and rebuild errors stay on stderr.

resolve --json reports materializedSurface (the written directory, or null when nothing was materialized) and, per extension, the url, generated namespaces, typeSurface, scriptApiCount, provenance (defold, cache or download; see Cache location), whether it was assetOnly, sceneSources (how many shared scene files it unpacked), the resolvedVersion (commit:<sha> or files-sha256:<hex>), the resolvedFiles hash of the files a game can use, — when the project pins that url — the pinnedVersion and pinnedFiles, and the pinStatus (unpinned / match / drift), and the ref, the kind of URL it is (commit / tag / branch / release / unknown), where only commit is fixed and branch draws a warning. A separate libraries array reports a dependency that matched a vendored library — its url, source (the library's host/owner/repo), materialized modules, provenance (vendored), and verified. A match the downloaded archive confirms always gets an entry. A verified: false entry (with an empty modules) is a repo-name match the archive did not confirm, reported but never materialized; it appears only when the dependency is asset-only. An unconfirmed match on a dependency that ships its own .script_api has no libraries[] entry at all and stays typeSurface: "extension" with its own namespaces.

A "vendored-library" or "vendored-native" entry also carries libraryStatus, how its archive stands against the reviews in library data: { "status": "exact", "by": "commit" | "api" }, { "status": "generated" }, { "status": "unsupported", "closest": <commit> | null, "members": [...] }, { "status": "newer-cli", "folder": <version> } or { "status": "unrecorded" }. It is absent when the run read no library data. No status changes the exit code.

typeSurface is present on every extensions[] entry and names which type surface that dependency actually contributed:

typeSurfaceMeaningnamespaces
"shipped"the declarations it ships in types/ replaced every other surfaceits installed file stems
"extension"it emitted a @globalTable module per .script_api doc, or an ambient namespace for a doc that extends an engine namespaceits namespaces
"vendored-native"a curated native declaration replaced anything the archive shipsits curated namespace
"vendored-library"a confirmed corpus match supersedes the docs for the namespaces its library publishes; its types are in libraries[]the archive's other .script_api namespaces, usually []
"none"asset-only with no confirmed match — it contributes no types at all[]

An entry with namespaces: [] is normal for the latter two, not a failure — read typeSurface rather than inferring from an empty namespaces or from assetOnly (a superseded dependency is assetOnly: false and lists only the namespaces its library does not type, such as defsave_ext beside the defsave.defsave module). Every declared dependency keeps an entry, so a pin-drift check still sees it. Summing extensions[].namespaces and libraries[].modules therefore yields each module exactly once, except a namespace several dependencies share, which each of them lists (see sharedNamespaces below):

{
  "command": "resolve",
  "ok": true,
  "written": [],
  "materializedSurface": ".defold-types/extensions",
  "extensions": [
    {
      "url": "https://github.com/defold/extension-iap/archive/main.zip",
      "ref": "branch",
      "namespaces": ["iap"],
      "typeSurface": "extension",
      "scriptApiCount": 1,
      "provenance": "download",
      "assetOnly": false,
      "sceneSources": 0,
      "resolvedVersion": "commit:5c33c398…",
      "resolvedFiles": "e3b0c442…",
      "pinnedVersion": "commit:5c33c398…",
      "pinnedFiles": "e3b0c442…",
      "pinStatus": "match"
    },
    {
      "url": "https://github.com/paulomrpp/dicebag/archive/main.zip",
      "ref": "branch",
      "namespaces": [],
      "typeSurface": "vendored-library",
      "scriptApiCount": 0,
      "provenance": "download",
      "assetOnly": true,
      "sceneSources": 0,
      "resolvedVersion": "commit:9f1e0a27…",
      "resolvedFiles": "7d865e95…",
      "pinStatus": "unpinned",
      "libraryStatus": { "status": "exact", "by": "commit" }
    }
  ],
  "libraries": [
    {
      "url": "https://github.com/8bitskull/dicebag/archive/main.zip",
      "source": "8bitskull/dicebag",
      "modules": ["dicebag.dicebag"],
      "provenance": "vendored",
      "verified": true
    }
  ]
}

The pinnedVersion and pinnedFiles fields are only present when the project's defold-typescript.lock records a pin for that url. The versions can match while pinStatus is drift: that means the files changed under the same commit, which pinnedFiles and resolvedFiles show. See Resolve for what pinStatus drives.

When several dependencies declare one namespace, each of their extensions[] entries lists it, and a sharedNamespaces array names it once with the urls that declare it, in [dependencies] order: "sharedNamespaces": [{ "namespace": "firebase", "urls": ["…/extension-firebase/archive/main.zip", "…/extension-firebase-analytics/archive/main.zip"] }]. The key is absent when no namespace is shared. A notices array holds the library data notices, and is absent when there are none.

Offline knowledge pack

@defold-typescript/docs ships two generated, never-hand-edited files at node_modules/@defold-typescript/docs/:

  • llms.txt — a curated index (per llmstxt.org): one link per guide page and per API namespace.
  • llms-full.txt — the whole guide inlined plus a compact namespace.function(signature) index of the entire API surface.

llms-full.txt is self-contained: an agent in a consumer project that has only node_modules and the in-project source can read every mechanic and signature from this one file — no network, no monorepo checkout. The docs site serves the same pair at /llms.txt and /llms-full.txt. Both are regenerated from the guide and the typed API on every docs build and drift-gated, so they never go stale against the shipped types.

This pack documents this toolchain's TypeScript surface. Defold's own engine docs are a separate, Lua/C++-first set served at defold.com/llms-*.txt — reach for those (and cross-reference the types) via Reach upstream Lua docs and convert. Do not confuse the two llms-full.txt files: this one is the port; defold.com's is the engine.

Helper and codegen scripts (Bun, /scripts)

When a task needs a build tool, a codegen pass, or a one-off maintenance script, do not write it into src/1 and do not run it with node. Two rules keep such scripts off the game's Lua build path:

  • Location: put the script in a project-root /scripts folder. The Defold build selects source by tsconfig.include (default src/**/*.ts) and ignores exclude, so any .ts under src/** other than a test or a file in src/test/ is transpiled to Lua and shipped — /scripts is outside that include, and outside the Defold-pinned main tsconfig.json.
  • Runner and typing: run with bun scripts/foo.ts (never node); node:* builtins work under Bun and are typed by bun-types (a project upgraded from an earlier release may also list @types/bun). Add a scripts/tsconfig.json with "noEmit": true, "types": ["bun-types"], and "include": ["**/*.ts"] — no Defold pin. Script dependencies go in the root package.json devDependencies.

See the Helper scripts guide for the full rationale and a copy-pasteable config.

Write a test

A test is a bun:test file, never a helper script. To add one:

  1. Choose the place by what the test imports. Only bun:test and game code: next to the module it tests. Anything from Bun's runtime (node:*, Bun, console, process, a module outside the source roots): src/test/.
  2. Name the file <module>.test.ts (*_test.ts, *.spec.ts and *_spec.ts work too); build, watch and the editor plugin skip it.
  3. Type it. A test next to its module starts with /// <reference types="bun-types/test" />. A test in src/test/ needs no line: src/test/env.d.ts already types the folder.
  4. Check it. Run bunx tsc --noEmit, bunx tsc --noEmit -p src/test/tsconfig.json and bun test; all three exit 0. A node:fs, console, process or TS6059 error on a test next to its module means it belongs in src/test/.

Test with Bun covers both places, the src/test/ config and how to stub engine calls.

Surface the ratchet backlog

bun scripts/ratchet-backlog.ts <source> --data <dir> lists every library coverage floor in the library data under <dir> still sitting below its 1.0 target, one slot per line, for either fidelity-floor or authored-parity-floor. A line reads <source>.json: <key> <axis> <value> (target 1) — the floor source it came from, the artifact whose floor is short, which axis is short, and by how much. No output means that source is entirely at target.

A below-target floor is backlog, not a gate failure. Both floor gates assert coverage >= floor, so a floor parked under 1.0 keeps passing by construction — the ratchet only ever catches coverage that falls. That makes the remaining climb invisible to CI, which is exactly the gap this probe fills. Coverage dropping below its floor still reds the gate immediately, as before.

Run the probe as part of any planning pass that asks "what is left to do?". Because the gates stay green, an agent that consults only CI concludes there is nothing outstanding; the probe is the signal that says otherwise. Treat a printed line as work to schedule, and no output as that source being done.

Verify against the real API surface

This section governs every runbook below it. Before answering any "how do I…" question about a Defold symbol, confirm the symbol against the installed surface — that it exists, its namespace, and its exact signature. An agent's default instinct is wrong here: the Lua-first manuals at defold.com and the ts-defold (@ts-defold/types) lore baked into training both describe surfaces that diverge from this toolchain's. Never emit a signature from training, from ts-defold, or from a raw Lua doc without first checking it exists in the materialized .defold-types/ surface or the installed @defold-typescript/types package. When recollection and the on-disk surface disagree, the surface wins.

Where the truth lives (reachable-surface map)

In a consumer project an agent can read only these; everything else (the generation pipeline, fixtures, monorepo planning docs) is contributor-only and absent from an install:

LocationWhat it holdsWhen it exists
.defold-types/<surfaceId>@<toolchain>/*.d.tsthe pinned ambient engine surface (e.g. .defold-types/defold-1.12.4@0.27.0/)after build; gitignored but on disk
node_modules/@defold-typescript/types/generated/*.d.tsnamespace signatures (go, vmath, factory, …)always, once installed
node_modules/@defold-typescript/types/src/the three factories (lifecycle.ts) and the narrowing guards (message-guard.d.ts, message-dispatch.d.ts, window-event-guard.d.ts)always, once installed
node_modules/@defold-typescript/types/api-availability.jsonthe N-version availability matrix — which symbols exist in which tracked versions (the Combined ## API in llms-full.txt filters against it; api-signatures.json alongside holds the matching authoritative declarations)always, once installed
node_modules/@defold-typescript/docs/guide/*.mdthis guide, refreshed on every installalways, once installed
packages/types/generated, packages/types/fixtures, packages/types/scriptsgenerator inputs and outputs — contributor-onlyonly in a clone of this monorepo

The pointers the init-agents managed block writes are the layered pack: node_modules/@defold-typescript/docs/llms.txt (the map) and node_modules/@defold-typescript/docs/llms-full.txt (the grep corpus), with the individual guide/<page>.md pages and the typed API in @defold-typescript/types/generated/*.d.ts alongside them.

The website's own routes carry a version range, not one surface: the unprefixed /api/<namespace> is the full range across every tracked release, /api/<version>/<namespace> is the range ending at that version, and /api/<version>/<namespace>?since=<version> states both bounds explicitly — for example go from 1.12.4 through 1.13.0. A browser fills a missing ?since= from the reader's last From choice, so write it out whenever the lower bound matters. That range is a reader's view, never an artifact dimension: llms.txt, llms-full.txt and the search and symbol indexes are always built full-range. So whatever a human has selected in the dropdowns, read a symbol's availability from the Availability tags in llms-full.txt or from api-availability.json, never from how narrow a page looked.

Confirm a signature

Read the signature from the namespace declaration instead of recalling it. Grep the generated .d.ts for the function:

grep -rn "function create" node_modules/@defold-typescript/types/generated/

Quote what the surface declares as authoritative — for factory.create it is factory.create(url, position?, rotation?, properties?, scale?): Hash | undefined. If the grep returns nothing, the symbol does not exist on this surface; do not invent it.

Reach upstream Lua docs and convert

Defold's own manuals and API reference are Lua-first. When the mechanic you need is only documented there, run the conversion loop: locate the mechanic in the Lua docs -> find its namespace in the generated .d.ts -> confirm the signature as above -> translate the idioms to the TypeScript surface.

Defold serves its whole documentation set as agent-ready text — reach for these to locate the mechanic, never to copy a call signature:

  • https://defold.com/llms-full.txt — manuals, API reference, and examples combined.
  • https://defold.com/llms-apis.txt — the C++/Lua/extension API reference alone.
  • https://defold.com/llms-manuals.txt — the conceptual manuals alone.
  • https://defold.com/llms-examples.txt — worked examples alone.

These describe the engine's Lua and C++ surface, not this toolchain's TypeScript one: argument order, optionality, and even whether a symbol exists can differ, so treat them as a concept-and-mechanic reference only. Once you know what to call, switch to the generated .d.ts (Confirm a signature) for the actual TypeScript signature you author against; when the two disagree, the .d.ts wins. A namespace in the Lua docs can be absent from TypeScript because it is not a scriptable runtime module at all — Defold has no input namespace, for example; input arrives through the on_input hook, not a polling API.

Lua idiomTypeScript surface
function init(self) … enddefineScript({ init() { … } })
obj:method(a)obj.method(a) (method form)
local x, y = f() (multi-return)const [x, y] = f() / LuaMultiReturn
hash("player")hash("player"), or a pre-hashed Hash id
msg.post("#comp", "msg", {})msg.post("#comp", "msg", {})

The first row carries a requirement the table cannot show: the lifecycle factory must be a value import from @defold-typescript/types, or from the matching @defold-typescript/types/script, /gui-script, or /render-script subpath. The rule is the same for defineScript, defineGuiScript, and defineRenderScript — erasure resolves the callee back to the types package, so a name that merely reads correctly is not enough. See Script lifecycle for the hook model itself.

import { defineScript } from "@defold-typescript/types";
import type { Hash } from "@defold-typescript/types";

The form to avoid re-declares the factory locally. It type-checks, build reports ok: true, and the lifecycle hooks are never erased:

import type { defineScript as defineScriptType } from "@defold-typescript/types";

declare const defineScript: typeof defineScriptType;

The tell is in the emitted artifact, not in the build report: if the .ts.script contains ____exports.default = defineScript(, erasure declined. A correct build has top-level function init( and function update( and no defineScript symbol at all. Recovery is in Fix the Lua output.

Fetch upstream on demand (gitignored, not a submodule)

When you need the engine's own API data or source, pull it on demand into a gitignored path — do not add a defold/defold git submodule. A submodule is a multi-GB tree pinned to one engine SHA that every clone then carries; the API data you actually need is the few-hundred-KB ref-doc.zip the type generator already consumes, cached at ~/.cache/defold-typescript/ref-doc/<version>/ (DEFOLD_TYPESCRIPT_CACHE overrides the cache root). Read the cached ref-doc.zip there, or for the rare source-reading case shallow-clone defold/defold into a gitignored dir. This is a cached download, not a submodule — the on-demand fetch keeps the repo small.

The verification loop

Once converted, prove it compiles before handing it back: write the snippet, run build --json, and on ok: false read the error span, fix the source, and rebuild. This is the same loop as Fix the Lua output; the script lifecycle page covers which hooks and which self typing each script kind exposes. On ok: true the build envelope adds a warnings array. It lists four kinds of issue, empty when clean, and the build never fixes any of them for you:

  • Sourceless outputs — a generated .lua/.ts.* left without a TypeScript source (a deleted or renamed source), each naming the stale file and the source to restore.
  • Scene-resource mismatches — a .go/.collection whose component: points at a mesh source asset (.gltf/.glb/.dae) instead of a .model component. Bob builds this silently, but the game object fails at runtime, so the CLI surfaces at build time what only the editor would otherwise catch. Wrap the mesh in a .model (with a materials block) and point the component at the .model.
  • Unreachable addresses — an address literal whose #fragment names a component no .go/.collection declares, repeated as structured entries in unreachableAddresses. Either declare the component or fix the address.
  • Cross-world addresses — an address naming a proxy world at a slot that resolves in the caller's own world (every handle-resolving go.* call), repeated as structured entries in crossWorldAddresses. Either address it through msg.post/msg.url or drop the socket.

Scaffold a project

Goal: create a new TypeScript surface — either a fresh project, or the TypeScript layer added to an existing Defold project.

Command (fresh project, new folder):

bunx @defold-typescript/cli@latest init path/to/project --json

Command (existing Defold project — run inside the folder that holds game.project):

bunx @defold-typescript/cli@latest init . --json

init requires an explicit destination folder — pass a path to create it, or . for the current folder. There is no implicit current-folder default, so an invocation with no path fails fast (ok: false) rather than scaffolding into the working directory by accident. init then detects whether a game.project is already present at the destination and either scaffolds a whole new project or adds the TypeScript surface alongside the existing one.

Returns:

{
  "command": "init",
  "ok": true,
  "written": ["tsconfig.json", "src/main.ts", "..."],
  "operations": [
    { "target": "tsconfig.json", "status": "merged" },
    { "target": "src/main.ts", "status": "skipped", "detail": "existing project sources present" }
  ]
}

On failure:

{ "command": "init", "ok": false, "error": "<message>" }

Reading ok: if ok is true, the scaffold succeeded and written lists every file created or modified — use it to know what to open next. If ok is false, stop and surface error; nothing was scaffolded.

Reading operations: each entry pairs a target with a status of written (freshly created), merged (an existing tsconfig.json was preserved and refreshed in place), or skipped (left untouched, with a detail reason — e.g. your own src/main.ts or engine sources already present). Branch on status when you need to distinguish a merge from a clobber.

Install the agent contract

Goal: drop an agent contract at the project root so any harness (or human) opening the repo finds the conventions and a pointer to the installed guide.

Tip

A fresh init already wrote this contract — its scaffold creates AGENTS.md + CLAUDE.md for you — and upgrade refreshes the managed block, as does init . --force. Run the standalone init-agents verb below when the project has no contract, or to restore a block that was edited or deleted.

Command:

bunx @defold-typescript/cli@latest init-agents . --json

Like init, init-agents requires an explicit destination — pass a path or . for the current folder; a missing path fails fast (ok: false). It writes up to two files — a run that finds both already current writes neither, and reports an empty written. AGENTS.md carries a managed block delimited by HTML comment markers; a fresh CLAUDE.md is the single line @AGENTS.md, re-exporting it. Only the content between the markers is ever rewritten, so any notes you add above or below the block survive re-runs untouched. If AGENTS.md already exists without the markers, the block is appended after one blank line and your prior content is left intact; a CLAUDE.md that already equals @AGENTS.md is left byte-for-byte unchanged. The block is versionless — its pointers resolve to node_modules/@defold-typescript/docs/llms.txt and llms-full.txt, which the install swaps under the same paths — so the verb is safe to re-run any time.

Returns:

{ "command": "init-agents", "ok": true, "written": ["AGENTS.md", "CLAUDE.md"] }

On failure:

{ "command": "init-agents", "ok": false, "error": "<message>" }

Reading ok: if ok is true, written lists the files touched in order — [] when the contract was already current, since a write that would reproduce a file byte-for-byte is skipped. If ok is false, stop and surface error, and do not assume the project is untouched: the files are written one after another, so a failure on the second leaves the first on disk.

Upgrade the toolchain

Goal: move the project to the latest @defold-typescript toolchain — the latest CLI, the managed files re-scaffolded from its templates, and the managed dependencies re-pinned and reinstalled.

Command (run from the project root):

bunx @defold-typescript/cli@latest upgrade --json

update is a synonym for upgrade; both spellings run the same verb, so either is safe to emit. There is no separate "check for updates" verb — the run resolves the latest version itself and re-scaffolds in place when it is already current.

The verb replaces the older two-command recipe (init . --force followed by an install). Do not spell that recipe out: the verb decides whether the running CLI is new enough to re-scaffold, and hands off to the newer one when it is not.

Returns:

{
  "command": "upgrade",
  "ok": true,
  "written": ["package.json", "tsconfig.json", "..."],
  "warnings": [],
  "from": "0.4.1",
  "to": "0.5.0",
  "handedOff": true
}

On failure:

{ "command": "upgrade", "ok": false, "error": "<message>" }

Reading ok: if ok is true, the upgrade landed — written lists the managed files the re-scaffold touched, from is the @defold-typescript/cli version the project had before the upgrade (the installed copy in node_modules, else the version in its package.json pin, and absent when neither exists), to is the resolved latest, and handedOff says whether a newer CLI performed the re-scaffold (false means the running CLI was already the latest and re-scaffolded in place). If ok is false, stop and surface error.

When handedOff is true, written is the list the newer CLI reports for the re-scaffold it performed, read back from the delegated run; when it is false, the list is the running CLI's own.

Inspect warnings even when ok is true. An unknown normalized checksum for .vscode/defold-debug.ts means the upgrade succeeded but preserved that file's existing bytes because it may be customized; the path is absent from written. Delete it and run defold-typescript setup-debug only when replacing it is the intended action.

The test layout adds more warnings, each a plain sentence ending in node_modules/@defold-typescript/docs/guide/testing.md, the same in the terminal and under --json, including through the hand-off:

  • A line starting src/test/tsconfig.json: names the settings the upgrade added to an existing test config, the values it kept that differ from the scaffold's, the include and exclude it replaced (before and after), or that the config does not extend the root and was left alone. Read it; the edits are already made.
  • A line starting tsconfig.json: says src/test was added to the root exclude.
  • A line starting Bun names an installed Bun older than the CLI's bun-types pin, or an exact project pin that differs from the installed Bun. Report it to the user; never change the pin or run bun upgrade on your own.
  • A line starting test/ or tests/ names a root test folder holding Bun tests. Moving those tests is the user's call.

The offline failure mode: upgrading is the one command that needs the network. When the npm registry is unreachable the run fails — ok is false with a non-zero exit — instead of re-scaffolding against the version already on disk. Read the failure; never treat it as a silent no-op that succeeded.

What it never touches: your own scripts. An entry file you authored (src/main.ts) is reported as skipped, not overwritten. See Upgrading the toolchain for what the re-scaffold refreshes and what it does to an existing defold-target pin.

Regenerate extension types

Goal: refresh the TypeScript surface for native extensions after a game.project [dependencies] change, so extension namespaces stay in sync with the declared archives. This automates the workflow described in Typing native extensions.

Command (run from the project root, after editing [dependencies]):

bunx @defold-typescript/cli resolve --json

resolve reads each declared extension's .script_api, regenerates the gitignored .defold-types/extensions/ surface — a @globalTable module per namespace, which scripts import as import * as iap from "iap" — and rewrites its index and package.json to exactly the declared set.

Returns the same one-shot envelope keyed command: "resolve", plus an extensions array reporting provenance for each resolved dependency:

{
  "command": "resolve",
  "ok": true,
  "written": [],
  "materializedSurface": ".defold-types/extensions",
  "extensions": [
    {
      "url": "<archive url>",
      "ref": "<commit | tag | branch | release | unknown>",
      "provenance": "<defold | cache | download>",
      "namespaces": ["<namespace>"],
      "typeSurface": "<none | extension | vendored-library | vendored-native | shipped>",
      "scriptApiCount": 1,
      "assetOnly": false,
      "sceneSources": 0,
      "resolvedVersion": "<version>",
      "resolvedFiles": "<hex>",
      "pinStatus": "<unpinned | match | drift>"
    }
  ]
}

On failure:

{ "command": "resolve", "ok": false, "error": "<message>" }

Reading ok: if ok is true, the extension surface is current — materializedSurface is the regenerated surface directory (.defold-types/extensions), and extensions records where each dependency came from (provenance), which type surface it contributed (typeSurface), how many .script_api files the archive carries (scriptApiCount — a "vendored-library" entry counts the docs its library replaced, so it can exceed its namespaces), how many scene sources it shared (sceneSources), what kind of URL it is (ref), and its pin state (resolvedVersion/resolvedFiles/pinStatus). Pins live in the committed defold-typescript.lock, which resolve writes, so commit it with the change. The written array is always empty for resolve. If ok is false, surface error; the existing surface is left untouched.

Add a script

Goal: add a new gameplay script to a TypeScript Defold project and attach it so it runs. There is no add verb — the workflow composes ordinary file creation with the shipped build verb, then a scene-file edit to wire the compiled component.

1. Write the source. One Defold script per file under src/, exporting a single lifecycle factory as default (never two in one file). The factory decides the compiled kind:

Source factoryCompiled artifactReferenced by
defineScript<name>.ts.scripta game object (.go / .collection) as a component
defineGuiScript<name>.ts.gui_scripta GUI scene (.gui), as its Script property
defineRenderScript<name>.ts.render_scriptthe render pipeline (a .render file, set via game.project)

A source that calls no factory emits a plain <name>.lua module to import instead. Which hooks to export (init, update, fixed_update, on_message, on_input, final, …) and how self is typed are covered in Script lifecycle.

2. Build (from the project root):

bunx @defold-typescript/cli build --json

Or, if a watch --json is already running, just save the file and read its rebuild event instead of invoking build.

Returns the one-shot envelope keyed command: "build", plus the build context fields:

{
  "command": "build",
  "ok": true,
  "written": ["src/<name>.ts.script", "..."],
  "defoldVersion": "<version>",
  "defoldChannel": "<stable | beta | alpha>",
  "apiSurface": "<surface id>",
  "materializedSurface": "<path | null>"
}

On failure:

{ "command": "build", "ok": false, "error": "<message>" }

Reading ok: if ok is true, the script transpiled — written lists the emitted artifact (.ts.script, .ts.gui_script, or .ts.render_script) to attach next; defoldVersion and apiSurface record which API surface it was built against; defoldChannel and defoldSha record the resolved release channel and head sha (both null for a fixed-version target, set when a channel target like beta is pinned or passed via --defold-target). If ok is false, the build failed — surface error and follow Fix the Lua output.

What build writes. Each .ts source under src/ produces exactly one output in the Defold project tree — a script component or a <name>.lua module, per the table above. import is rewritten to require("<module>") resolving against the emitted .lua, so a shared module must be built for its require to resolve at runtime. The build's own runtime modules are synthesized on demand in the runtime folder (lib/defold_typescript/ by default, moved by package.json runtime-dir): lualib_bundle.lua (when a source uses a TS runtime helper like Object.keys or spread, or when timers or hsm/async are used, since those require it), timers.lua (when timers are used), hsm/<module>.lua (per imported hsm module) and ecs/index.lua (when @defold-typescript/types/ecs is imported for values). A build with no errors deletes the ones nothing needs any more and lists them in removed.

Who creates these: TypeScriptToLua (TSTL) produces the Lua content in memory; the CLI writes the files, choosing the .ts.script / .ts.gui_script / .ts.render_script / .lua name and location. TSTL never touches disk — that is why the outputs carry Defold-correct extensions instead of plain .lua. Treat the --json written array as the authoritative list of what landed; do not infer paths.

3. Attach the compiled script. Building only produces the artifact; nothing runs until a scene references it as a component. Scene files (.go, .collection, .gui, .render) reference the compiled artifact, never the .ts source. A game object references a .ts.script through a components { … } entry naming its project-root-absolute path:

components {
  id: "player"
  component: "/src/player.ts.script"
}

In a standalone .go the block appears verbatim. When the game object is embedded in a .collection, Defold stores the same block as an escaped string inside an embedded_instances { data: "…" } entry — the form to write when editing the file directly. The platformer example shows this in game/player.collection:

embedded_instances {
  id: "player"
  data: "components {\n"
  "  id: \"player\"\n"
  "  component: \"/src/player.ts.script\"\n"
  ...
  "}\n"
  ...
}

A .ts.gui_script is referenced by a .gui scene's Script property and a .ts.render_script by the render pipeline, the same compiled-artifact rule.

4. Verify the attachment. Two checks confirm the script is wired in:

  • Grep the scene files for the compiled name:

    grep -rl "player.ts.script" --include="*.go" --include="*.collection" --include="*.gui" .

    A hit means a scene references it; no hit means it is orphaned and will not run.

  • Defold compiles only reachable resources, so after a Defold build (the CLI's defold build subcommand) an attached script produces build/default/src/player.ts.scriptc — the path mirrors the source — while an orphaned script never appears under build/default/ at all. (The _generated_* artifacts there are inlined or asset-derived resources — embedded game objects, components, textures — never referenced script files, which keep their source path.)

Narrow engine callback payloads

Goal: type an engine callback's untyped payload without hand-rolling typeof/in/as.

Rule for clankers: when an engine callback hands back an untyped or unknown payload that is discriminated by a separate id/event argument, reach for the provided declaration-only guard before reaching for typeof/in/as. TypeScript cannot correlate two independent parameters, and Defold's ids/event constants are pre-hashed Hash values or branded numbers — neither works as a discriminated-union tag. Each guard below re-introduces the discriminant at the use site. They are all declaration-only: the transpiler lowers each call to its runtime comparison, so there is no runtime Lua symbol and no import to add.

on_message — narrow one message with isMessage, or route many with onMessage:

export default defineScript({
  on_message(self, message_id, message) {
    if (isMessage(message_id, message, "contact_point_response")) {
      // message narrowed to the contact_point_response payload — no cast.
      print(message.distance);
    }
  },
});

window.set_listener — narrow the callback's data with isWindowEvent:

window.set_listener((self, event, data) => {
  if (isWindowEvent(event, data, window.WINDOW_EVENT_RESIZED)) {
    // data narrowed to { width: number; height: number } — no cast.
    print(data.width, data.height);
  }
});

An unknown id/event constant is a compile error, so the guard also catches typos. The full narrowing reference, including onMessage's multi-message dispatcher, lives in Typed messages and the window.set_listener gotcha.

Fix the Lua output

Goal: recover from a transpile failure reported by build or watch.

Command (re-run after each source fix):

bunx @defold-typescript/cli build --json

On a transpile failure the one-shot build --json envelope carries the message:

{ "command": "build", "ok": false, "error": "<message>" }

Under a long-lived watch --json, the same failure arrives as an NDJSON event on stdout (one JSON object per line) keyed command: "watch":

{ "command": "watch", "event": "rebuild", "ok": false, "error": "<message>" }

The first build emits event: "build"; each later rebuild emits event: "rebuild". build and the transpile-diagnostics pass share one diagnostic run, so the error names the offending source span.

Reading ok: while ok is false, read error for the failing span, then fix the source and rebuild. Two pages route the fix: TypeScript gotchas for the runtime-semantics traps that compile clean but surprise under Lua, and Transpile diagnostics for what the diagnostic pass surfaces. Repeat until ok is true, then read written as in Add a script.

The failure ok cannot report: build answers ok: true and Defold still rejects the resources, as a cascade in the engine log:

WARNING:RESOURCE: Unable to create resource: /game/player.ts.scriptc: FORMAT_ERROR
WARNING:RESOURCE: Unable to create resource: /_generated_*.goc: FORMAT_ERROR
WARNING:RESOURCE: Unable to create resource: /game/game.collectionc: FORMAT_ERROR

The emitted script is not a Defold script. Read the first line, not the last: the cascade names the .goc and .collectionc that reference the script, not the .ts source. Check the artifact for ____exports.default = defineScript(, then recover in order: fix the import as in Reach upstream Lua docs and convert, re-run bunx @defold-typescript/cli build --json, and clear the Defold project's build/ output if stale compiled resources keep failing.

Compile in the editor after a build

Goal: learn whether the Defold side of the project is broken — a bad .collection, a missing resource, a Lua error in the generated code — without running the game. This is the edit, build, compile loop.

Command (run from the project root, with the Defold editor open on it):

bunx @defold-typescript/cli build --editor-compile --json

Once every output file is written, build asks the attached Defold 1.13.2+ editor to compile the project and waits for its answer; there is no time limit. The result gains an editorCompile object:

{"command":"build","ok":false,"error":"the Defold editor failed to compile the project with 1 issue","editorCompile":{"outcome":"compiled","success":false,"issues":[{"message":"attempt to call a nil value","severity":"error","resource":"/src/main.ts.script","range":{"start":{"line":3,"character":4},"end":{"line":3,"character":17}},"source":{"file":"src/main.ts","line":5,"column":11}}]}}

Branch on editorCompile.outcome:

  • "compiled" with success: false — the build exits 1 with ok: false. Each issue carries the editor's message, severity, and, when sent, resource and a zero-based range. source is the authored TypeScript location, present only when the build's source map resolved it; an issue in a .collection or the lualib bundle has none. Fix the issues and rerun.
  • "compiled" with success: true — the project compiled. issues may still hold warnings; the build stays ok.
  • "compiled" with no success — the editor answered but its body could not be read. Nothing was proven; the build stays ok.
  • "unsupported" — the editor is older than Defold 1.13.2 and has no compile command. Upgrade the editor.
  • "skipped" — the editor refused the request.
  • "unavailable" — no editor is open on the project. Open it and rerun.

Only success: false fails the build, so the flag is safe in a script that also runs where no editor is open. Without the flag nothing is posted and the result has no editorCompile key.

To keep this check running while you edit, use watch --editor-compile --json instead: it emits the same object on an editorCompile event after every rebuild and every project file change.

Run the game in the editor after a build

Goal: start the game on the code just written and learn where it is running. This is the edit, build, run loop.

Command (run from the project root, with the Defold editor open on it):

bunx @defold-typescript/cli build --editor-run --json

Once every output file is written, build asks the attached Defold 1.13.2+ editor to build and launch the game, and waits until the engine reports its address. The result gains an editorRun object:

{"command":"build","ok":true,"written":["src/main.ts.script"],"editorRun":{"outcome":"ran","success":true,"issues":[],"targetUrl":"http://127.0.0.1:57069"}}

editorRun reads like editorCompile, with "ran" in place of "compiled", plus:

  • targetUrl — the running engine's address, present only when the run succeeded and the engine reported it. A successful run without it means the engine quit or did not answer in time; read the warning in issues.

The game window opens behind other windows; add --editor-focus to bring it to the front. With --editor-compile as well, only the run is posted and the result has no editorCompile key. Without --editor-run nothing is posted and the result has no editorRun key. To get later edits into the running game, switch to hot reload.

Hot reload the running game

Goal: get an edit into the already running game and find out whether an error surfaced on the editor console while the command watched, without opening the editor and without holding a foreground watcher. This is the fast inner loop for an agent: change a .ts, rebuild, reload, read the result, decide.

Commands (run from the project root):

bunx @defold-typescript/cli build --json
bunx @defold-typescript/cli reload --json

Chain them with &&: build exits non-zero on a compile error, so a failed build never reloads and the game stays on the last code that actually built.

reload posts one reload and then reads the editor console for a bounded window (--wait <ms>, default 2000). An editor before Defold 1.13.2 answers the post with HTTP 202 — queued — and nothing more; 1.13.2 and later answer once the reload has finished, with a verdict reload reports as editorIssues. Neither answer covers a Lua error the reloaded code raises once it runs, which reaches only the console. Its single JSON line is:

{"command":"reload","ok":false,"error":"the reloaded code reported an error","outcome":"accepted","consoleErrors":["ERROR:SCRIPT: /src/main.ts.script:4: attempt to index a nil value"],"consoleErrorLocations":[{"chunk":"/src/main.ts.script","chunkLine":4,"file":"src/main.ts","line":5,"column":11}],"consoleObserved":true,"consoleWindowComplete":true}

consoleErrors is always the console's own text, naming the generated chunk. consoleErrorLocations is the best-effort translation back to the authored TypeScript, one entry per reference the build's source map resolved — read it when present, and fall back to consoleErrors when it is [], which is what a chunk with no map, an uncovered generated line, an unparseable map, or a map resolving to something that is not a file in the project produces. Never assume it is populated. Every file it does carry is a project-relative path naming a file in the project, under any outDir.

Branch on outcome first, then editorIssues, then consoleObserved, then ok. editorIssues is present only against Defold 1.13.2 or later: [] when the editor accepted the reload, and absent against an older editor.

  • outcome: "unavailable" — no editor is running, or it never answered within the attach deadline. Nothing was posted; start the editor and the game before retrying.
  • outcome: "skipped" — the editor is running but declined: usually no game is running, or nothing was dirty. Press Build in the editor once to get a game under it.
  • outcome: "accepted" with ok: false and a non-empty editorIssues — the editor rejected the reload, and the console was not read. Each issue carries message, severity, and, when the editor sent them, resource (a project path such as /src/main.ts.script) and range (zero-based line and character). Fix the issues and rebuild.
  • outcome: "accepted" with consoleObserved: false and ok: false — the post was accepted but the console never opened, so nothing was watched. Retry, or pass --wait 0 to accept that trade deliberately.
  • outcome: "accepted" with consoleObserved: false and ok: true — --wait 0: no console was read at all, so the post being accepted is the whole claim.
  • outcome: "accepted" with consoleObserved: true and ok: true — the post was accepted, the whole console window was read (consoleWindowComplete: true), and nothing appeared on it.
  • outcome: "accepted" with ok: false, consoleObserved: true and a non-empty consoleErrors — the post was accepted and the new code threw. consoleErrors carries the header and its traceback frames in order; that is your stack trace.
  • outcome: "accepted" with ok: false, consoleObserved: true, consoleWindowComplete: false and an empty consoleErrors — the console closed or failed before the window ended, so errors raised later were not seen. Retry the reload rather than reading it as quiet.

ok: true is not proof the reload succeeded. The window is a heuristic: an error thrown after it closes, or on a frame the game has not reached, is missed. Widen --wait for a reload that does real work before it can fail. Two failure classes never reach the console at all — Defold's own build errors (a bad component reference, a missing atlas, a Lua syntax error) go to the editor's Build Errors tab. Against Defold 1.13.2 or later, build --editor-compile reports them before you reload.

When reload reports no error but the game behaves as before, check on_reload rather than the reload: hot reload runs the new code against the old state and does not re-run init, so state seeded in init keeps its old values. See Script lifecycle.

For a person editing files rather than an agent driving one change at a time, watch --hot-reload does this continuously instead.

Drive the engine build

Goal: once the TypeScript surface transpiles clean, run the actual Defold engine build headlessly — resolve native dependencies, compile the project, or produce a platform bundle — without opening the editor. This is the autonomous phase after the type and transpile loop: the .ts sources are already emitted as Defold artifacts, and now bob (the engine's command-line builder) turns the project tree into engine output.

Commands (run from the project root):

bunx @defold-typescript/cli bob status --json    # dry-run: report the resolved target/jar/Java
bunx @defold-typescript/cli bob resolve --json   # fetch native extension deps
bunx @defold-typescript/cli bob build --json     # compile to build/default
bunx @defold-typescript/cli bob bundle --json     # produce a platform bundle
bunx @defold-typescript/cli bob run --json       # debug build, then launch the game

Each bob <sub> verb shells out to bob and, under --json, keeps stdout to exactly one JSON object — bob's own chatter is captured, not streamed, so a line-reader can JSON.parse stdout deterministically. The envelope is:

{ "command": "bob", "subcommand": "build", "ok": true, "exitCode": 0, "defoldVersion": "1.12.4", "defoldChannel": null, "defoldSha": "402218d…", "output": "<bob tail>" }

On a non-zero bob exit:

{ "command": "bob", "subcommand": "build", "ok": false, "exitCode": 17, "error": "bob build exited with code 17", "defoldVersion": "1.12.4", "defoldChannel": null, "defoldSha": "402218d…", "output": "<bob tail>" }

output is a trimmed tail of bob's combined stdout/stderr, present for diagnostics on both outcomes. Without --json, bob's output streams live to the terminal instead and no JSON is written.

Target-driven artifact: bob downloads the bob.jar that matches the resolved --defold-target, not a fixed stable head — a pinned version resolves to that version's artifact SHA, a channel (stable/beta/alpha) resolves to the channel head by SHA. Under --json the envelope reports the resolved defoldVersion, defoldChannel (null for a pinned version), and defoldSha, so a caller can confirm exactly which engine build bob ran against.

Reading ok / exitCode: branch on ok first — true means bob succeeded and the CLI's exit code is 0. On ok: false, the CLI exit code is bob's own exitCode (not a flat 1), so a caller can distinguish bob failures by code; read output for the tail of what bob printed and error for the summary.

Pre-flight with bob status: bob status is a read-only dry-run — it resolves the --defold-target and reports the selected version/channel/SHA, the sha-keyed bob.jar path and whether it is cached, and the resolved Java runtime, without downloading the jar or running bob. It is fully offline for a pinned version and touches the network only to resolve a moving channel's head; an offline channel resolution exits non-zero with an actionable error. A missing Java runtime is reported (java: null), not fatal. Use it to confirm preconditions before a resolve/build:

{ "command": "bob", "subcommand": "status", "ok": true, "defoldVersion": "1.12.4", "defoldChannel": null, "defoldSha": "402218d…", "bobJar": { "path": "~/.cache/defold-typescript/bob/402218d…/bob.jar", "cached": true }, "java": "java" }

Preconditions — now satisfied autonomously: two setup steps that used to require a human are handled for you. bob needs a Java runtime, and bob resolves one in order (--java/DEFOLD_JAVA override → java on PATH → the installed editor's bundled JDK), so a machine with only the Defold editor installed builds with no separate JDK. bob itself (bob.jar) is auto-downloaded to the cache on first use and reused thereafter. The one precondition still required is network egress: the first bob resolve/build fetches bob.jar and any native extension archives, so an air-gapped run fails until the cache is warmed.

Composite build+launch with bob run: bob run is the one convenience verb that combines steps — Bob has no native run, so the CLI composes it: download the target-matched bob.jar, debug-build into build/default, ensure a target-matched engine (the native-extension build/<platform>/dmengine when the build produced one, else the stock engine fetched by the resolved SHA into a sibling engine cache next to the jar cache and recorded so a later run reuses it), then launch. bob, the typings, and the running engine all share the one resolved SHA. --java/--build-server thread into the build as for bob build; a cache hit skips the engine download; an offline download reports an actionable error. A failed build short-circuits with Bob's exit code and never launches — the CLI exit code is that build code. Because a live game cannot be captured, its output streams to the terminal even under --json; the composite envelope prints on exit:

{ "command": "bob", "subcommand": "run", "ok": true, "build": { "exitCode": 0 }, "launch": { "enginePath": "build/arm64-osx/dmengine", "exitCode": 0 } }

Launch an existing build with run: once build/default holds a compiled project, the top-level run command launches it directly — no transpile, no Bob, no engine download, no Java. It reuses the native-extension build engine (build/<platform>/dmengine) when present, otherwise the stock engine a prior bob run cached; when neither the compiled project nor an engine is found it errors and names the bob build / bob run that would produce them.

bunx @defold-typescript/cli run --json           # launch build/default
bunx @defold-typescript/cli run -- --windowed    # engine args pass through after --

The engine's exit code becomes the command's exit code, and Ctrl-C (SIGINT/SIGTERM) forwards to the engine for a clean shutdown. Unlike bob, run streams the game live even under --json — a running game is not capturable — and prints one envelope on exit:

{ "command": "run", "ok": true, "enginePath": "build/arm64-osx/dmengine", "projectc": "build/default/game.projectc", "exitCode": 0 }

On a missing build or engine, run --json emits { "command": "run", "ok": false, "error": "…" } and exits 1.

Combine components on a game object

Goal: put several components — scripts, a sprite, a collision object — on one game object and let them cooperate.

One .go (or an embedded_instances block inside a .collection) lists each component under its own id. A script reaches a sibling component on the same object by that #-prefixed id — no path is needed because they share the object. The platformer's game/player.collection embeds the player script next to its sprite and collision object exactly this way; the Add a script runbook shows the embedded_instances form to write when editing the scene file directly.

import { defineScript } from "@defold-typescript/types";

export default defineScript({
  on_input(self, action_id) {
    if (action_id == hash("jump")) {
      // "#" addresses a sibling component on this same game object.
      msg.post("#animator", "play_animation", { id: hash("jump") });
    }
  },
});

Confirm each id names a real component and the snippet builds — see Verify against the real API surface.

Spawn objects with a factory

Goal: create new game objects at runtime from a prototype.

Add a .factory component to a game object and point it at the prototype .go. At runtime, factory.create(url, position?, rotation?, properties?, scale?) returns the spawned object's id as a Hash, or undefined when the spawn fails, so narrow it before use. The fourth argument, properties, seeds the new script's self before its init runs, so each spawned instance can start with its own state.

import { defineScript } from "@defold-typescript/types";

export default defineScript({
  init() {
    // properties (4th arg) seed the spawned script's self before its init runs.
    const enemy = factory.create("#enemyfactory", undefined, undefined, {
      health: 100,
    });
    return { lastSpawned: enemy };
  },
});

To check the table against the spawned script's declared properties, name its shape in the curried form; an undeclared name or a wrongly typed value is then a type error (Check the properties a factory spawns with):

const enemy = factory.create<EnemyProps>()("#enemyfactory", undefined, undefined, { health: 100 });

Confirm factory.create against node_modules/@defold-typescript/types/generated/factory.d.ts, and the curried form against node_modules/@defold-typescript/types/src/factory-overloads.d.ts, and build the snippet — see Verify against the real API surface.

Spawn a hierarchy with a collection factory

Goal: spawn a whole tree of game objects in one call.

A .collectionfactory component points at a .collection. Unlike factory, collectionfactory.create(url, position?, rotation?, properties?, scale?) returns a LuaTable<Hash, Hash> mapping each prototype id in the collection to the runtime id it was spawned as. Read one spawned object out of the table with .get(prototypeId), passing the hash or the /-prefixed path string the collection gives it; the engine hashes a string key for you. go.delete(ids) deletes every object the call spawned.

import { defineScript } from "@defold-typescript/types";

export default defineScript({
  init() {
    const ids = collectionfactory.create("#levelfactory");
    // Read one spawned object out of the table by its prototype path.
    const player = ids.get("/player");
    return { player };
  },
});

To seed the spawned scripts' properties, call the curried collectionfactory.create<P>() directly with an object literal: P maps each instance id to ScriptPropertiesOf<typeof itsScript>, and the build hashes the ids.

collectionfactory.create<LevelProps>()("#levelfactory", undefined, undefined, { "/player": { speed: 250 } });

The bare form's properties table is keyed by hash("/player"), such as a LuaMap<Hash, PlayerProps>, because the engine raises on a string id.

Confirm collectionfactory.create against node_modules/@defold-typescript/types/generated/collectionfactory.d.ts and build the snippet — see Verify against the real API surface.

Pass messages between components

Goal: send a message from one component to another and receive it typed.

msg.post(receiver, message_id, message?) addresses the receiver by a URL string. Two forms cover most cases: "#component" reaches a sibling component on the same game object, and "/object#component" reaches a named component on a different object. The receiver handles it in on_message; to narrow the untyped payload by message_id without typeof/as, reuse the guard from Narrow engine callback payloads rather than re-deriving it here.

import { defineScript } from "@defold-typescript/types";

export default defineScript({
  update(self) {
    // "#…" → sibling on this object; "/path#…" → a component on another object.
    msg.post("#health", "damage", { amount: 10 });
    msg.post("/enemy#ai", "alert");
  },
});

Confirm each address resolves and the snippet builds — see Verify against the real API surface.

Address an object by URL

Goal: pick the right URL form for every msg.post / go.get / go.set / msg.url call, and know when the socket: prefix is required.

A Defold URL is [socket:][path][#fragment] — the first part is optional. Inside a single world (everything in your bootstrap collection) address by relative id, absolute path, or sibling component, with no socket::

  • "camera" — a sibling instance by id, resolved relative to the current component.
  • "/camera" — the same instance by id, absolute from the current world's root.
  • "#health" — a sibling component on the same game object.
  • "/enemy#ai" — a named component on a different object in the same world.

The socket: segment is reserved for crossing into a collection-proxy-loaded world: msg.post("level_a:/door#sensor", "open") reaches door#sensor in the collection whose Name property is level_a. That value is the target collection's Name, not the proxy component's id — and a collection's Name is a field distinct from its folder, so a bare "main:…" copied from a Lua example is fragile (it assumes your bootstrap collection happens to be named main).

msg.url takes no argument, one argument (a string, Hash, Url or undefined), or three arguments that may each be undefined, where an undefined socket is the current game world. A socket and fragment with an undefined path still raise Can't resolve id with specified socket and fragment. at runtime. The two-arg msg.url(socket, path) call is a runtime error, and the overloads in msg-overloads.d.ts reject it at compile time.

Confirm every address resolves and the snippet builds — see Verify against the real API surface. For the full address grammar and the cross-world proxy case, follow up with the TypeScript gotchas URL addressing entry.

Where script state lives

Goal: decide whether a piece of mutable state belongs on self or in a module.

Per-instance state belongs on the typed self: init's returned object is copied onto self for that component instance, so two objects running the same script keep independent values. A module-level let/const behaves differently, and the build shows how — this source:

import { defineScript } from "@defold-typescript/types";

// Module-level: one value, not per-instance.
let spawnCount = 0;

export default defineScript({
  init() {
    // Per-instance: copied onto this component's self.
    return { health: 100 };
  },
  update(self) {
    self.health -= 1;
    spawnCount += 1;
  },
});

compiles spawnCount to a single Lua module local evaluated once, while health is assigned onto each instance's self:

local spawnCount = 0
function init(self)
    -- self.health is set per instance
end
function update(____self)
    ____self.health = ____self.health - 1
    spawnCount = spawnCount + 1
end

Because Defold loads each module once via require and caches it, that module local is shared by every component instance that requires the module — it is not per-instance state. Reach for a module local only for constants or a deliberately-shared singleton; keep anything each instance must own its own copy of on self. The full self typing model — how init infers it and how properties seed it — is in Script lifecycle.

Above a module local sits one wider tier: a VM-global declared with declare global. The declaration emits no Lua; a use site lowers to a bare Lua global shared across the entire VM — no require, no module scope:

function ____exports.bump()
    FOO = FOO + 1
    return FOO
end

No local FOO and no ____exports. prefix — FOO is raw VM-wide state, broader than a cached module local. Reach for it only for genuine engine/Lua globals; prefer a module singleton for app state. The full four-tier treatment — per-instance self, shared module local, cross-script module singleton, and VM-global — is in Where script state lives.

Bump the pinned Defold version

Unlike every runbook above — written for an agent driving a consumer project — this section is for a maintainer (human or agent) working inside this repo, rotating the pinned Defold engine version the whole toolchain generates against. The mechanics are a single command; what a maintainer must still understand is the semantics, the network boundary, and the handful of decisions the command cannot make.

Prerequisites

  • Bun — the repo's package manager and script runner.
  • Network egress for the bump itself: it runs the fail-closed release import and fetches the upstream ref-doc.zip. The completeness gate (--check, below) is fully offline.

Usage

bun run bump:defold --to <version>

bump:defold --to orchestrates the whole rotation: it plans the transition, runs the fail-closed release import, rewrites the version sources of truth, syncs the ref-doc fixtures (core and extension) into the new target dir, rewrites the target metadata, regenerates every derived artifact, and reports the decisions left to a human. Add --json for a single machine-readable summary — it is the sole document on stdout, and its remainingHumanDecisions array is the part an agent branches on.

bun run bump:defold --check

bump:defold --check is the offline completeness gate: it re-derives the expected release evidence from the committed sources and fails if any generated artifact (fixtures, availability, signatures, the llms corpus) is stale relative to them. It touches no network. Run it after a bump — and in review — to prove the rotation is complete.

Patch vs minor

Both classes demote: the new version becomes the default target and the prior default moves into a committed historical surface under generated/versions/, keeping its own fixturesDir. A patch bump (1.13.0 to 1.13.1) does this just as a minor one (1.13.x to 1.14.0) does, so a patch never takes its predecessor's surface with it. bump:defold classifies which one applies from the --to version automatically — you do not select it.

What the classes differ on is retention: SURFACE_RETENTION in scripts/release-model.ts keeps the current release plus the newest release of the preceding minor line in DEFOLD_VERSIONS, so a patch drops its predecessor from that pre-baked pair while a minor keeps it. A dropped version stays resolvable through its api-targets.json entry and its committed surface; the bump reports each one as a manual review point rather than deciding silently.

Manual review points

bump:defold reports the decisions it deliberately will not make (its remainingHumanDecisions); resolve each by hand:

  • Vendor the engine bindings — bump:defold --to fails at its regen stage until fixtures/defold-<new>/engine-bindings/ and fixtures/defold-<new>/engine-evidence/ exist, and no bump stage creates them. A failed bump prints no remainingHumanDecisions, so the rest of this list still applies. Run the networked sync, then regenerate:

    GITHUB_TOKEN="$(gh auth token)" bun packages/types/scripts/sync-engine-bindings.ts
    bun run regen:all

    The sync re-reads every vendored target. A changed commit under an older target means upstream moved that release tag; check that no binding file changed with it. It also fetches engine-evidence/, the engine files a PROPERTY_KEY_RANGES engine pin names, at the bindings commit. The sync records each evidence file's blob id from that commit's tree in the bindings manifest and rejects a download whose bytes hash to another id. --evidence refreshes only those files, with no GitHub API call; a pin on a file the bindings manifest records no id for needs the full sync first.

  • Curate api-migrations.json for the <from> -> <to> transition — the deprecation list is never auto-edited.

  • Re-confirm import-manifest.json — verify the imported release tag matches the intended <to> build.

  • Author the upgrade guide — add a <!-- release: <new> --> section to packages/docs/guide/upgrading-defold-versions.md. The readiness gate follows the marker, so no new page and no new gate is owed per bump. Shape the section as the marker, then one ## Defold <new> owning the release, topic headings at h3 beneath it, and one h4 per documented symbol. Topic headings repeat freely across releases, but every ## Defold <version> and every per-symbol h4 must slug uniquely page-wide — a symbol documented in a second release needs a distinguishing suffix, or its anchor silently moves to the older note.

  • Minor bumps only — review the demoted defold-<prev> surface under generated/versions/.

Publication is separate

Cutting the npm release is decoupled from the bump: mise run release is its own networked step, run when you choose to publish. It is not part of completing a version bump.

Knowing a bump is due

Neither bump:defold --check nor release-readiness looks upstream — both gate the evidence for a bump already made. The trigger comes from the Defold upstream release check workflow, which runs daily and can be dispatched by hand:

bun run upstream:release-check --json

It resolves the upstream stable channel head (d.defold.com/stable/info.json), compares it to CURRENT_STABLE_DEFOLD_VERSION, and opens a GitHub issue naming the transition and the command to run. Drift exits 0 — only an unreachable channel fails. Three heads are deliberately ignored: one equal to the pin, one behind it (a channel rollback would otherwise ask for a downgrade the release model cannot express), and any prerelease. The stable channel is the source precisely because it never advertises the -beta/-alpha tags that would otherwise fire this every few weeks.

The issue title is keyed on the upstream version alone, so reruns before the bump lands find the existing issue instead of filing duplicates.

Footnotes

  1. src/ is this guide's shorthand and the scaffold's default, not a fixed location. Your source roots are the include globs in tsconfig.json — ["src/**/*.ts"] out of the box, and any list of folders you set; build and watch compile exactly what those globs match, and ignore exclude. ↩

On this page