TypeScript Order Tutorial
Download one complete draft-Order example, install its locked public npm packages, change Notebook quantity from 2 to 3, save the Order and line totals together, then read the result in a new Node process. The source package includes the evaluated model, generated library, console and three-order fixture; no site checkout, runtime checkout, generator account or online Assist call is needed.
The first read/edit below uses published @teaql/teaql 0.3.1. The later
seventeen-case suite, including deletion readback and pagination, still uses a
workspace runtime: WORKSPACE PASS — RELEASE PENDING. The nullable generator
repair remains pending generator deployment. Node SQLite evidence does not
certify browser/TFP execution.
1. Prepare the example
Download the TypeScript Order source ZIP and SHA256SUMS into the same empty directory. Check the archive before extracting it:
shasum -a 256 -c SHA256SUMS
unzip order-typescript-first-run.zip
cd order-typescript
On Linux, sha256sum -c SHA256SUMS is the equivalent checksum command.
The included README
contains the same startup and recovery steps.
You need:
- Node 22.23.4 and its bundled npm, matching
.nvmrc. With nvm already installed, runnvm installandnvm useinside this directory. Alternatively install that version from the official Node archive and put itsbindirectory on PATH. No global TypeScript or ts-node is needed. - Bash and unzip on macOS/Linux, or WSL on Windows, plus access to the public npm
registry.
better-sqlite3may download a compatible prebuilt addon from GitHub. If none is available, installation needs Python 3, a C/C++ toolchain, make and Node headers; on macOS use Xcode Command Line Tools. No database server or Docker is needed. The recorded run used a macOS ARM64 prebuild; other platforms were not newly verified. - Python 3 only if you want the independent database check below or need native addon compilation.
From the extracted directory:
node --version
npm --version
bash order.sh build
The wrapper requires Node v22.23.4. build runs npm ci with the unchanged
lockfile, explicit public registry settings and a package-local .npm-cache,
then npm run build (tsc --noEmit). Expect ORDER_BUILD_OK. Keep installation
scripts enabled so the native SQLite addon can install.
The included manifest
uses the npm alias teaql-ts for the historical @teaql/teaql version 0.3.1;
imports therefore use teaql-ts. The lockfile pins better-sqlite3 12.11.1, TypeScript
5.9.3, ts-node 10.9.2 and the transitive dependencies. Preserve the alias
and lockfile; do not copy another workspace's node_modules or silently upgrade
the runtime. This recipe qualifies the recorded version, not npm's latest.
For your own model, follow TypeScript Quick Start and scoped Assist. This download reuses the evaluated Order v1.0 model and three-order fixture. Isolation and stock use separate model revisions and are not drop-in fixtures for this package.
2. Understand startup and run the first edit
The included src/main.ts is the unchanged original first-flow application.
It imports UserContext from teaql-ts, SQLiteTeaQLClient from
teaql-ts/sql/sqlite, and application-local Q, E and
GENERATED_RUNTIME_MODULE. The read/write excerpts below come from that file;
its required helper and EDIT audit string are application definitions.
The console creates SQLiteTeaQLClient(database,{}), installs
GENERATED_RUNTIME_MODULE into the provider, registers it as dataService on a
server-created UserContext, then awaits context.ensureSchema(). Module
installation registers metadata and behavior; schema reconciliation is an
explicit database operation. In a service, keep startup/admin schema work
separate from requests and derive tenant/actor/policy from trusted server context.
The browser-safe package profile does not provide this Node SQLite wiring.
Run from the extracted order-typescript directory:
bash order.sh init
bash order.sh read
bash order.sh edit
bash order.sh verify
The default database is .local/orders.sqlite. init refuses an existing file
and never deletes data; the other commands refuse a missing database. Each phase
starts a fresh Node process against the same database. The console is a short
process example, not a long-lived service shutdown implementation; use the
separately qualified lifecycle examples for explicit provider cleanup.
| Command | Expected result |
|---|---|
init | Explicit schema setup, then three Orders and six items; ORDER_OK phase=bootstrap and ORDER_OK phase=seed. |
read | ORD-2026-1001 is DRAFT, total 3850 USD cents, Notebook quantity 2; Order/items version 1. |
edit | Notebook quantity 3, Notebook line total 3750, Order total 5100. |
verify | The same graph in a new process; Order and changed item version 2, untouched item version 1. |
Handlers print ORDER_CASE JSON and ORDER_OK phase=.... Find the Order by
business number and the item by SKU, not copied generated numeric IDs. Run the
edit once when comparing these first-run versions. To repeat the whole sequence:
export ORDER_DATABASE="$(mktemp -d)/orders.sqlite"
bash order.sh init
bash order.sh read
bash order.sh edit
bash order.sh verify
Keep the same absolute ORDER_DATABASE for all four commands. Seeding is not an
import/upsert service. Optionally check committed storage independently after
editing:
python3 check_database.py "${ORDER_DATABASE:-$PWD/.local/orders.sqlite}" edited fixture.json
The unchanged oracle opens SQLite read-only and checks totals, quantities,
versions, relations and integrity. bash order.sh notes also exposes the original
nullable/projection/invalid-quantity handlers; their NotLoaded probes are handled
negative examples, not startup failures. Those handlers retain their historical
evidence and were not rerun for this narrow packaging check.
First-run evidence
The 2026-11-15 first-run receipt records extraction without node_modules or npm cache, locked installation, TypeScript compilation, seed/read/edit/new-process readback, the read-only SQLite oracle and existing/missing-database guards. It binds the ZIP and source hashes, all 64 npm archive integrities, installed runtime resolution and the native addon hash/Node ABI. The verified environment was macOS ARM64 with Node 22.23.4 and npm 10.9.9, not a fresh OS image or a multi-platform campaign.
The original eight-case receipt remains the source authority. The later seventeen-case receipt keeps its workspace qualification. A first-edit PASS does not clear deletion, pagination, cancellation, lifecycle, browser or generator-deployment markers.
3. Load the full Order before editing
const rows=await Q.customerOrders().withOrderNumberIs("ORD-2026-1001").withOrderStatusIsDraft()
.selectOrderItemListWith(Q.orderItems().orderBySkuCodeAscending().orderByIdAscending().limit(101)).limit(2)
.comment("Load full draft order and complete bounded items").purpose("Validate and edit one draft order").executeForList(context);
The outer bound of 2 lets the application reject multiple matching DRAFT Orders; it does not establish global business-key uniqueness across other statuses. The child bound of 101 is an overflow sentinel for a supported maximum of 100 items. Require exactly one Order, DRAFT status and at most 100 loaded items before continuing. A one-item preview is useful for a list screen, but cannot supply the complete total for an edit. The full source performs these checks after the query; keep them when adapting the excerpt.
comment describes the operation and purpose records the business reason.
Both travel with execution through the trusted context. A buyer filter in this
v1.0 fixture is a business predicate; it does not authenticate or authorize a
buyer. Use the separate buyer/tenant isolation contract
when implementing protected access.
4. Validate money and save one atomic edit
The application validates integral quantity in [1, 100], USD currency, each stored
line amount and the complete new Order total. Prices and totals are integer cents.
It finds exactly one SKU-NOTEBOOK, computes 3 × 1250 + 3 × 450 = 5100, then
changes the selected item and Order together. The following write excerpt assumes
those validated, fully loaded variables; it is not a replacement for validation.
The audit reason is Edit draft Order quantity and totals atomically, named
EDIT in most examples and editReason/EditReason in Go, Swift and .NET.
changed.updateQuantity(quantity); changed.updateLineTotalMinor(quantity*required(E.orderItem(changed).unitPriceMinor().eval()));
order.updateTotalMinor(total); console.log("ORDER_GRAPH_ATTEMPT");
await order.auditAs(EDIT).save(context);
The edit rejects unsafe or non-integral JavaScript numbers before calculating integer cents. The loaded item objects belong to the Order graph; mutate the chosen item and save the audited Order once. Preserve the source package’s exact npm alias and lockfile when reproducing this edit.
A successful audited save returns the persisted typed entity. The core example reads again after mutation, rather than treating a pre-save object as independent evidence of committed state. A rejected stale write requires reloading authoritative state and a business decision before retrying; it is not permission to overwrite the winner or retry every provider error.
5. Use projections, nulls and pages deliberately
| Task | TypeScript API in this example | Result / responsibility |
|---|---|---|
| Execute a bounded query | await query.executeForList(context) | Typed SmartList; preserve native errors and check cardinality. |
| Read selected money | E.customerOrder(order).totalMinor().eval() | Loaded integer cents; not a formatting or currency conversion API. |
| Access selected items | order.orderItemList() | Only the relation that was explicitly loaded. |
| Default a selected SQL NULL note | orderNote().orElse("No note") | Null-only fallback; an empty string stays empty and NotLoaded still reports a missing field. |
| Save an audited mutation | await order.auditAs(EDIT).save(context) | Persisted typed entity; the required transaction includes all changed entities. |
| Request an exact page total | offset(offset).limit(limit).count() → page.totalCount | Total of the filtered set, independent of page length. |
The note accessors in the table are called on the corresponding E expression.
required, report, pageRows, load, edit and prepare_edit are application
helpers where present; they are not additional generated terminal methods.
| Note state | Expected behavior |
|---|---|
| Selected value | Leave at reception stays that value. |
| Selected SQL NULL | A null-only default produces No note. |
| Selected empty text | Remains the empty string. |
| Omitted field | Native NotLoaded diagnostic, including when a null-only default is attempted. |
The following page handler belongs to the later seventeen-case application,
which is not included in the first-run ZIP and retains its workspace RELEASE PENDING
qualification and retained workspace prerequisites.
For a read-only list screen, that bounded-page handler validates
offset >= 0 and 1 <= limit <= 3, sets a stable total/ID order and explicitly
selects one item preview per Order. With validated offset, limit and
buyer, its native query is:
const page=await Q.customerOrders().withBuyerReferenceIs(buyer).orderByTotalMinorAscending().orderByIdAscending()
.selectOrderItemListWith(Q.orderItems().orderBySkuCodeAscending().orderByIdAscending().limit(1)).offset(offset).limit(limit).count()
.comment("Read bounded Order pages").purpose("Compare filtered totals and per-order item previews").executeForList(context);
This query only reads. Do not save its one-item preview as if it were a full
Order edit or infer deletion of omitted items. The pagination fixture has eight
matching BUYER-EXPORT Orders, whereas the first-edit fixture above has three
Orders overall. See the page API decision guide
for fixture selection, continuous export, retained-ID jumps and aggregate results.
6. Diagnose a failure before changing code
A better-sqlite3 load/ABI error is a Node/native-addon setup problem. Match the recorded Node toolchain and build the addon for it; do not classify the failure as a query or optimistic conflict.
| Symptom | First action |
|---|---|
| Node version rejected | Activate 22.23.4 before both installation and execution; the wrapper checks .nvmrc. |
ts-node/register or dependency missing | Run bash order.sh build from the extracted package; use its local dependencies. |
| npm/prebuild download or fallback compiler fails | Check access to npm/GitHub/Node headers and the platform compiler; retry the same locked build. Keep install scripts enabled. |
| Existing DB / missing DB | Initialize a new absolute ORDER_DATABASE; use that same path for read/edit/verify. Never reseed an edited database. |
| Empty Order or duplicate row | Confirm absolute DB path, fixture and business number; preserve the cardinality check. |
| Wrong total after edit | Check complete item loading and integer validation before the audited save. |
| Missing field error | Reload the field/relation explicitly; do not substitute a null default. |
| Version conflict | Reload authoritative state and decide whether the requested edit is still valid. |
| Busy/locked, commit or cancellation failure | Inspect native provider error and transaction boundary; follow the TypeScript Order troubleshooting table. |
Continue with the Order API usage guide, TypeScript advanced data operations, version and qualification table and documentation coverage matrix. The School regression baseline and all prior Order receipts remain unchanged.
Continue with advanced Order writes
Follow TypeScript Advanced Order Mutations for explicit line deletion, legal state transitions and stale-version recovery. Each recipe explains its starting state, transaction boundary, native errors and independent readback using the existing qualified example. Start a fresh recipe database; do not reuse the quantity-edited database above.
Continue with Order queries
Use TypeScript Order Queries for continuous export, retained-ID page jumps and provider summaries. The query recipes use separate nine-/ten-order datasets; keep the fixture and context/store lifetime with the operation you are learning.
Continue with buyer and tenant isolation
Use TypeScript Order Isolation to upgrade the model to v1.1 and build root/buyer scope from an application-owned trusted session.