### Run Hono Example Source: https://github.com/nordcraftengine/nordcraft/blob/main/examples/custom-element/README.md Use this command to start the Hono example. Ensure you have Bun installed. ```bash template=medium bun run dev ``` -------------------------------- ### Signal Usage Example Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Demonstrates how to create, get, and set values for a reactive signal. ```typescript const count = signal(0) count() // Get value: 0 count.set(1) // Set value to 1 ``` -------------------------------- ### Install Dependencies Source: https://github.com/nordcraftengine/nordcraft/blob/main/README.md Install project dependencies using bun. This command is essential for setting up the development environment. ```bash bun install ``` -------------------------------- ### Create a Button Component Example Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/02-component-types.md An example demonstrating how to define a simple button component with a label attribute and an onClick event. ```typescript const buttonComponent: Component = { name: 'Button', description: 'Reusable button component', attributes: { label: { name: 'label', type: 'string' }, onClick: { name: 'onClick', type: 'event' } }, nodes: { root: { type: 'element', tag: 'button', children: ['label-text'] }, 'label-text': { type: 'text', value: { type: 'path', path: ['Attributes', 'label'] } } } } ``` -------------------------------- ### Build Commands Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/07-backend-integration.md Common commands for type checking, building, development, and starting the application using Bun. ```bash # Type check bun typecheck # Build bun run build # Development bun dev # Production bun start ``` -------------------------------- ### SwitchOperation Example Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/03-formula-system.md An example demonstrating how to use the SwitchOperation to handle different states or errors based on variable paths. ```typescript { type: 'switch', cases: [ { condition: { type: 'path', path: ['Variables', 'status'] }, formula: { type: 'value', value: 'Loading...' } }, { condition: { type: 'path', path: ['Variables', 'error'] }, formula: { type: 'value', value: 'Error occurred' } } ], default: { type: 'path', path: ['Apis', 'getData', 'data'] } } ``` -------------------------------- ### FunctionOperation Examples Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/03-formula-system.md Shows how to call built-in functions like String.length() and custom functions from a specific package. ```typescript // Call built-in function: String.length() { type: 'function', name: 'length', arguments: [ { formula: { type: 'path', path: ['Attributes', 'name'] } } ] } ``` ```typescript // Call custom function: myPackage.capitalize() { type: 'function', name: 'capitalize', package: 'myPackage', arguments: [ { formula: { type: 'path', path: ['Attributes', 'text'] } } ] } ``` -------------------------------- ### Example ElementNodeModel for a Button Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/02-component-types.md An example of creating an ElementNodeModel for a button. Note the use of 'Formula' for attributes like 'onClick'. ```typescript const buttonElement: ElementNodeModel = { type: 'element', tag: 'button', attrs: { class: { type: 'value', value: 'primary-btn' }, onClick: { type: 'value', value: 'handleClick' } }, style: { backgroundColor: '#0066cc', padding: '10px 20px' }, children: ['label'] } ``` -------------------------------- ### Run Preview Server Source: https://github.com/nordcraftengine/nordcraft/blob/main/packages/backend/README.md Starts a preview server that fetches project files from a Durable Object. Requires linking to the internal Nordcraft repository first. ```sh bun run preview ``` -------------------------------- ### PathOperation Examples Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/03-formula-system.md Demonstrates accessing various data paths, including nested properties and array indices. ```typescript // Access Attributes.name { type: 'path', path: ['Attributes', 'name'] } ``` ```typescript // Access Variables.count { type: 'path', path: ['Variables', 'count'] } ``` ```typescript // Access ListItem.Item (in loops) { type: 'path', path: ['ListItem', 'Item'] } ``` ```typescript // Access nested data: data.Apis.apiName.data.users { type: 'path', path: ['Apis', 'apiName', 'data', 'users'] } ``` ```typescript // Access array index: ListItem.Item[0] { type: 'path', path: ['ListItem', 'Item', 0] } ``` -------------------------------- ### ArrayOperation Example Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/03-formula-system.md An example of creating an array with literal values and a value accessed via a path. ```typescript { type: 'array', arguments: [ { formula: { type: 'value', value: 'item1' } }, { formula: { type: 'value', value: 'item2' } }, { formula: { type: 'path', path: ['Attributes', 'thirdItem'] } } ] } // Evaluates to: ['item1', 'item2', ] ``` -------------------------------- ### List Iteration Example Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Shows how to iterate over a list of items and display a property from each item. ```typescript const listNode: ElementNodeModel = { type: 'element', tag: 'div', repeat: { type: 'path', path: ['Attributes', 'items'] }, repeatKey: { type: 'path', path: ['ListItem', 'Item', 'id'] }, children: ['itemContent'] } const itemContent: TextNodeModel = { type: 'text', value: { type: 'path', path: ['ListItem', 'Item', 'name'] } } ``` -------------------------------- ### Instantiate ToddleComponent and Get Dependencies Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/06-toddlecomponent-class.md Demonstrates how to instantiate a ToddleComponent and retrieve its unique sub-components and formula references. ```typescript const button = new ToddleComponent({ component: buttonComponent, getComponent: getComponent, packageName: undefined, globalFormulas: formulas }) // Get all sub-components const dependencies = button.uniqueSubComponents // Get all formula calls const formulaCalls = button.formulaReferences // Traverse all formulas with context const allFormulas = Array.from(button.formulasInComponent()) ``` -------------------------------- ### Basic Hono Integration Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/07-backend-integration.md Integrates Hono with the backend framework using `createApp`. This example shows how to configure the `projectInfoFn` to load project details and files. ```typescript import { createApp } from '@nordcraft/backend/hono' const app = createApp({ projectInfoFn: async () => ({ project: { name: 'App', id: 'id', short_id: 'sh', type: 'app' }, fileGetter: async ({ name, type, package: pkg }) => { // Load from filesystem, database, or API } }) }) app.listen(3000) ``` -------------------------------- ### OrOperation Example Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/03-formula-system.md An example of an OrOperation used to check if a user has any of multiple roles (admin, owner, moderator). ```typescript { type: 'or', arguments: [ { formula: { type: 'path', path: ['Variables', 'isAdmin'] } }, { formula: { type: 'path', path: ['Variables', 'isOwner'] } }, { formula: { type: 'path', path: ['Variables', 'isModerator'] } } ] } ``` -------------------------------- ### ValueOperation Examples Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/03-formula-system.md Illustrates how to represent literal string, number, boolean, and object values using ValueOperation. ```typescript // Literal string { type: 'value', value: 'Hello World' } ``` ```typescript // Literal number { type: 'value', value: 42 } ``` ```typescript // Literal boolean { type: 'value', value: true } ``` ```typescript // Literal object { type: 'value', value: { name: 'John', age: 30 } } ``` -------------------------------- ### ObjectOperation Example Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/03-formula-system.md An example of creating an object with properties 'id', 'name', and 'active', where 'id' and 'name' are derived from attributes and 'active' is a literal. ```typescript { type: 'object', arguments: [ { name: 'id', formula: { type: 'path', path: ['Attributes', 'id'] } }, { name: 'name', formula: { type: 'path', path: ['Attributes', 'name'] } }, { name: 'active', formula: { type: 'value', value: true } } ] } // Evaluates to: { id: 123, name: 'John', active: true } ``` -------------------------------- ### Conditional Rendering Example Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how to conditionally render a text node based on a variable's value. ```typescript const node: TextNodeModel = { type: 'text', value: { type: 'value', value: 'Hello' }, condition: { type: 'path', path: ['Variables', 'isVisible'] } } ``` -------------------------------- ### Implement FileGetter Function Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/05-ssr-reference.md An example implementation of the FileGetter function. It constructs a file path based on package and type, then fetches and parses the JSON response. ```typescript const fileGetter: FileGetter = async ({ name, type, package: pkg }) => { const path = pkg ? `${pkg}/${type}/${name}.json` : `${type}/${name}.json` const response = await fetch(path) return response.json() } ``` -------------------------------- ### @toddle/startsWith Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Checks if a string begins with the characters of a specified string. Returns true if it starts with the prefix, otherwise false. ```APIDOC ## @toddle/startsWith ### Description Checks string prefix. ### Signature ```typescript @toddle/startsWith(str: string, prefix: string): boolean ``` ``` -------------------------------- ### InstalledPackage Interface Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/05-ssr-reference.md Represents a dependency package installed in the project, including its components, actions, formulas, and manifest details. ```APIDOC ## InstalledPackage Interface Dependency package installed in the project. ```typescript type InstalledPackage = Pick< ProjectFiles, 'components' | 'actions' | 'formulas' > & { manifest: { name: string commit: string } } ``` **Parameters**: | Parameter | Type | Description | |-----------|------|-------------| | components | `Record` | Exported components | | actions | `Record` | Exported actions | | formulas | `Record` | Exported formulas | | manifest.name | `string` | Package name | | manifest.commit | `string` | Package version (commit hash) | ``` -------------------------------- ### Check if String Starts With Prefix Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Checks if a string begins with the characters of a specified prefix. Returns true if it does, false otherwise. ```typescript @toddle/startsWith(str: string, prefix: string): boolean ``` -------------------------------- ### Event Handling with API Fetch Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md An example of handling a click event to fetch data from an API and store the result in a variable. ```typescript const workflow: ComponentWorkflow = { name: 'onClick', trigger: { name: 'click' }, actions: { first: { type: 'Fetch', api: 'myApi', inputs: { id: { type: 'path', path: ['Attributes', 'id'] } } }, second: { type: 'Variable', name: 'result', value: { type: 'path', path: ['Apis', 'myApi', 'data'] } } } } ``` -------------------------------- ### Instantiate ToddleComponent Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/06-toddlecomponent-class.md Example of how to create a new instance of the ToddleComponent class, providing necessary parameters like the component definition and a function to resolve other components. ```typescript const toddleComponent = new ToddleComponent({ component: buttonComponent, getComponent: (name, pkg) => componentRegistry[name], packageName: undefined, globalFormulas: { formulas: { capitalize: {...} }, packages: {} } }) ``` -------------------------------- ### Evaluate Simple Addition Formula Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/03-formula-system.md Example of using `applyFormula` to evaluate a simple addition formula. This demonstrates how to structure a formula object with nested values. ```typescript const result = applyFormula( { type: 'function', name: 'add', arguments: [ { formula: { type: 'value', value: 5 } }, { formula: { type: 'value', value: 3 } } ] }, formulaContext ) // Result: 8 ``` -------------------------------- ### InstalledPackage Interface Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/05-ssr-reference.md Defines the structure for an installed dependency package. Includes exported components, actions, formulas, and package manifest details like name and commit hash. ```typescript type InstalledPackage = Pick< ProjectFiles, 'components' | 'actions' | 'formulas' > & { manifest: { name: string commit: string } } ``` -------------------------------- ### Get Theme Signal Function Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Retrieves the current theme from the page state. Returns a Signal containing the theme name or null. ```typescript const getThemeSignal = ( pageState: ComponentData, ): Signal ``` -------------------------------- ### Build Component Dependency Graph Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/06-toddlecomponent-class.md Recursively builds a component dependency graph starting from a root ToddleComponent. It tracks visited components to avoid infinite loops. ```typescript function buildComponentGraph( root: ToddleComponent, visited = new Set() ) { const graph = {} if (visited.has(root.component.name)) return graph visited.add(root.component.name) graph[root.component.name] = root.uniqueSubComponents.map(sub => { return sub.component.name }) for (const sub of root.uniqueSubComponents) { Object.assign(graph, buildComponentGraph(sub, visited)) } return graph } ``` -------------------------------- ### ToddleComponent Constructor Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/06-toddlecomponent-class.md Initializes a new instance of the ToddleComponent class. It requires the component definition, a function to get other components, the package name, and global formulas. ```APIDOC ## Constructor ### Constructor Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | component | `Component` | Yes | Component definition to wrap | | getComponent | `(name: string, packageName?: string) => Component | undefined` | Yes | Function to resolve component references | | packageName | `string | undefined` | Yes | Package this component belongs to | | globalFormulas | `GlobalFormulas` | Yes | Global formula definitions | **Example**: ```typescript const toddleComponent = new ToddleComponent({ component: buttonComponent, getComponent: (name, pkg) => componentRegistry[name], packageName: undefined, globalFormulas: { formulas: { capitalize: {...} }, packages: {} } }) ``` ``` -------------------------------- ### Hono Integration with Custom Data Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/07-backend-integration.md Extends the Hono integration by providing custom data through the `getComponentData` function. This example fetches user details and includes them in the component data. ```typescript const app = createApp({ projectInfoFn: projectLoader, getComponentData: async (req) => { const user = await getUser(req) return { User: { id: user.id, email: user.email, isAdmin: user.isAdmin, } } } }) ``` -------------------------------- ### Initialize Preview Server Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/07-backend-integration.md Set up a preview server for development using `createApp`. This server supports hot reloading and provides debugging information. ```typescript const previewApp = createApp({ projectInfoFn: previewProjectLoader, // ... }) ``` -------------------------------- ### Run Development Server Source: https://github.com/nordcraftengine/nordcraft/blob/main/packages/backend/README.md Executes the development server. Ensure static assets are built beforehand using the predev command. ```sh bun run dev ``` -------------------------------- ### Define a Reusable Component Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Create a Nordcraft component with a name, description, input attributes, state variables, DOM nodes, and event actions. This example defines a button component that increments a counter on click. ```typescript const myComponent: Component = { name: 'MyComponent', description: 'My reusable component', // Input properties attributes: { label: { name: 'label', type: 'string', required: true, defaultValue: 'Click me' } }, // State variables: { count: { name: 'count', initialValue: { type: 'value', value: 0 } } }, // DOM tree nodes: { root: { type: 'element', tag: 'button', attrs: { onClick: { type: 'value', value: 'handleClick' } }, children: ['label'] }, label: { type: 'text', value: { type: 'path', path: ['Attributes', 'label'] } } }, // Event handlers actions: { onClick: { name: 'onClick', trigger: { name: 'click' }, actions: { increment: { type: 'Variable', name: 'count', value: { type: 'function', name: 'add', arguments: [ { formula: { type: 'path', path: ['Variables', 'count'] } }, { formula: { type: 'value', value: 1 } } ] } } } } } } ``` -------------------------------- ### Create Hono App with createApp Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/07-backend-integration.md Use the `createApp` function from `@nordcraft/backend/hono` to initialize a Hono application. It requires a `projectInfoFn` to load project metadata and a file getter. ```typescript import { createApp } from '@nordcraft/backend/hono' const app = createApp({ projectInfoFn: async () => ({ project: { name: 'MyApp', id: 'app-123', ... }, fileGetter: async ({ name, type, package: pkg }) => { // Load components, formulas, etc. } }) }) export default app ``` -------------------------------- ### API Performance Interface Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/09-complete-types-reference.md Interface to track API request performance, including timestamps for request start, response start, and response end. ```typescript interface ApiPerformance { requestStart?: Nullable responseStart?: Nullable responseEnd?: Nullable } ``` -------------------------------- ### Initialize Nordcraft Backend with Hono Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Set up the Nordcraft backend application using Hono. This involves defining project information and a file getter function for loading resources. The application listens on port 3000. ```typescript import { createApp } from '@nordcraft/backend/hono' const app = createApp({ projectInfoFn: async () => ({ project: { name: 'MyApp', id: 'app-123', short_id: 'app', type: 'app' }, fileGetter: async ({ name, type, package: pkg }) => { // Load components, formulas, etc. const path = pkg ? `${pkg}/${type}/${name}.json` : `${type}/${name}.json` const res = await fetch(path) return res.json() } }), getComponentData: async (req) => ({ User: { id: 'user-123', email: 'user@example.com' } }) }) app.listen(3000) ``` -------------------------------- ### Build All Packages Source: https://github.com/nordcraftengine/nordcraft/blob/main/README.md Build all packages within the repository. This command is used for compiling the project for distribution or deployment. ```bash bun run build ``` -------------------------------- ### Common Bun Commands Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Provides essential commands for building, type checking, development, production, and testing within the Nordcraft project using Bun. ```bash # Build all packages bun run build # Type check bun typecheck # Development bun dev # Production bun start # Testing bun test ``` -------------------------------- ### Nordcraft Project File Structure Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Illustrates the standard directory layout for components, formulas, actions, APIs, and pages within a Nordcraft project. ```plaintext components/ Button.ts Card.ts formulas/ capitalize.ts filter.ts actions/ navigate.ts save.ts apis/ getUsers.ts pages/ Home.ts About.ts ``` -------------------------------- ### Project Types Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/INDEX.md Defines the types related to Nordcraft projects, files, APIs, routes, and installed packages. ```typescript // Project Types ToddleProject ProjectFiles ApiService (union) Route (union) InstalledPackage ``` -------------------------------- ### @toddle/values Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Gets an array of a given object's own enumerable property values. Returns the array of values. ```APIDOC ## @toddle/values ### Description Gets object values. ### Signature ```typescript @toddle/values(obj: object): unknown[] ``` ``` -------------------------------- ### Runtime Package Imports Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/INDEX.md Import initialization and root creation functions from the '@nordcraft/runtime' package. ```typescript import { initGlobalObject, createRoot } from '@nordcraft/runtime' ``` -------------------------------- ### @toddle/keys Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Gets an array of a given object's own enumerable property names. Returns the array of keys. ```APIDOC ## @toddle/keys ### Description Gets object property names. ### Signature ```typescript @toddle/keys(obj: object): string[] ``` ``` -------------------------------- ### Runtime Initialization Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/README.md Functions for initializing the Nordcraft Engine runtime environment, including setting up global objects and creating the root element for rendering. ```APIDOC ## initGlobalObject ### Description Initializes the global object with optional formulas and actions. ### Signature ```typescript initGlobalObject(code?: { formulas, actions }) ``` ## createRoot ### Description Creates the root HTML element for the Nordcraft application. ### Signature ```typescript createRoot(domNode: HTMLElement) ``` ### Parameters - **domNode** (HTMLElement) - The DOM node to attach the root to. ``` -------------------------------- ### Runtime Package Initialization Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/README.md Functions for initializing the global object and creating the root for the runtime environment. ```typescript initGlobalObject, createRoot, Toddle, LocationSignal ``` -------------------------------- ### createApp Function (Hono Integration) Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/07-backend-integration.md The `createApp` function initializes a Hono application instance for Nordcraft projects. It accepts configuration options such as project information retrieval, custom component data fetching, route definitions, themes, and error handling. ```APIDOC ## createApp Function (Hono) ### Description Initializes a Hono application instance for Nordcraft projects, handling routing, middleware, and project loading. ### Signature ```typescript const createApp = (options: { projectInfoFn: () => Promise<{ project: ToddleProject, fileGetter: FileGetter }> getComponentData?: (req: Request) => Promise routes?: Route[] themes?: Record onError?: (error: Error, req: Request) => void }): Hono ``` ### Parameters #### Options - **projectInfoFn** (`() => Promise<{ project: ToddleProject, fileGetter: FileGetter }>`) - Required - Async function returning project metadata and file getter. - **getComponentData** (`(req: Request) => Promise`) - Optional - Function to add custom data to components based on the request. - **routes** (`Route[]`) - Optional - Route definitions for rewrites and redirects. - **themes** (`Record`) - Optional - An object containing available themes. - **onError** (`(error: Error, req: Request) => void`) - Optional - Callback function to handle errors. ### Returns Hono application instance ready to be mounted. ### Example ```typescript import { createApp } from '@nordcraft/backend/hono' const app = createApp({ projectInfoFn: async () => ({ project: { name: 'MyApp', id: 'app-123', ... }, fileGetter: async ({ name, type, package: pkg }) => { // Load components, formulas, etc. } }) }) export default app ``` ``` -------------------------------- ### Get Registered Action Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Retrieves a previously registered custom action by its name. Returns `undefined` if the action is not found. ```typescript toddle.getAction(name: string): ActionHandler | undefined ``` -------------------------------- ### Get Registered Formula Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Retrieves a previously registered custom formula by its name. Returns `undefined` if the formula is not found. ```typescript toddle.getFormula(name: string): FormulaHandler | undefined ``` -------------------------------- ### Import Runtime and SSR Modules Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Import modules for initializing the global object and creating the root for runtime, as well as types for SSR project files and file getters. ```typescript // Runtime import { initGlobalObject, createRoot } from '@nordcraft/runtime' // SSR import type { ProjectFiles, FileGetter } from '@nordcraft/ssr' ``` -------------------------------- ### Project Configuration (config Object) Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/05-ssr-reference.md Defines project-level configuration settings, including runtime version, default theme, and meta tag generation rules using formulas. ```APIDOC ## config Object Project-level configuration in `ProjectFiles.config`: ```typescript config?: { runtimeVersion?: string // Target runtime version theme?: OldTheme // Default theme meta?: { icon?: { formula: Formula } robots?: { formula: Formula } sitemap?: { formula: Formula } manifest?: { formula: Formula } serviceWorker?: { formula: Formula } } } ``` **Meta Formulas**: Dynamic generation of: - `icon` - Favicon href - `robots.txt` rules - `sitemap.xml` entries - Web manifest - Service worker code ``` -------------------------------- ### Custom Property Name Type Alias Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/09-complete-types-reference.md Defines a type for custom CSS property names, which must start with '--'. ```typescript type CustomPropertyName = `--${string}` ``` -------------------------------- ### Create Root Component Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Renders the root component into a specified DOM element. Ensure initGlobalObject() is called first and window.__toddle is populated. ```typescript const createRoot = (domNode: HTMLElement) => void ``` ```typescript // In HTML
// In JavaScript initGlobalObject() const app = document.getElementById('app') createRoot(app) ``` -------------------------------- ### Get current branch name Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Retrieves the name of the current Git branch. This can be useful for logging or conditional logic based on the branch. ```typescript @toddle/branchName(): string ``` -------------------------------- ### createRoot Function Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Renders the root component into a specified DOM element. This function should be called after `initGlobalObject`. ```APIDOC ## createRoot Function ### Description Renders the root component into a specified DOM element. This function should be called after `initGlobalObject`. ### Signature ```typescript const createRoot = (domNode: HTMLElement) => void ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **domNode** (`HTMLElement`, Required): DOM element to render into. ### Example ```typescript // In HTML //
// In JavaScript initGlobalObject() const app = document.getElementById('app') createRoot(app) ``` ### Requirements - Must call `initGlobalObject()` first. - `window.__toddle` must be populated with component data. - DOM node must be empty. ``` -------------------------------- ### @toddle/entries Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Gets an array of a given object's own enumerable string-keyed property [key, value] pairs. Returns the array of entries. ```APIDOC ## @toddle/entries ### Description Gets key-value pairs. ### Signature ```typescript @toddle/entries(obj: object): Array<[string, unknown]> ``` ``` -------------------------------- ### Link Local Packages Source: https://github.com/nordcraftengine/nordcraft/blob/main/README.md Link all local packages in the repository using bun link. This is useful for local development to test packages against each other. ```bash bun run link ``` -------------------------------- ### isPageComponent Function Example Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/02-component-types.md Demonstrates how to use the isPageComponent function to check if a component is a page with routing capabilities. If it is, the route property is guaranteed to exist. ```typescript if (isPageComponent(component)) { const route = component.route // Guaranteed to exist } ``` -------------------------------- ### Import Backend and Standard Library Modules Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Import the Hono backend application creator and formulas from the standard library. Ensure correct paths for these imports. ```typescript // Backend import { createApp } from '@nordcraft/backend/hono' // Standard library import * as formulas from '@nordcraft/std-lib/dist/formulas' ``` -------------------------------- ### Extract Subarray Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Extracts a section of an array and returns a new array containing the extracted elements. Specify start and optional end indices. ```typescript @toddle/slice( array: unknown[], start?: number, end?: number ): unknown[] ``` -------------------------------- ### Editor Preview Entry Point Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Defines the entry point for the special runtime used for rendering components within the Nordcraft editor. It supports live updates and debugging. ```typescript packages/runtime/src/editor-preview.main.ts ``` -------------------------------- ### Get Object Values Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Retrieves an array of a given object's own enumerable property values. Use this to access all values within an object. ```typescript @toddle/values(obj: object): unknown[] ``` -------------------------------- ### Backend Package Imports Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/INDEX.md Import the createApp function for backend integration with Hono, Node.js, or Bun. ```typescript import { createApp } from '@nordcraft/backend/hono' import { createApp } from '@nordcraft/backend/node' import { createApp } from '@nordcraft/backend/bun' ``` -------------------------------- ### Nordcraft Runtime Architecture Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/INDEX.md Describes the key processes managed by the @nordcraft/runtime package. ```text @nordcraft/runtime ├── Page Initialization ├── Component Rendering ├── Formula Evaluation ├── API Execution ├── Event Handling └── State Management ``` -------------------------------- ### initGlobalObject Function Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Initializes the global `toddle` object and sets up the runtime environment. It can also register custom formulas and actions. ```APIDOC ## initGlobalObject Function ### Description Initializes the global `toddle` object and sets up the runtime environment. It can also register custom formulas and actions. ### Signature ```typescript const initGlobalObject = (code?: { formulas: Record>> actions: Record> }) => void ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **code** (`object`, Optional): Custom formulas and actions to register. - **code.formulas** (`Record`, Optional): Package → formula name → formula definition. - **code.actions** (`Record`, Optional): Package → action name → action definition. ### Example ```typescript initGlobalObject({ formulas: { 'my-package': { 'myFormula': { name: 'myFormula', handler: (args, ctx) => args.value.toUpperCase() } } }, actions: { 'my-package': { 'myAction': { name: 'myAction', version: 2, handler: (args, ctx) => console.log(args) } } } }) ``` ``` -------------------------------- ### Build Docker Image for Backend Source: https://github.com/nordcraftengine/nordcraft/blob/main/packages/backend/README.md Builds the Docker image for the Nordcraft backend. Use `docker:build:debug` to build without cache. ```sh bun run docker:build ``` -------------------------------- ### Import Core Types and App Creation Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/07-backend-integration.md Import necessary types for routes, components, and component data, along with the createApp function from the Hono backend package. ```typescript import type { Route, Component, ComponentData } from '@nordcraft/core' import { createApp } from '@nordcraft/backend/hono' ``` -------------------------------- ### ApiPerformance Interface Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/01-core-api-types.md Provides timing metrics for API requests, including when the request started, when response headers were received, and when the response body was fully received. ```APIDOC ## ApiPerformance Interface ### Description Timing metrics for API requests. ### Interface Definition ```typescript interface ApiPerformance { requestStart?: Nullable responseStart?: Nullable responseEnd?: Nullable } ``` ### Parameters #### Interface Fields - **requestStart** (`number`) - Optional - Timestamp when request started (ms) - **responseStart** (`number`) - Optional - Timestamp when response headers received (ms) - **responseEnd** (`number`) - Optional - Timestamp when response body fully received (ms) ``` -------------------------------- ### Project Configuration for SSR Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/05-ssr-reference.md Defines the optional `config` object for project-level configuration, including runtime version, default theme, and settings for dynamically generating meta tags like icons, robots.txt, sitemaps, manifests, and service workers using formulas. ```typescript config?: { runtimeVersion?: string // Target runtime version theme?: OldTheme // Default theme meta?: { icon?: { formula: Formula } robots?: { formula: Formula } sitemap?: { formula: Formula } manifest?: { formula: Formula } serviceWorker?: { formula: Formula } } } ``` -------------------------------- ### Get current page URL Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Retrieves the full current URL of the page, including the protocol, host, path, query parameters, and hash fragment. ```typescript @toddle/currentURL(): string ``` -------------------------------- ### Get Object Property Names Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Retrieves an array of a given object's own enumerable property names. Use this to iterate over an object's keys. ```typescript @toddle/keys(obj: object): string[] ``` -------------------------------- ### initLogState Function Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Initializes debug logging for the runtime. This function is part of the debugging utilities provided by the Nordcraft runtime. ```APIDOC ## initLogState Function ### Description Initializes debug logging for the runtime. ### Signature ```typescript const initLogState = () => void ``` ``` -------------------------------- ### Set Theme Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Applies a specified theme to the application. ```typescript @toddle/setTheme(themeName) ``` -------------------------------- ### Get Custom Action from Registry Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Retrieves a custom action from the actions registry, optionally specifying a package name. Useful for accessing actions provided by plugins. ```typescript toddle.getCustomAction( name: string, packageName?: string, ): PluginActionV2 | undefined ``` -------------------------------- ### Get Custom Formula from Registry Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Retrieves a custom formula from the formulas registry, optionally specifying a package name. Useful for accessing formulas provided by plugins. ```typescript toddle.getCustomFormula( name: string, packageName?: string, ): PluginFormula | undefined ``` -------------------------------- ### Storage Actions Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Actions for interacting with browser storage mechanisms. ```APIDOC ## saveToLocalStorage ### Description Saves a key-value pair to the browser's local storage. ### Method Signature ```typescript @toddle/saveToLocalStorage(key: string, value: any) ``` ### Parameters #### Path Parameters - **key** (string) - Required - The key under which to store the value. - **value** (any) - Required - The value to store. ``` ```APIDOC ## deleteFromLocalStorage ### Description Deletes an item from the browser's local storage by its key. ### Method Signature ```typescript @toddle/deleteFromLocalStorage(key: string) ``` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the item to delete. ``` ```APIDOC ## clearLocalStorage ### Description Clears all data from the browser's local storage. ### Method Signature ```typescript @toddle/clearLocalStorage() ``` ``` ```APIDOC ## saveToSessionStorage ### Description Saves a key-value pair to the browser's session storage. ### Method Signature ```typescript @toddle/saveToSessionStorage(key: string, value: any) ``` ### Parameters #### Path Parameters - **key** (string) - Required - The key under which to store the value. - **value** (any) - Required - The value to store. ``` ```APIDOC ## deleteFromSessionStorage ### Description Deletes an item from the browser's session storage by its key. ### Method Signature ```typescript @toddle/deleteFromSessionStorage(key: string) ``` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the item to delete. ``` ```APIDOC ## clearSessionStorage ### Description Clears all data from the browser's session storage. ### Method Signature ```typescript @toddle/clearSessionStorage() ``` ``` -------------------------------- ### Get Unique Sub-Components of a ToddleComponent Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/06-toddlecomponent-class.md The 'uniqueSubComponents' getter returns an array of unique ToddleComponent instances referenced by the current component. It deduplicates child components by name. ```typescript get uniqueSubComponents(): ToddleComponent[] ``` ```typescript // If a component references Button and Card twice each const subComps = toddleComponent.uniqueSubComponents // Returns: [ToddleComponent(Button), ToddleComponent(Card)] ``` -------------------------------- ### Initialize Global Runtime Object Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md Initializes the global 'toddle' object and sets up the runtime environment. Use this to register custom formulas and actions. ```typescript const initGlobalObject = (code?: { formulas: Record>> actions: Record> }) => void ``` ```typescript initGlobalObject({ formulas: { 'my-package': { 'myFormula': { name: 'myFormula', handler: (args, ctx) => args.value.toUpperCase() } } }, actions: { 'my-package': { 'myAction': { name: 'myAction', version: 2, handler: (args, ctx) => console.log(args) } } } }) ``` -------------------------------- ### Nordcraft Backend Architecture Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/INDEX.md Outlines the responsibilities of the @nordcraft/backend package for server-side operations. ```text @nordcraft/backend ├── HTTP Server Integration ├── Page Handling ├── Static Asset Serving ├── API Proxying └── Route Management ``` -------------------------------- ### Get Object Key-Value Pairs Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Retrieves an array of a given object's own enumerable string-keyed property [key, value] pairs. Useful for iterating over both keys and values simultaneously. ```typescript @toddle/entries(obj: object): Array<[string, unknown]> ``` -------------------------------- ### Define Modern v2 API Request Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Defines an HTTP GET request to fetch users with authorization headers and query parameters. Uses path formulas for dynamic values. ```typescript const api: ApiRequest = { version: 2, name: 'fetchUsers', type: 'http', autoFetch: { type: 'value', value: true }, url: { type: 'value', value: 'https://api.example.com' }, path: { users: { formula: { type: 'value', value: 'users' }, index: 0 } }, method: ApiMethod.GET, headers: { 'Authorization': { formula: { type: 'path', path: ['Variables', 'token'] } } }, inputs: { pageSize: { formula: { type: 'value', value: 10 } } }, queryParams: { limit: { formula: { type: 'path', path: ['Variables', 'pageSize'] } } }, client: { credentials: 'include', parserMode: 'json', onCompleted: { name: 'onSuccess' }, onFailed: { name: 'onError' } } } ``` -------------------------------- ### Get Formula References from a ToddleComponent Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/06-toddlecomponent-class.md The 'formulaReferences' getter returns a Set of strings representing all formula functions called within this component. This includes built-in and namespaced package formulas. ```typescript get formulaReferences(): Set ``` ```typescript const refs = toddleComponent.formulaReferences // Returns: Set(['length', 'filter', 'myPackage/custom']) ``` -------------------------------- ### Backend Package App Creation Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/README.md Function to create an application using Hono for the backend. ```typescript createApp (Hono) ``` -------------------------------- ### Nordcraft Standard Library Architecture Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/INDEX.md Details the categories and number of formulas and actions available in the @nordcraft/std-lib package. ```text @nordcraft/std-lib ├── Array Formulas (20+) ├── String Formulas (15+) ├── Object Formulas ├── Math Formulas ├── Date Formulas ├── Type Formulas ├── Navigation Actions ├── Storage Actions ├── DOM Actions └── Utility Actions ``` -------------------------------- ### Get Action References from a ToddleComponent Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/06-toddlecomponent-class.md The 'actionReferences' getter returns a Set of strings representing all custom action handlers called within this component. This includes built-in and namespaced package actions. ```typescript get actionReferences(): Set ``` ```typescript const refs = toddleComponent.actionReferences // Returns: Set(['log', 'myPackage/send']) ``` -------------------------------- ### Remove Last N Elements from Array Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Creates a new array with the last N elements removed from the original array. Use this to get an array excluding a specified number of trailing items. ```typescript @toddle/dropLast(array: unknown[], count: number): unknown[] ``` -------------------------------- ### Nordcraft Core Architecture Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/INDEX.md Outlines the main modules and structure of the @nordcraft/core package. ```text @nordcraft/core ├── Component Structure ├── API Definition Types ├── Formula System ├── Styling └── Utils ``` -------------------------------- ### Remove First N Elements from Array Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Creates a new array with the first N elements removed from the original array. Use this to get the remainder of an array after skipping a certain number of initial items. ```typescript @toddle/drop(array: unknown[], count: number): unknown[] ``` -------------------------------- ### SSR Package Type Definitions Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/09-complete-types-reference.md Defines type aliases and interfaces for project files, API services, routes, and installed packages within the SSR package. Use these types to ensure type safety when working with project configurations and data structures. ```typescript // Type Aliases type FileGetter = (args: { package?: string name: string type: keyof ProjectFiles }) => Promise | Route | Theme | ApiService> type ApiService = | ContentfulApiService | CustomApiService | DatoCmsApiService | SupabaseApiService | UmbracoApiService | XanoApiService type Route = RewriteRoute | RedirectRoute type InstalledPackage = Pick & { manifest: { name: string; commit: string } } // Interfaces interface ToddleProject { name: string description?: string | null short_id: string id: string type: 'app' | 'package' thumbnail?: { path: string } | null } interface ProjectFiles { components: Partial> packages?: Partial> actions?: Record formulas?: Record> routes?: Record config?: { runtimeVersion?: string theme?: OldTheme meta?: { icon?: { formula: Formula } robots?: { formula: Formula } sitemap?: { formula: Formula } manifest?: { formula: Formula } serviceWorker?: { formula: Formula } } } themes?: Record services?: Record } interface BaseApiService { name: string baseUrl?: Formula docsUrl?: Formula apiKey?: Formula meta?: Record } interface SupabaseApiService extends BaseApiService { type: 'supabase' meta?: { projectUrl?: Formula } } interface XanoApiService extends BaseApiService { type: 'xano' } interface DatoCmsApiService extends BaseApiService { type: 'datocms' } interface UmbracoApiService extends BaseApiService { type: 'umbraco' } interface ContentfulApiService extends BaseApiService { type: 'contentful' } interface CustomApiService extends BaseApiService { type: 'custom' } interface BaseRoute { source: RouteDeclaration destination: ApiBase enabled?: { formula: Formula } } interface RewriteRoute extends BaseRoute { type: 'rewrite' } interface RedirectRoute extends BaseRoute { type: 'redirect' status?: RedirectStatusCode } ``` -------------------------------- ### Global window.__toddle Object Structure Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/04-runtime-reference.md This object must be available on `window.__toddle` before `initGlobalObject()` is called. It contains project, branch, commit, and component information, typically injected by the server during SSR or by a bundler. ```typescript { project: string // Project ID branch: string // Branch name commit: string // Commit hash component: Component // Root component components: Component[] // All components pageState: ComponentData // Initial page state } ``` -------------------------------- ### Navigate to URL Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/QUICK-REFERENCE.md Navigates the user to a specified URL. Can optionally open the URL in a new tab. ```typescript @toddle/gotToURL(url, { openInNewTab: boolean }) ``` -------------------------------- ### Set Theme Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Changes the current theme of the application. Pass `null` to unset the theme. ```typescript @toddle/setTheme(themeName: string | null) ``` -------------------------------- ### Runtime Configuration Object Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/README.md Represents the global runtime object available in the browser's window, providing access to project details, registered components, and functions for registering and retrieving formulas and actions. This is the entry point for interacting with the engine's core functionalities. ```typescript window.toddle = { project: string branch: string commit: string components: Component[] registerFormula(name, handler) registerAction(name, handler) getFormula(name) getAction(name) // ... more } ``` -------------------------------- ### Std-lib Package Imports Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/INDEX.md Import formulas and actions modules from the '@nordcraft/std-lib' package. ```typescript import * as formulas from '@nordcraft/std-lib/dist/formulas' import * as actions from '@nordcraft/std-lib/dist/actions' ``` -------------------------------- ### Clipboard Actions Source: https://github.com/nordcraftengine/nordcraft/blob/main/_autodocs/08-standard-library-reference.md Actions for interacting with the system clipboard. ```APIDOC ## copyToClipboard ### Description Copies the provided text to the system clipboard. ### Method Signature ```typescript @toddle/copyToClipboard(text: string): Promise ``` ### Parameters #### Path Parameters - **text** (string) - Required - The text to copy to the clipboard. ### Returns A Promise that resolves when the text has been copied. ```