Desarrollo tempranoPre-1.0: la sintaxis puede cambiar.Historial de versionesGitHub
Constructor de APIs REST y Autenticación

Rune API Studio: Constructor visual de APIs REST y Auth

Diseña endpoints REST tipados, configura 7 esquemas nativos @Authentication con RBAC, scopes y límites de tasa, simula peticiones en vivo y exporta .rune válido + OpenAPI 3.0.

Ver código fuente

Licencia de la herramienta

api_studio.rune
#!RUNE

import "parts"

@App
name = RuneApiStudio
version = 1.0
type = REST
port = 3003

@Frontend
type = rune-web
path = %ROOT%
page = api_studio

@Page/api_studio
title = Rune API Studio — REST API & Auth Builder
style = api_studio
logic = api_studio
on_mount = initApiStudio
view:
    main .wb-shell:
        ApiStudioHeader
        ApiProjectBar
        div class="{wb_layout_cls}":
            if has_sidebar:
                ApiSidebar
            ApiEditorPanel
            if show_code_panel:
                ApiOutputCabinet
parts/components/auth_editor.rune
@Component/ApiAuthEditor
view:
    div .wb-view:
        if show_add_auth_picker:
            div .wb-picker-panel:
                div .wb-card-header:
                    div:
                        h3 .wb-card-title "Choose an Authentication Method"
                        p .wb-card-hint "Click any of Vectrune’s 7 built-in schemes to add it to your API."
                    button .wb-btn-subtle type=button click="toggleAddAuthPicker" "Cancel"
                div .wb-picker-grid:
                    button .wb-picker-card type=button click="addAuthScheme('jwt')":
                        span .wb-scheme-badge .scheme-jwt "JWT"
                        strong "JWT Bearer Token"
                        span .wb-picker-desc "Best for user logins & SPAs (HS256/RS256/ES256, OIDC JWKS, optional /auth/token)."
                    button .wb-picker-card type=button click="addAuthScheme('oauth2')":
                        span .wb-scheme-badge .scheme-oauth2 "OAuth2"
                        strong "OAuth 2.0 / OIDC"
                        span .wb-picker-desc "Validate external IdP access tokens via RFC 7662 introspection or JWKS."
                    button .wb-picker-card type=button click="addAuthScheme('api_key')":
                        span .wb-scheme-badge .scheme-api_key "API Key"
                        strong "API Key (Header / Query)"
                        span .wb-picker-desc "Great for B2B partners & developer portals with per-key scopes."
                    button .wb-picker-card type=button click="addAuthScheme('basic')":
                        span .wb-scheme-badge .scheme-basic "Basic"
                        strong "HTTP Basic Auth"
                        span .wb-picker-desc "Simple username/password with WWW-Authenticate realm & sha256: hashes."
                    button .wb-picker-card type=button click="addAuthScheme('bearer')":
                        span .wb-scheme-badge .scheme-bearer "Bearer"
                        strong "Opaque Bearer Token"
                        span .wb-picker-desc "Static machine-to-machine tokens with constant-time verification."
                    button .wb-picker-card type=button click="addAuthScheme('hmac')":
                        span .wb-scheme-badge .scheme-hmac "HMAC"
                        strong "HMAC-SHA256 Webhook"
                        span .wb-picker-desc "Verify signed webhook payloads from Stripe, GitHub, or internal queues."
                    button .wb-picker-card type=button click="addAuthScheme('cookie')":
                        span .wb-scheme-badge .scheme-cookie "Cookie"
                        strong "Signed Session Cookie"
                        span .wb-picker-desc "Browser session authentication via HMAC-signed or token-backed cookies."

        if !has_selected_auth and !show_add_auth_picker:
            div .wb-empty-state:
                h2 "No authentication methods yet"
                p "Add JWT, OAuth 2.0, API Keys, HTTP Basic, Bearer tokens, HMAC webhooks, or Session Cookies."
                button .wb-btn-primary type=button click="toggleAddAuthPicker" "+ Add Authentication Method"

        if has_selected_auth:
            div .wb-view-head:
                div:
                    span .wb-eyebrow "AUTHENTICATION · {sel_auth_title}"
                    h2 .wb-view-title "@Authentication/{sel_auth_name}"
                    p .wb-view-desc "{sel_auth_desc}"
                button .wb-btn-danger type=button click="deleteSelectedAuth" "Delete"

            div .wb-section-card:
                h3 .wb-card-title "Identity & Scheme Type"
                div .wb-form-grid:
                    label .wb-field:
                        span .wb-label "Scheme Name (referenced by routes)"
                        input .wb-input .wb-mono type=text value="{selected_auth.name}" data-preserve-draft=true on_input="updateAuthField(['name', this.value])"
                    label .wb-field:
                        span .wb-label "Scheme Type"
                        select .wb-select change="updateAuthField(['type', this.value])":
                            option value=jwt selected="{selected_auth.type == 'jwt'}" "JWT Bearer (HS256/RS256/ES256/JWKS)"
                            option value=oauth2 selected="{selected_auth.type == 'oauth2'}" "OAuth 2.0 / OIDC Introspection"
                            option value=api_key selected="{selected_auth.type == 'api_key'}" "API Key (Header / Query)"
                            option value=basic selected="{selected_auth.type == 'basic'}" "HTTP Basic Auth"
                            option value=bearer selected="{selected_auth.type == 'bearer'}" "Opaque Bearer Token"
                            option value=hmac selected="{selected_auth.type == 'hmac'}" "HMAC-SHA256 Webhook Signature"
                            option value=cookie selected="{selected_auth.type == 'cookie'}" "Signed Session Cookie"

            if sel_auth_type == 'jwt':
                div .wb-section-card:
                    h3 .wb-card-title "JWT Verification & Token Issuer"
                    div .wb-form-grid:
                        label .wb-field:
                            span .wb-label "Signing Algorithm"
                            select .wb-select change="updateAuthField(['algorithm', this.value])":
                                option value=HS256 selected="{selected_auth.algorithm == 'HS256'}" "HS256 (HMAC-SHA256)"
                                option value=HS384 selected="{selected_auth.algorithm == 'HS384'}" "HS384 (HMAC-SHA384)"
                                option value=HS512 selected="{selected_auth.algorithm == 'HS512'}" "HS512 (HMAC-SHA512)"
                                option value=RS256 selected="{selected_auth.algorithm == 'RS256'}" "RS256 (RSA Public Key / JWKS)"
                                option value=ES256 selected="{selected_auth.algorithm == 'ES256'}" "ES256 (ECDSA P-256 / JWKS)"
                        label .wb-field:
                            span .wb-label "Token Endpoint (optional POST issuer)"
                            input .wb-input .wb-mono type=text placeholder="/auth/token" value="{selected_auth.token_endpoint}" data-preserve-draft=true on_input="updateAuthField(['token_endpoint', this.value])"
                        label .wb-field:
                            span .wb-label "Shared Secret (for HS*)"
                            input .wb-input .wb-mono type=text value="{selected_auth.secret}" data-preserve-draft=true on_input="updateAuthField(['secret', this.value])"
                        label .wb-field:
                            span .wb-label "JWKS URL (for OIDC / RS256 / ES256)"
                            input .wb-input .wb-mono type=text placeholder="https://idp.example.com/.well-known/jwks.json" value="{selected_auth.jwks_url}" data-preserve-draft=true on_input="updateAuthField(['jwks_url', this.value])"
                        label .wb-field:
                            span .wb-label "Issuer (iss)"
                            input .wb-input type=text value="{selected_auth.issuer}" data-preserve-draft=true on_input="updateAuthField(['issuer', this.value])"
                        label .wb-field:
                            span .wb-label "Audience (aud)"
                            input .wb-input type=text value="{selected_auth.audience}" data-preserve-draft=true on_input="updateAuthField(['audience', this.value])"
                        label .wb-field:
                            span .wb-label "Expiration (seconds)"
                            input .wb-input type=number value="{selected_auth.expiration}" on_input="updateAuthField(['expiration', this.value])"
                        label .wb-field:
                            span .wb-label "Clock Leeway (seconds)"
                            input .wb-input type=number value="{selected_auth.leeway}" on_input="updateAuthField(['leeway', this.value])"

            if sel_auth_type == 'oauth2':
                div .wb-section-card:
                    h3 .wb-card-title "OAuth 2.0 & OIDC Provider"
                    div .wb-form-grid:
                        label .wb-field:
                            span .wb-label "RFC 7662 Introspection URL"
                            input .wb-input .wb-mono type=text placeholder="https://idp.example.com/oauth/introspect" value="{selected_auth.introspection_url}" data-preserve-draft=true on_input="updateAuthField(['introspection_url', this.value])"
                        label .wb-field:
                            span .wb-label "JWKS URL (JWT access tokens)"
                            input .wb-input .wb-mono type=text placeholder="https://idp.example.com/.well-known/jwks.json" value="{selected_auth.jwks_url}" data-preserve-draft=true on_input="updateAuthField(['jwks_url', this.value])"
                        label .wb-field:
                            span .wb-label "Client ID"
                            input .wb-input .wb-mono type=text value="{selected_auth.client_id}" data-preserve-draft=true on_input="updateAuthField(['client_id', this.value])"
                        label .wb-field:
                            span .wb-label "Client Secret"
                            input .wb-input .wb-mono type=text value="{selected_auth.client_secret}" data-preserve-draft=true on_input="updateAuthField(['client_secret', this.value])"
                        label .wb-field:
                            span .wb-label "Authorization URL (OpenAPI)"
                            input .wb-input .wb-mono type=text value="{selected_auth.authorization_url}" data-preserve-draft=true on_input="updateAuthField(['authorization_url', this.value])"
                        label .wb-field:
                            span .wb-label "Token URL (OpenAPI)"
                            input .wb-input .wb-mono type=text value="{selected_auth.token_url}" data-preserve-draft=true on_input="updateAuthField(['token_url', this.value])"

            if sel_auth_type == 'api_key':
                div .wb-section-card:
                    h3 .wb-card-title "API Key Delivery"
                    div .wb-form-grid:
                        label .wb-field:
                            span .wb-label "HTTP Header Name"
                            input .wb-input .wb-mono type=text value="{selected_auth.header}" data-preserve-draft=true on_input="updateAuthField(['header', this.value])"
                        label .wb-field:
                            span .wb-label "Optional Query Parameter"
                            input .wb-input .wb-mono type=text placeholder="api_key" value="{selected_auth.query}" data-preserve-draft=true on_input="updateAuthField(['query', this.value])"

            if sel_auth_type == 'basic':
                div .wb-section-card:
                    h3 .wb-card-title "HTTP Basic Challenge"
                    label .wb-field:
                        span .wb-label "WWW-Authenticate Realm"
                        input .wb-input type=text value="{selected_auth.realm}" data-preserve-draft=true on_input="updateAuthField(['realm', this.value])"

            if sel_auth_type == 'hmac':
                div .wb-section-card:
                    h3 .wb-card-title "HMAC-SHA256 Signature Verification"
                    div .wb-form-grid:
                        label .wb-field:
                            span .wb-label "Signature Header"
                            input .wb-input .wb-mono type=text value="{selected_auth.header}" data-preserve-draft=true on_input="updateAuthField(['header', this.value])"
                        label .wb-field:
                            span .wb-label "Webhook Signing Secret"
                            input .wb-input .wb-mono type=text value="{selected_auth.secret}" data-preserve-draft=true on_input="updateAuthField(['secret', this.value])"
                        label .wb-field:
                            span .wb-label "Header Prefix"
                            input .wb-input .wb-mono type=text placeholder="sha256=" value="{selected_auth.prefix}" data-preserve-draft=true on_input="updateAuthField(['prefix', this.value])"
                        label .wb-field:
                            span .wb-label "Digest Encoding"
                            select .wb-select change="updateAuthField(['encoding', this.value])":
                                option value=hex selected="{selected_auth.encoding == 'hex'}" "hex (lowercase)"
                                option value=base64 selected="{selected_auth.encoding == 'base64'}" "base64"
                        label .wb-field:
                            span .wb-label "Caller Subject (auth.sub)"
                            input .wb-input type=text value="{selected_auth.sub}" data-preserve-draft=true on_input="updateAuthField(['sub', this.value])"
                        label .wb-field:
                            span .wb-label "Granted Scopes"
                            input .wb-input type=text value="{selected_auth.scopes}" data-preserve-draft=true on_input="updateAuthField(['scopes', this.value])"

            if sel_auth_type == 'cookie':
                div .wb-section-card:
                    h3 .wb-card-title "Session Cookie Settings"
                    div .wb-form-grid:
                        label .wb-field:
                            span .wb-label "Cookie Name"
                            input .wb-input .wb-mono type=text value="{selected_auth.cookie_name}" data-preserve-draft=true on_input="updateAuthField(['cookie_name', this.value])"
                        label .wb-field:
                            span .wb-label "HMAC Signing Secret"
                            input .wb-input .wb-mono type=text value="{selected_auth.secret}" data-preserve-draft=true on_input="updateAuthField(['secret', this.value])"

            if sel_auth_type != 'hmac':
                div .wb-section-card:
                    div .wb-card-header:
                        h3 .wb-card-title:
                            if sel_auth_type == 'jwt' or sel_auth_type == 'basic':
                                "Configured Users & Permissions"
                            if sel_auth_type == 'api_key':
                                "Configured API Keys & Permissions"
                            if sel_auth_type == 'oauth2' or sel_auth_type == 'bearer' or sel_auth_type == 'cookie':
                                "Configured Tokens & Permissions"
                        span .wb-card-hint "Used by runtime validation and the Try It simulator"
                    div .wb-table-list:
                        for e in sel_auth_entries:
                            div .wb-cred-item:
                                div .wb-cred-primary:
                                    span .wb-mono-bold "{e.k}"
                                    span .wb-cred-arrow "→ {e.v}"
                                div .wb-cred-badges:
                                    if e.roles != "":
                                        span .wb-role-badge "roles: {e.roles}"
                                    if e.scopes != "":
                                        span .wb-scope-badge "scopes: {e.scopes}"
                                button .wb-btn-ghost-danger type=button click="removeAuthEntry(e.k)" "Remove"
                    div .wb-cred-form:
                        input .wb-input type=text placeholder="username / key / token" value="{new_cred_a}" data-preserve-draft=true on_input="setNewCredA(this.value)"
                        input .wb-input type=text placeholder="password / subject" value="{new_cred_b}" data-preserve-draft=true on_input="setNewCredB(this.value)"
                        input .wb-input type=text placeholder="roles (admin, user)" value="{new_cred_roles}" data-preserve-draft=true on_input="setNewCredRoles(this.value)"
                        input .wb-input type=text placeholder="scopes (orders:read)" value="{new_cred_scopes}" data-preserve-draft=true on_input="setNewCredScopes(this.value)"
                        button .wb-btn-primary type=button click="addAuthEntry" "+ Add"
parts/components/editor_panel.rune
@Component/ApiEditorPanel
view:
    section .wb-stage aria-label="Main editor workspace":
        if active_section == 'route':
            if !is_graphql:
                ApiRouteEditor
            if is_graphql:
                ApiResolverEditor

        if active_section == 'auth':
            ApiAuthEditor

        if active_section == 'schema':
            div .wb-view:
                if !has_selected_schema:
                    div .wb-empty-state:
                        h2 "No data model selected"
                        p "Create a @Schema model to document request payloads in OpenAPI 3.0 and validate incoming bodies."
                        button .wb-btn-primary type=button click="addSchema" "+ Create Data Model"
                if has_selected_schema:
                    div .wb-view-head:
                        div:
                            span .wb-eyebrow "DATA MODEL · @Schema"
                            h2 .wb-view-title "{sel_schema_name}"
                            p .wb-view-desc "Attach this model to any POST, PUT, PATCH, or CRUD endpoint to auto-generate OpenAPI request schemas."
                        button .wb-btn-danger type=button click="deleteSelectedSchema" "Delete Model"

                    div .wb-section-card:
                        label .wb-field:
                            span .wb-label "Model Name"
                            input .wb-input type=text value="{sel_schema_name}" data-preserve-draft=true change="renameSelectedSchema(this.value)"

                    div .wb-section-card:
                        div .wb-card-header:
                            h3 .wb-card-title "Fields ({sel_schema_fields.length})"
                            span .wb-card-hint "Primitive types supported by native validate & OpenAPI"
                        div .wb-table-list:
                            for f in sel_schema_fields:
                                div .wb-table-row:
                                    span .wb-mono-bold "{f.name}"
                                    span .wb-type-pill "{f.type}"
                                    button .wb-btn-ghost-danger type=button click="removeSchemaField(f.name)" "Remove"
                        div .wb-inline-form:
                            input .wb-input type=text placeholder="Add field name (e.g. email)" value="{new_field_name}" data-preserve-draft=true on_input="setNewFieldName(this.value)"
                            select .wb-select-sm change="setNewFieldType(this.value)":
                                option value=string selected="{new_field_type == 'string'}" "string"
                                option value=number selected="{new_field_type == 'number'}" "number"
                                option value=bool selected="{new_field_type == 'bool'}" "bool"
                            button .wb-btn-primary type=button click="addSchemaField" "+ Add Field"

        if active_section == 'app':
            div .wb-view .wb-view-wide:
                div .wb-view-head:
                    div:
                        span .wb-eyebrow "SERVER CONFIGURATION · @App"
                        h2 .wb-view-title "{app_name} v{app_version}"
                        p .wb-view-desc "Set the defaults inherited by every endpoint: default authentication, CORS headers, OpenAPI docs, and global rate limiting."

                div .wb-two-col:
                    div .wb-section-card:
                        h3 .wb-card-title "General & Default Auth"
                        div .wb-form-grid:
                            label .wb-field:
                                span .wb-label "API Name"
                                input .wb-input type=text value="{app_name}" data-preserve-draft=true on_input="setAppName(this.value)"
                            label .wb-field:
                                span .wb-label "Version"
                                input .wb-input type=text value="{app_version}" data-preserve-draft=true on_input="setAppVersion(this.value)"
                            label .wb-field:
                                span .wb-label "Listen Port"
                                input .wb-input type=number value="{app_port}" on_input="setAppPort(this.value)"
                            label .wb-field:
                                span .wb-label "Default Auth Policy"
                                select .wb-select change="setDefaultAuth(this.value)":
                                    option value=none selected="{default_auth == 'none'}" "None (endpoints are public unless set)"
                                    for a in auth_schemes:
                                        option value="{a.name}" selected="{default_auth == a.name}" "{a.name} ({a.type})"
                        if !is_graphql:
                            label .wb-toggle-row:
                                input type=checkbox checked="{swagger_enabled}" change="toggleSwagger"
                                span "Expose OpenAPI 3.0 JSON (/openapi.json) and Swagger UI (/swagger-ui)"

                    div .wb-section-card:
                        h3 .wb-card-title "CORS (Cross-Origin Requests)"
                        label .wb-field:
                            span .wb-label "Browser Access Policy"
                            select .wb-select change="setCorsMode(this.value)":
                                option value=off selected="{cors_mode == 'off'}" "Disabled (same-origin only)"
                                option value=all selected="{cors_mode == 'all'}" "Allow All Origins (cors = true)"
                                option value=origins selected="{cors_mode == 'origins'}" "Allow Specific Origins"
                        if cors_mode == 'origins':
                            label .wb-field:
                                span .wb-label "Allowed Origins (comma-separated)"
                                input .wb-input type=text value="{cors_origins}" data-preserve-draft=true on_input="setCorsOrigins(this.value)"
                        p .wb-helper "Vectrune automatically injects Access-Control-Allow-* headers using tower-http CorsLayer."

                div .wb-section-card:
                    div .wb-card-header:
                        div:
                            h3 .wb-card-title "Global Rate Limiting"
                            p .wb-card-hint "Protects every endpoint unless overridden with rate_limit = none or a custom limit."
                        label .wb-toggle-row:
                            input type=checkbox checked="{rate_limit_enabled}" change="toggleRateLimit"
                            span "Enabled"
                    if rate_limit_enabled:
                        div .wb-form-grid-3:
                            label .wb-field:
                                span .wb-label "Max Requests"
                                input .wb-input type=number value="{rate_limit_requests}" on_input="setRateLimitRequests(this.value)"
                            label .wb-field:
                                span .wb-label "Time Window (seconds)"
                                input .wb-input type=number value="{rate_limit_window}" on_input="setRateLimitWindow(this.value)"
                            label .wb-field:
                                span .wb-label "Limit Bucket Key"
                                select .wb-select change="setRateLimitKey(this.value)":
                                    option value=ip selected="{rate_limit_key == 'ip'}" "Per Client IP (ip)"
                                    option value=auth selected="{rate_limit_key == 'auth'}" "Per Authenticated User (auth)"
                                    option value=global selected="{rate_limit_key == 'global'}" "Global Shared Bucket (global)"
                                    option value="header:X-Client-Id" selected="{rate_limit_key == 'header:X-Client-Id'}" "Header (header:X-Client-Id)"

                div .wb-callout:
                    span .wb-callout-tag "SECURITY SUMMARY"
                    p .wb-callout-text "{protected_route_count} of {route_count} endpoints require authentication · {auth_count} auth method(s) configured · Declarative TLS / mTLS transport support is proposed in docs/proposals/tls-and-mtls.md."

        if active_section == 'simulator':
            ApiSimulatorPanel
parts/components/header.rune
@Component/ApiStudioHeader
view:
    header .wb-topbar:
        div .wb-brand-group:
            div .wb-logo-mark "API"
            div .wb-brand-copy:
                div .wb-title-row:
                    h1 .wb-title "Rune API Studio"
                    div .wb-proto-switch role=group aria-label="API Protocol":
                        button .wb-proto-btn {.active when !is_graphql} type=button click="setApiProtocol('rest')" "REST"
                        button .wb-proto-btn {.active when is_graphql} type=button click="setApiProtocol('graphql')" "GraphQL"
            span .wb-divider ""
            label .wb-app-field for=as-app-name:
                span .wb-app-prefix "@App"
                input #as-app-name .wb-app-input type=text maxlength=48 value="{app_name}" data-preserve-draft=true on_input="setAppName(this.value)" aria-label="API name"
            label .wb-example-picker for=as-example-select:
                span .wb-app-prefix "Example"
                select #as-example-select .wb-preset-select aria-label="Choose API example or saved project" change="openSavedOrPreset(this.value)":
                    optgroup label="REST Examples":
                        option value=hello_world selected="{selected_preset == 'hello_world'}" "Hello World (Simple REST)"
                        option value=secure_orders selected="{selected_preset == 'secure_orders'}" "Secure Orders (JWT + OAuth2 + API Key)"
                        option value=saas_multi_auth selected="{selected_preset == 'saas_multi_auth'}" "SaaS Gateway (Basic + Key + Bearer + Cookie)"
                        option value=webhook_gateway selected="{selected_preset == 'webhook_gateway'}" "Webhook Gateway (HMAC-SHA256 + Bearer)"
                        option value=blank_rest selected="{selected_preset == 'blank_rest'}" "Minimal Auth Starter (JWT + Items)"
                    optgroup label="GraphQL Examples":
                        option value=book_graphql selected="{selected_preset == 'book_graphql'}" "Book Catalog (GraphQL + JWT + RBAC)"
                        option value=starter_graphql selected="{selected_preset == 'starter_graphql'}" "Hello GraphQL (Simple Starter)"
                    if selected_preset == "":
                        option value="" selected=true disabled=true "Imported project"
                    if saved_apis.length > 0:
                        optgroup label="Saved in Browser":
                            for entry in saved_apis:
                                option value="{entry.id}" selected="{selected_preset == entry.id}" "{entry.name}"

        div .wb-top-actions:
            button .wb-btn-icon type=button disabled="{!can_undo}" click="undoApiEdit" aria-label="Undo" "Undo"
            button .wb-btn-icon type=button disabled="{!can_redo}" click="redoApiEdit" aria-label="Redo" "Redo"
            button .wb-btn-subtle type=button click="saveApiToStorage" "Save"
            button .wb-btn-subtle {.active when show_code_panel} type=button click="toggleCodePanel":
                if show_code_panel:
                    "Hide Code"
                if !show_code_panel:
                    "Show Code"
            button .wb-btn-primary type=button click="downloadRuneSource" "Export .rune"
            button .wb-btn-icon type=button click="toggleFullscreen" aria-label="Toggle fullscreen":
                if is_fullscreen:
                    "Exit"
                if !is_fullscreen:
                    "Expand"
parts/components/output_cabinet.rune
@Component/ApiOutputCabinet
view:
    aside .wb-code-drawer aria-label="Live generated code, OpenAPI, tests, and import":
        div .wb-drawer-tabs:
            button .wb-drawer-tab {.active when active_output_tab == 'rune'} type=button click="setOutputTab('rune')" "Rune"
            button .wb-drawer-tab {.active when active_output_tab == 'openapi'} type=button click="setOutputTab('openapi')":
                if !is_graphql:
                    "OpenAPI 3.0"
                if is_graphql:
                    "GraphQL SDL"
            button .wb-drawer-tab {.active when active_output_tab == 'tests'} type=button click="setOutputTab('tests')" "@Test"
            button .wb-drawer-tab {.active when active_output_tab == 'import'} type=button click="setOutputTab('import')" "Import"

        if active_output_tab == 'rune':
            div .wb-drawer-toolbar:
                span .wb-drawer-hint "vectrune check & run ready"
                div .wb-drawer-actions:
                    button .wb-btn-code type=button click="copyRuneSource" "Copy"
                    button .wb-btn-code .accent type=button click="downloadRuneSource" "Download"
            pre .wb-drawer-pre tabindex=0 "{exported_rune}"

        if active_output_tab == 'openapi':
            if !is_graphql:
                div .wb-drawer-toolbar:
                    span .wb-drawer-hint "OpenAPI 3.0.3 · securitySchemes"
                    div .wb-drawer-actions:
                        button .wb-btn-code type=button click="copyOpenApiJson" "Copy"
                        button .wb-btn-code .accent type=button click="downloadOpenApiJson" "Download"
                pre .wb-drawer-pre tabindex=0 "{exported_openapi}"
            if is_graphql:
                div .wb-drawer-toolbar:
                    span .wb-drawer-hint "GraphQL Schema Definition Language"
                    div .wb-drawer-actions:
                        button .wb-btn-code type=button click="copyGraphqlSdl" "Copy"
                        button .wb-btn-code .accent type=button click="downloadGraphqlSdl" "Download"
                pre .wb-drawer-pre tabindex=0 "{exported_sdl}"

        if active_output_tab == 'tests':
            div .wb-drawer-toolbar:
                span .wb-drawer-hint "Save next to the exported API and run vectrune test."
                div .wb-drawer-actions:
                    button .wb-btn-code type=button click="copyTestSuite" "Copy"
                    button .wb-btn-code .accent type=button click="downloadTestSuite" "Download"
            pre .wb-drawer-pre tabindex=0 "{exported_tests}"

        if active_output_tab == 'import':
            div .wb-import-drawer:
                p .wb-drawer-hint "Paste an existing Vectrune REST or GraphQL .rune file to load its @App, @Authentication, @Schema, @Route, or @GraphQL sections."
                textarea #as-import-textarea .wb-import-area rows=14 data-preserve-draft=true placeholder="#!RUNE\n@App\nname = MyAPI\ntype = REST\nport = 8080\ndefault_auth = JWTAuth\n\n@Authentication/JWTAuth\ntype = jwt\nsecret = \"my-secret\"" on_input="setImportCode(this.value)" aria-label="Paste Rune REST API code" "{import_code}"
                button .wb-btn-primary type=button click="importApiRuneCode" "Import & Parse .rune"
parts/components/project_bar.rune
@Component/ApiProjectBar
view:
    nav .wb-stepbar aria-label="API Studio sections":
        div .wb-tabs:
            button .wb-tab {.active when active_section == 'route'} type=button click="setActiveSection('route')":
                span .wb-tab-num "1"
                if !is_graphql:
                    span "Endpoints"
                    span .wb-tab-count "{route_count}"
                if is_graphql:
                    span "Resolvers"
                    span .wb-tab-count "{resolver_count}"
            button .wb-tab {.active when active_section == 'auth'} type=button click="setActiveSection('auth')":
                span .wb-tab-num "2"
                span "Authentication"
                span .wb-tab-count "{auth_count}"
            button .wb-tab {.active when active_section == 'schema'} type=button click="setActiveSection('schema')":
                span .wb-tab-num "3"
                span "Data Models"
                span .wb-tab-count "{schema_count}"
            button .wb-tab {.active when active_section == 'app'} type=button click="setActiveSection('app')":
                span .wb-tab-num "4"
                span "Server & Limits"
            button .wb-tab .wb-tab-try {.active when active_section == 'simulator'} type=button click="setActiveSection('simulator')":
                span .wb-try-dot ""
                if !is_graphql:
                    span "Try It · Live Tester"
                if is_graphql:
                    span "Try It · GraphQL Console"

        div .wb-status-bar aria-live=polite:
            if !is_graphql:
                span .wb-posture-summary "{protected_route_count}/{route_count} protected"
            if is_graphql:
                span .wb-posture-summary "{resolver_count} resolvers · {default_auth == 'none' ? 'public' : default_auth}"
            span .wb-status-msg "{status_message}"
parts/components/resolver_editor.rune
@Component/ApiResolverEditor
view:
    div .wb-view:
        if !has_selected_resolver:
            div .wb-empty-state:
                h2 "No GraphQL resolver selected"
                p "Select a Query or Mutation from the left list, or create a new GraphQL resolver."
                div .wb-head-actions:
                    button .wb-btn-primary type=button click="addResolver('query')" "+ Query"
                    button .wb-btn-subtle type=button click="addResolver('mutation')" "+ Mutation"

        if has_selected_resolver:
            div .wb-view-head:
                div .wb-route-headline:
                    span class="wb-method wb-method-lg {sel_resolver_cls}" "{sel_resolver_badge}"
                    h2 .wb-view-title "{sel_resolver_name}"
                div .wb-head-actions:
                    button .wb-btn-try type=button click="openResolverInSimulator(selected_resolver_id)" "▶ Try in GraphQL Console"
                    button .wb-btn-danger type=button click="deleteSelectedResolver" "Delete"

            div .wb-pipeline aria-label="GraphQL resolver pipeline":
                div .wb-pipe-step:
                    span .wb-pipe-label "1. Endpoint"
                    span .wb-pipe-val "POST /graphql"
                span .wb-pipe-arrow "→"
                div .wb-pipe-step:
                    span .wb-pipe-label "2. Auth"
                    span .wb-pipe-val "{default_auth}"
                span .wb-pipe-arrow "→"
                div .wb-pipe-step:
                    span .wb-pipe-label "3. Access"
                    span .wb-pipe-val "{sel_resolver_access_pill}"
                span .wb-pipe-arrow "→"
                div .wb-pipe-step:
                    span .wb-pipe-label "4. Returns"
                    span .wb-pipe-val "{sel_resolver_ret}"

            div .wb-section-card:
                h3 .wb-card-title "Resolver Signature"
                div .wb-form-grid-3:
                    label .wb-field:
                        span .wb-label "Operation Kind"
                        select .wb-select change="updateResolverField(['kind', this.value])":
                            option value=query selected="{sel_resolver_kind == 'query'}" "Query (read)"
                            option value=mutation selected="{sel_resolver_kind == 'mutation'}" "Mutation (write)"
                    label .wb-field:
                        span .wb-label "Field Name"
                        input .wb-input .wb-mono type=text value="{sel_resolver_name}" data-preserve-draft=true on_input="updateResolverField(['name', this.value])"
                    label .wb-field:
                        span .wb-label "Return Type (@Schema)"
                        select .wb-select change="updateResolverField(['return_type', this.value])":
                            option value=JSON selected="{sel_resolver_return_type == 'JSON' or sel_resolver_return_type == ''}" "JSON (dynamic)"
                            for s in schemas:
                                option value="{s.name}" selected="{sel_resolver_return_type == s.name}" "{s.name}"

            div .wb-section-card:
                div .wb-card-header:
                    h3 .wb-card-title "Arguments ({sel_resolver_args.length})"
                    span .wb-card-hint "Bound directly as variables inside the resolver steps"
                div .wb-table-list:
                    for a in sel_resolver_args:
                        div .wb-table-row:
                            span .wb-mono-bold "{a.name}"
                            span .wb-type-pill "{a.type}"
                            button .wb-btn-ghost-danger type=button click="removeResolverArg(a.name)" "Remove"
                div .wb-inline-form:
                    input .wb-input type=text placeholder="arg name (e.g. title)" value="{new_arg_name}" data-preserve-draft=true on_input="setNewArgName(this.value)"
                    select .wb-select-sm change="setNewArgType(this.value)":
                        option value=string selected="{new_arg_type == 'string'}" "string"
                        option value=number selected="{new_arg_type == 'number'}" "number"
                        option value=bool selected="{new_arg_type == 'bool'}" "bool"
                    button .wb-btn-primary type=button click="addResolverArg" "+ Add Arg"

            div .wb-section-card:
                div .wb-card-header:
                    div:
                        h3 .wb-card-title "Resolver Authorization (RBAC & Scopes)"
                        p .wb-card-hint "Enforced per resolver after @App default_auth authenticates POST /graphql."
                div .wb-form-grid:
                    label .wb-field:
                        span .wb-label "Allowed Roles (any match → Forbidden)"
                        input .wb-input type=text placeholder="e.g. admin" value="{sel_resolver_roles}" data-preserve-draft=true on_input="updateResolverField(['roles', this.value])"
                    label .wb-field:
                        span .wb-label "Required Scopes (all required → Forbidden)"
                        input .wb-input type=text placeholder="e.g. books:write" value="{sel_resolver_scopes}" data-preserve-draft=true on_input="updateResolverField(['scopes', this.value])"

            div .wb-section-card:
                div .wb-card-header:
                    div:
                        h3 .wb-card-title "Resolver Steps"
                        p .wb-card-hint "Use memory.get, memory.append, auth.sub, and arguments directly."
                    div .wb-snippet-bar:
                        button .wb-btn-chip type=button click="applyResolverSnippet('mem_list')" "Memory List"
                        button .wb-btn-chip type=button click="applyResolverSnippet('mem_find')" "Memory Find"
                        button .wb-btn-chip type=button click="applyResolverSnippet('auth_echo')" "Echo Auth"
                textarea id="as-resolver-steps-{selected_resolver_id}" .wb-code-area rows=5 data-preserve-draft=true on_input="updateResolverField(['steps', this.value])" "{sel_resolver_steps}"
parts/components/route_editor.rune
@Component/ApiRouteEditor
view:
    div .wb-view:
        if !has_selected_route:
            div .wb-empty-state:
                h2 "No endpoint selected"
                p "Select an endpoint from the left list or create a new REST route."
                button .wb-btn-primary type=button click="addRoute" "+ Create Endpoint"

        if has_selected_route:
            div .wb-view-head:
                div .wb-route-headline:
                    span class="wb-method wb-method-lg {sel_route_method_cls}" "{sel_route_method}"
                    h2 .wb-view-title "{sel_route_path}"
                div .wb-head-actions:
                    button .wb-btn-try type=button click="openRouteInSimulator(selected_route_id)" "▶ Try This Endpoint"
                    button .wb-btn-danger type=button click="deleteSelectedRoute" "Delete"

            div .wb-pipeline aria-label="Request execution pipeline":
                div .wb-pipe-step:
                    span .wb-pipe-label "1. Auth"
                    span .wb-pipe-val {.is-public when sel_route_is_public} "{sel_route_auth_pill}"
                span .wb-pipe-arrow "→"
                div .wb-pipe-step:
                    span .wb-pipe-label "2. Access"
                    span .wb-pipe-val "{sel_route_access_pill}"
                span .wb-pipe-arrow "→"
                div .wb-pipe-step:
                    span .wb-pipe-label "3. Rate Limit"
                    span .wb-pipe-val "{sel_route_rl_pill}"
                span .wb-pipe-arrow "→"
                div .wb-pipe-step:
                    span .wb-pipe-label "4. Handler"
                    span .wb-pipe-val "run: (with auth.*)"

            div .wb-section-card:
                h3 .wb-card-title "Endpoint Basics"
                div .wb-form-grid-3:
                    label .wb-field:
                        span .wb-label "HTTP Method"
                        select .wb-select change="updateRouteField(['method', this.value])":
                            option value=GET selected="{sel_route_method == 'GET'}" "GET"
                            option value=POST selected="{sel_route_method == 'POST'}" "POST"
                            option value=PUT selected="{sel_route_method == 'PUT'}" "PUT"
                            option value=PATCH selected="{sel_route_method == 'PATCH'}" "PATCH"
                            option value=DELETE selected="{sel_route_method == 'DELETE'}" "DELETE"
                            option value=CRUD selected="{sel_route_method == 'CRUD'}" "CRUD (auto REST)"
                    label .wb-field:
                        span .wb-label "URL Path"
                        input .wb-input .wb-mono type=text value="{sel_route_path}" data-preserve-draft=true on_input="updateRouteField(['path', this.value])"
                    label .wb-field:
                        span .wb-label "Body / CRUD Schema"
                        select .wb-select change="updateRouteField(['expect', this.value])":
                            option value="" selected="{sel_route_expect == ''}" "None"
                            for s in schemas:
                                option value="{s.name}" selected="{sel_route_expect == s.name}" "{s.name}"

                if sel_route_method == "CRUD":
                    p .wb-helper "To run CRUD, add a @DataSource and bind it with data_source in the exported .rune file."

            div .wb-section-card:
                div .wb-card-header:
                    div:
                        h3 .wb-card-title "Who Can Call This Endpoint?"
                        p .wb-card-hint "Choose default auth, make it public, or allow multiple auth schemes (OR fallback)."
                div .wb-segmented:
                    button .wb-seg-btn {.active when sel_route_auth_mode == 'inherit'} type=button click="updateRouteField(['auth_mode', 'inherit'])" "Use Default ({default_auth})"
                    button .wb-seg-btn {.active when sel_route_auth_mode == 'none'} type=button click="updateRouteField(['auth_mode', 'none'])" "Public (No Auth)"
                    button .wb-seg-btn {.active when sel_route_auth_mode == 'custom'} type=button click="updateRouteField(['auth_mode', 'custom'])" "Choose Schemes"
                if sel_route_auth_mode == 'custom':
                    if sel_route_auth_schemes.length == 0:
                        p .wb-helper "Select a scheme to protect this endpoint. With no schemes selected, the endpoint is public."
                    div .wb-chip-picker:
                        for st in sel_route_scheme_toggles:
                            button .wb-check-chip {.active when st.active} type=button click="toggleRouteAuthScheme(st.name)":
                                span .wb-chip-dot ""
                                span .wb-chip-label "{st.name}"
                                span .wb-chip-type "{st.badge}"
                if sel_route_auth_mode != 'none':
                    div .wb-form-grid:
                        label .wb-field:
                            span .wb-label "Allowed Roles (caller needs any one → 403)"
                            input .wb-input type=text placeholder="e.g. admin, editor" value="{sel_route_roles}" data-preserve-draft=true on_input="updateRouteField(['roles', this.value])"
                        label .wb-field:
                            span .wb-label "Required Scopes (caller needs all → 403)"
                            input .wb-input type=text placeholder="e.g. orders:read, orders:write" value="{sel_route_scopes}" data-preserve-draft=true on_input="updateRouteField(['scopes', this.value])"

            div .wb-section-card:
                div .wb-card-header:
                    div:
                        h3 .wb-card-title "Rate Limit Override"
                        p .wb-card-hint "Inherit the global @App limit, exempt this route, or set a stricter burst limit."
                div .wb-segmented:
                    button .wb-seg-btn {.active when sel_route_rl_mode == 'inherit'} type=button click="updateRouteField(['rl_mode', 'inherit'])" "Inherit Global"
                    button .wb-seg-btn {.active when sel_route_rl_mode == 'none'} type=button click="updateRouteField(['rl_mode', 'none'])" "No Limit (Exempt)"
                    button .wb-seg-btn {.active when sel_route_rl_mode == 'custom'} type=button click="updateRouteField(['rl_mode', 'custom'])" "Custom Limit"
                if sel_route_rl_mode == 'custom':
                    div .wb-form-grid-3:
                        label .wb-field:
                            span .wb-label "Requests"
                            input .wb-input type=number value="{sel_route_rl_requests}" on_input="updateRouteField(['rl_requests', this.value])"
                        label .wb-field:
                            span .wb-label "Window (sec)"
                            input .wb-input type=number value="{sel_route_rl_window}" on_input="updateRouteField(['rl_window', this.value])"
                        label .wb-field:
                            span .wb-label "Bucket Key"
                            select .wb-select change="updateRouteField(['rl_key', this.value])":
                                option value=ip selected="{sel_route_rl_key == 'ip'}" "Client IP (ip)"
                                option value=auth selected="{sel_route_rl_key == 'auth'}" "Caller Identity (auth)"
                                option value=global selected="{sel_route_rl_key == 'global'}" "Global (global)"
                                option value="header:X-Client-Id" selected="{sel_route_rl_key == 'header:X-Client-Id'}" "Header (X-Client-Id)"

            if sel_route_method != 'CRUD':
                div .wb-section-card:
                    div .wb-card-header:
                        div:
                            h3 .wb-card-title "Response Logic (run:)"
                            p .wb-card-hint "Access auth.sub, auth.scheme, auth.roles, auth.scopes, and body directly."
                        div .wb-snippet-bar:
                            button .wb-btn-chip type=button click="applyRouteSnippet('auth_echo')" "Echo Caller"
                            button .wb-btn-chip type=button click="applyRouteSnippet('create_echo')" "Create Resource"
                            button .wb-btn-chip type=button click="applyRouteSnippet('patch_echo')" "Patch Resource"
                    textarea id="as-route-steps-{selected_route_id}" .wb-code-area rows=4 data-preserve-draft=true on_input="updateRouteField(['steps', this.value])" "{sel_route_steps}"
parts/components/sidebar.rune
@Component/ApiSidebar
view:
    aside .wb-list-pane aria-label="Section items":
        if active_section == 'route':
            if !is_graphql:
                div .wb-list-head:
                    div:
                        h2 .wb-list-title "Endpoints"
                        p .wb-list-sub "Click an endpoint to configure security & response."
                    button .wb-btn-add type=button click="addRoute" "+ Endpoint"
                div .wb-list-items:
                    for row in route_rows:
                        button .wb-item-card {.selected when row.selected} type=button click="selectRoute(row.id)":
                            div .wb-item-top:
                                span class="wb-method {row.method_cls}" "{row.method}"
                                span .wb-item-path "{row.path}"
                            div .wb-item-foot:
                                span .wb-lock-pill {.public when row.is_public} "{row.lock}"
            if is_graphql:
                div .wb-list-head:
                    div:
                        h2 .wb-list-title "Resolvers"
                        p .wb-list-sub "Queries & Mutations on /graphql."
                    div .wb-add-group:
                        button .wb-btn-add type=button click="addResolver('query')" "+ Query"
                        button .wb-btn-add type=button click="addResolver('mutation')" "+ Mut"
                div .wb-list-items:
                    for row in resolver_rows:
                        button .wb-item-card {.selected when row.selected} type=button click="selectResolver(row.id)":
                            div .wb-item-top:
                                span class="wb-method {row.cls}" "{row.badge}"
                                span .wb-item-path "{row.name}"
                            div .wb-item-foot:
                                span .wb-item-meta ": {row.ret}"
                                span .wb-lock-pill "{row.lock}"

        if active_section == 'auth':
            div .wb-list-head:
                div:
                    h2 .wb-list-title "Auth Methods"
                    p .wb-list-sub "Reusable @Authentication schemes."
                button .wb-btn-add type=button click="toggleAddAuthPicker" "+ Add Auth"
            div .wb-list-items:
                for row in auth_rows:
                    button .wb-item-card {.selected when row.selected} type=button click="selectAuth(row.id)":
                        div .wb-item-top:
                            span class="wb-scheme-badge scheme-{row.type}" "{row.badge}"
                            span .wb-item-name "{row.name}"
                        div .wb-item-foot:
                            span .wb-item-meta "{row.meta}"

        if active_section == 'schema':
            div .wb-list-head:
                div:
                    h2 .wb-list-title "Data Models"
                    p .wb-list-sub "Typed @Schema payloads for OpenAPI & validation."
                button .wb-btn-add type=button click="addSchema" "+ Model"
            div .wb-list-items:
                for row in schema_rows:
                    button .wb-item-card {.selected when row.selected} type=button click="selectSchema(row.id)":
                        div .wb-item-top:
                            span .wb-item-name "{row.name}"
                        div .wb-item-foot:
                            span .wb-item-meta "{row.meta}"
parts/components/simulator_panel.rune
@Component/ApiSimulatorPanel
view:
    div .wb-view .wb-view-wide:
        div .wb-sim-scenarios:
            span .wb-scenario-label "Quick Demos:"
            button .wb-scenario-pill type=button disabled="{sim_is_sending}" click="triggerQuickScenario('anon')" "Test 401 · Anonymous"
            button .wb-scenario-pill type=button disabled="{sim_is_sending}" click="triggerQuickScenario('valid')" "Test 200 · Valid Caller"
            button .wb-scenario-pill type=button disabled="{sim_is_sending}" click="triggerQuickScenario('forbidden')" "Test 403 · Missing Role"
            button .wb-scenario-pill type=button disabled="{sim_is_sending}" click="triggerQuickScenario('burst_demo')" "Test 429 · Rate Limit Burst"

        if !is_graphql:
            div .wb-request-bar:
                span class="wb-method wb-method-lg {sim_route_method_cls}" "{sim_route_method}"
                select .wb-url-select aria-label="Target Route" change="selectSimRoute(this.value)":
                    for r in routes:
                        option value="{r.id}" selected="{r.id == sim_route_id}" "{r.method} {r.path}"
                select .wb-auth-select aria-label="Send Credentials As" change="selectSimAuthMode(this.value)":
                    option value=none selected="{sim_auth_mode == 'none'}" "No Auth (Anonymous)"
                    for a in auth_schemes:
                        option value="{a.name}" selected="{a.name == sim_auth_mode}" "{a.name} ({a.type})"
                button .wb-btn-primary type=button disabled="{sim_is_sending or sim_route == null}" click="sendSimRequest":
                    if sim_is_sending:
                        "Simulating…"
                    if !sim_is_sending:
                        "Send Request"
                button .wb-btn-subtle type=button disabled="{sim_is_sending or sim_route == null}" click="sendBurstRequests" "Burst 5x"
                button .wb-btn-icon type=button disabled="{sim_is_sending}" click="resetSimBuckets" "Reset"

            p .wb-policy-banner "{sim_route_summary}"

        if is_graphql:
            div .wb-request-bar:
                span .wb-method .wb-method-lg .method-patch "GQL"
                select .wb-url-select aria-label="GraphQL Resolver" change="selectSimResolver(this.value)":
                    for g in resolvers:
                        option value="{g.id}" selected="{g.id == sim_resolver_id}" "{g.kind == 'mutation' ? 'MUTATION' : 'QUERY'} · {g.name}"
                select .wb-auth-select aria-label="Send Credentials As" change="selectSimAuthMode(this.value)":
                    option value=none selected="{sim_auth_mode == 'none'}" "No Auth (Anonymous)"
                    for a in auth_schemes:
                        option value="{a.name}" selected="{a.name == sim_auth_mode}" "{a.name} ({a.type})"
                button .wb-btn-primary type=button disabled="{sim_is_sending}" click="sendSimRequest":
                    if sim_is_sending:
                        "Executing…"
                    if !sim_is_sending:
                        "Execute"
                button .wb-btn-subtle type=button disabled="{sim_is_sending}" click="sendBurstRequests" "Burst 5x"
                button .wb-btn-icon type=button disabled="{sim_is_sending}" click="resetSimBuckets" "Reset"

            p .wb-policy-banner "POST /graphql · App Auth: {default_auth == 'none' ? 'public' : default_auth} · Rate Limit: {rate_limit_enabled ? (rate_limit_requests + ' req / ' + rate_limit_window + 's (' + rate_limit_key + ')') : 'off'}"

        div .wb-sim-split:
            div .wb-section-card:
                h3 .wb-card-title "Request"
                if sim_scheme_type == 'none':
                    p .wb-helper "No Authorization, API Key, HMAC, or Cookie headers will be sent."
                if sim_scheme_type == 'jwt' or sim_scheme_type == 'basic':
                    div .wb-form-grid:
                        label .wb-field:
                            span .wb-label "Username"
                            input .wb-input .wb-mono type=text value="{sim_username}" data-preserve-draft=true on_input="setSimUsername(this.value)"
                        label .wb-field:
                            span .wb-label "Password"
                            input .wb-input .wb-mono type=text value="{sim_password}" data-preserve-draft=true on_input="setSimPassword(this.value)"
                if sim_scheme_type == 'api_key':
                    label .wb-field:
                        span .wb-label "API Key"
                        input .wb-input .wb-mono type=text value="{sim_api_key}" data-preserve-draft=true on_input="setSimApiKey(this.value)"
                if sim_scheme_type == 'oauth2' or sim_scheme_type == 'bearer' or sim_scheme_type == 'cookie':
                    label .wb-field:
                        span .wb-label "Bearer Token / Session Cookie"
                        input .wb-input .wb-mono type=text value="{sim_token}" data-preserve-draft=true on_input="setSimToken(this.value)"
                if sim_scheme_type == 'hmac':
                    label .wb-toggle-row:
                        input type=checkbox checked="{sim_hmac_valid}" change="toggleSimHmacValid"
                        span "Valid HMAC-SHA256 body signature (uncheck to simulate tampered payload)"
                if !is_graphql and sim_route_has_params:
                    div .wb-form-grid:
                        for p in sim_route_param_rows:
                            label .wb-field:
                                span .wb-label "Path Param: {p.name}"
                                input .wb-input .wb-mono type=text value="{p.value}" data-preserve-draft=true on_input="setSimPathParam(p.name, this.value)"
                if !is_graphql and sim_route_has_body:
                    label .wb-field:
                        span .wb-label "JSON Body ({sim_route_method})"
                        textarea .wb-code-area rows=3 data-preserve-draft=true on_input="setSimBody(this.value)" "{sim_body}"
                if is_graphql:
                    if sim_gql_has_args:
                        div .wb-form-grid:
                            for arg in sim_gql_arg_rows:
                                label .wb-field:
                                    span .wb-label "Arg: {arg.name} ({arg.type})"
                                    input id="as-sim-gql-arg-{sim_resolver_id}-{arg.name}" .wb-input .wb-mono type=text value="{arg.value}" data-preserve-draft=true on_input="setSimGqlArg(arg.name, arg.type, this.value)"
                    label .wb-field:
                        span .wb-label "GraphQL Operation"
                        textarea id="as-sim-gql-query-{sim_resolver_id}" .wb-code-area rows=6 data-preserve-draft=true on_input="setSimGqlQuery(this.value)" "{sim_gql_query}"
                    label .wb-field:
                        span .wb-label "Variables (JSON)"
                        textarea id="as-sim-gql-vars-{sim_resolver_id}" .wb-code-area rows=3 on_input="setSimGqlVars(this.value)" "{sim_gql_vars}"
                if sim_last_curl != "":
                    div .wb-sub-code:
                        span .wb-sub-code-label "curl template"
                        pre .wb-dark-pre "{sim_last_curl}"

            div .wb-section-card .wb-resp-card {.is-sending when sim_is_sending}:
                div .wb-resp-head:
                    h3 .wb-card-title "Response"
                    div .wb-resp-status:
                        if sim_is_sending:
                            span .wb-http-badge .badge-sending .visible "Simulating…"
                        if !sim_is_sending and sim_last_status > 0:
                            span class="wb-http-badge badge-{sim_status_class} visible" "{sim_last_status}"
                p .wb-resp-reason "{sim_last_reason}"
                if sim_last_headers.length > 0:
                    div .wb-hdr-box:
                        span .wb-sub-code-label "Response Headers"
                        for h in sim_last_headers:
                            div .wb-hdr-item "{h}"
                if sim_last_body != "":
                    div .wb-sub-code:
                        span .wb-sub-code-label "Response Body"
                        pre .wb-dark-pre "{sim_last_body}"
                if sim_last_auth_json != "":
                    div .wb-sub-code:
                        span .wb-sub-code-label "Injected auth Context (available inside run:)"
                        pre .wb-dark-pre "{sim_last_auth_json}"
parts/logic/codec.rune
@Logic/api_studio

func sanitize_ident(raw, fallback):
    local cleaned = regex_replace((raw ?? "").trim(), "[^A-Za-z0-9_]", "")
    return cleaned != "" ? cleaned : fallback

func normalize_api_path(raw):
    local path = (raw ?? "").trim()
    return path.startsWith("/") ? path : ("/" + path)

func format_api_rune(app_name, app_version, app_port, swagger_enabled, cors_mode, cors_origins, default_auth, rl_enabled, rl_req, rl_win, rl_key, auth_list, schema_list, route_list):
    local out = ["#!RUNE", "# Generated by Rune API Studio", ""]
    local safe_app = sanitize_ident(app_name, "MyRestAPI")
    out.push("@App")
    out.push("name = " + safe_app)
    out.push("version = " + ((app_version ?? "").trim() != "" ? app_version.trim() : "1.0.0"))
    out.push("type = REST")
    out.push("port = " + clamp(round(to_number(app_port, 8080)), 1, 65535))
    out.push("swagger = " + swagger_enabled)
    if cors_mode == "all":
        out.push("cors = true")
    else if cors_mode == "origins":
        local origins = split_csv(cors_origins)
        if origins.length > 0:
            out.push("cors = " + json.stringify(origins))
    if (default_auth ?? "") != "" and default_auth != "none":
        out.push("default_auth = " + default_auth)
    if rl_enabled:
        local rl_obj = {"requests": clamp(round(to_number(rl_req, 60)), 1, 100000), "window": clamp(round(to_number(rl_win, 60)), 1, 86400), "key": (rl_key ?? "ip")}
        out.push("rate_limit = " + json.stringify(rl_obj))
    out.push("")

    for a in auth_list:
        local aname = sanitize_ident(a.name, "AuthScheme")
        out.push("@Authentication/" + aname)
        out.push("type = " + a.type)
        match a.type:
            "jwt":
                out.push("algorithm = " + (a.algorithm != "" ? a.algorithm : "HS256"))
                if (a.secret ?? "") != "":
                    out.push("secret = \"" + a.secret + "\"")
                if (a.public_key ?? "") != "":
                    out.push("public_key = \"" + a.public_key + "\"")
                if (a.jwks_url ?? "") != "":
                    out.push("jwks_url = \"" + a.jwks_url + "\"")
                if (a.issuer ?? "") != "":
                    out.push("issuer = \"" + a.issuer + "\"")
                if (a.audience ?? "") != "":
                    out.push("audience = \"" + a.audience + "\"")
                if to_number(a.leeway, 60) != 60:
                    out.push("leeway = " + round(to_number(a.leeway, 60)))
                if to_number(a.expiration, 3600) > 0:
                    out.push("expiration = " + round(to_number(a.expiration, 3600)))
                if (a.token_endpoint ?? "") != "":
                    out.push("token_endpoint = \"" + a.token_endpoint + "\"")
                if (a.roles_claim ?? "roles") != "roles":
                    out.push("roles_claim = \"" + a.roles_claim + "\"")
                if (a.scopes_claim ?? "scope") != "scope":
                    out.push("scopes_claim = \"" + a.scopes_claim + "\"")
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("users:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"username": e.k, "password": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
            "oauth2":
                if (a.introspection_url ?? "") != "":
                    out.push("introspection_url = \"" + a.introspection_url + "\"")
                if (a.client_id ?? "") != "":
                    out.push("client_id = \"" + a.client_id + "\"")
                if (a.client_secret ?? "") != "":
                    out.push("client_secret = \"" + a.client_secret + "\"")
                if (a.jwks_url ?? "") != "":
                    out.push("jwks_url = \"" + a.jwks_url + "\"")
                if (a.issuer ?? "") != "":
                    out.push("issuer = \"" + a.issuer + "\"")
                if (a.audience ?? "") != "":
                    out.push("audience = \"" + a.audience + "\"")
                if (a.authorization_url ?? "") != "":
                    out.push("authorization_url = \"" + a.authorization_url + "\"")
                if (a.token_url ?? "") != "":
                    out.push("token_url = \"" + a.token_url + "\"")
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("tokens:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"token": e.k, "sub": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
            "api_key":
                out.push("header = \"" + ((a.header ?? "") != "" ? a.header : "X-API-Key") + "\"")
                if (a.query ?? "") != "":
                    out.push("query = \"" + a.query + "\"")
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("keys:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"key": e.k, "sub": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
            "basic":
                out.push("realm = \"" + ((a.realm ?? "") != "" ? a.realm : "Vectrune API") + "\"")
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("users:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"username": e.k, "password": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
            "bearer":
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("tokens:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"token": e.k, "sub": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
            "hmac":
                out.push("header = \"" + ((a.header ?? "") != "" ? a.header : "X-Webhook-Signature") + "\"")
                out.push("secret = \"" + (a.secret ?? "webhook-secret") + "\"")
                if (a.prefix ?? "") != "":
                    out.push("prefix = \"" + a.prefix + "\"")
                out.push("encoding = " + ((a.encoding ?? "") != "" ? a.encoding : "hex"))
                if (a.sub ?? "") != "":
                    out.push("sub = \"" + a.sub + "\"")
                local rlist = split_csv(a.roles)
                if rlist.length > 0:
                    out.push("roles = " + json.stringify(rlist))
                local slist = split_csv(a.scopes)
                if slist.length > 0:
                    out.push("scopes = " + json.stringify(slist))
            "cookie":
                out.push("cookie_name = \"" + ((a.cookie_name ?? "") != "" ? a.cookie_name : "vectrune_session") + "\"")
                if (a.secret ?? "") != "":
                    out.push("secret = \"" + a.secret + "\"")
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("tokens:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"token": e.k, "sub": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
        out.push("")

    for s in schema_list:
        local sname = sanitize_ident(s.name, "Record")
        out.push("@Schema/" + sname)
        for f in (s.fields ?? []):
            local fname = sanitize_ident(f.name, "field")
            out.push(fname + " = " + (f.type ?? "string"))
        out.push("")

    for r in route_list:
        local rpath = normalize_api_path(r.path)
        out.push("@Route/" + r.method + " " + rpath)
        if r.auth_mode == "none" or (r.auth_mode == "custom" and r.auth_schemes.length == 0):
            out.push("auth = none")
        else if r.auth_mode == "custom":
            out.push("auth = " + (r.auth_schemes.length == 1 ? r.auth_schemes[0] : json.stringify(r.auth_schemes)))
        local rroles = split_csv(r.roles)
        if rroles.length > 0:
            out.push("roles = " + json.stringify(rroles))
        local rscopes = split_csv(r.scopes)
        if rscopes.length > 0:
            out.push("scopes = " + json.stringify(rscopes))
        if (r.expect ?? "") != "" and r.expect != "none":
            if r.method == "CRUD":
                out.push("schema = " + r.expect)
            else:
                out.push("expect = " + r.expect)
        if r.rl_mode == "none":
            out.push("rate_limit = none")
        else if r.rl_mode == "custom":
            local rl_o = {"requests": clamp(round(to_number(r.rl_requests, 20)), 1, 100000), "window": clamp(round(to_number(r.rl_window, 60)), 1, 86400), "key": (r.rl_key ?? "ip")}
            out.push("rate_limit = " + json.stringify(rl_o))
        if r.method != "CRUD":
            out.push("run:")
            local raw_steps = (r.steps ?? "").trim()
            if raw_steps == "":
                out.push("    return {\"ok\": true}")
            else:
                for line in raw_steps.split("\n"):
                    if line.trim() != "":
                        out.push("    " + line)
        out.push("")

    return rune.format(out.join("\n").trim() + "\n", 100)

func format_api_tests(app_name, default_auth, route_list):
    local safe_app = sanitize_ident(app_name, "Api")
    local out = ["#!RUNE", "# Auto-generated native HTTP tests — run with: vectrune test", "import " + json.stringify(safe_app.toLowerCase() + ".rune"), ""]
    local idx = 1
    for r in route_list:
        if r.method == "CRUD":
            continue
        local eff = effective_route_auth_names(r, default_auth)
        local path = normalize_api_path(r.path)
        local test_path = regex_replace(path, "\\{[^}]+\\}", "demo-1")
        local public_route = eff.length == 0
        local test_name = public_route ? "PublicRoute" : "RejectsUnauthRoute"
        local status = public_route ? declared_response_status(r.steps) : 401
        local request = {"method": r.method, "path": test_path}
        if r.method == "POST" or r.method == "PUT" or r.method == "PATCH":
            request.body = {}
        out.push("@Test/" + safe_app + "/" + test_name + idx)
        out.push("run:")
        out.push("    req = " + json.stringify(request))
        out.push("    res = test-request req")
        out.push("    assert res.status == " + status)
        out.push("")
        idx += 1
    return out.join("\n").trim() + "\n"

func format_openapi_json(app_name, app_version, default_auth, rl_enabled, auth_list, schema_list, route_list):
    local sec_schemes = {}
    for a in auth_list:
        match a.type:
            "jwt":
                sec_schemes[a.name] = {"type": "http", "scheme": "bearer", "bearerFormat": "JWT"}
            "bearer":
                sec_schemes[a.name] = {"type": "http", "scheme": "bearer"}
            "basic":
                sec_schemes[a.name] = {"type": "http", "scheme": "basic"}
            "api_key":
                sec_schemes[a.name] = {"type": "apiKey", "in": "header", "name": ((a.header ?? "") != "" ? a.header : "X-API-Key")}
            "cookie":
                sec_schemes[a.name] = {"type": "apiKey", "in": "cookie", "name": ((a.cookie_name ?? "") != "" ? a.cookie_name : "vectrune_session")}
            "hmac":
                sec_schemes[a.name] = {"type": "apiKey", "in": "header", "name": ((a.header ?? "") != "" ? a.header : "X-Webhook-Signature"), "description": "HMAC-SHA256 signature"}
            "oauth2":
                local auth_u = (a.authorization_url ?? "") != "" ? a.authorization_url : "https://idp.example.com/oauth/authorize"
                local tok_u = (a.token_url ?? "") != "" ? a.token_url : "https://idp.example.com/oauth/token"
                local flow_scopes = {}
                for r in route_list:
                    local allowed = effective_route_auth_names(r, default_auth)
                    if allowed.includes(a.name):
                        for scope in split_csv(r.scopes):
                            flow_scopes[scope] = scope
                sec_schemes[a.name] = {"type": "oauth2", "flows": {"authorizationCode": {"authorizationUrl": auth_u, "tokenUrl": tok_u, "scopes": flow_scopes}}}

    local comp_schemas = {}
    for s in schema_list:
        local props = {}
        local req = []
        for f in (s.fields ?? []):
            local jtype = f.type == "bool" ? "boolean" : f.type
            props[f.name] = {"type": jtype}
            req.push(f.name)
        comp_schemas[s.name] = {"type": "object", "properties": props, "required": req}

    local paths = {}
    for r in route_list:
        local p = normalize_api_path(r.path)
        if paths[p] == null:
            paths[p] = {}
        local m = r.method == "CRUD" ? "get" : r.method.toLowerCase()
        local eff = effective_route_auth_names(r, default_auth)
        local rscopes = split_csv(r.scopes)
        local rroles = split_csv(r.roles)
        local status = "" + declared_response_status(r.steps)
        local op = {"summary": r.method + " " + p, "responses": {}}
        op.responses[status] = {"description": "Handler response"}
        local params = []
        for part in p.split("/"):
            if part.startsWith("{") and part.endsWith("}"):
                params.push({"name": part.slice(1, part.length - 1), "in": "path", "required": true, "schema": {"type": "string"}})
        if params.length > 0:
            op.parameters = params
        if eff.length > 0:
            local sec = []
            for ename in eff:
                local entry = {}
                local scheme = sec_schemes[ename]
                entry[ename] = scheme != null and scheme.type == "oauth2" ? rscopes : []
                sec.push(entry)
            op.security = sec
            op.responses["401"] = {"description": "Unauthorized"}
            if rroles.length > 0 or rscopes.length > 0:
                op.responses["403"] = {"description": "Forbidden"}
        if r.rl_mode == "custom" or (r.rl_mode == "inherit" and rl_enabled):
            op.responses["429"] = {"description": "Too Many Requests"}
        if (m == "post" or m == "put" or m == "patch") and (r.expect ?? "") != "" and r.expect != "none":
            op.requestBody = {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/" + r.expect}}}}
        paths[p][m] = op

    local spec = {"openapi": "3.0.3", "info": {"title": app_name, "version": app_version}, "paths": paths, "components": {"securitySchemes": sec_schemes, "schemas": comp_schemas}}
    return json.stringify(spec, null, 2)

func declared_response_status(steps):
    for line in (steps ?? "").split("\n"):
        if line.startsWith("respond "):
            local code = to_number(line.slice(8).split(" ")[0], 200)
            return clamp(round(code), 100, 599)
    return 200

func render_imported_steps(items, indent):
    local lines = []
    for item in items:
        local blocks = entries(item)
        if blocks.length == 0:
            lines.push(indent + item)
        else:
            for block in blocks:
                lines.push(indent + block.key + ":")
                lines.push(render_imported_steps(block.value, indent + "    "))
    return lines.join("\n")

func arr_to_csv(val):
    if val == null:
        return ""
    if val.split != null:
        return replace_all(replace_all(val, "[", ""), "]", "").trim()
    local items = []
    for x in val:
        items.push("" + x)
    return items.join(", ")

func parse_gql_field_sig(raw_sig):
    local sig = (raw_sig ?? "").trim()
    local parts = sig.split("(")
    if parts.length < 2:
        local simple_name = sanitize_ident(sig, "field")
        return {"name": simple_name, "args": []}
    local p0 = parts[0]
    local p1 = parts[1]
    local fname = sanitize_ident(p0, "field")
    local inner = regex_replace(p1, "\\).*", "")
    local args = []
    local raw_args = inner.split(",")
    for part in raw_args:
        local p = part.trim()
        if p != "":
            local kv = p.split(":")
            local k0 = kv[0]
            local aname = sanitize_ident(k0, "")
            local atype = "string"
            if kv.length > 1:
                local k1 = kv[1]
                local k1_t = k1.trim()
                local k1_l = k1_t.toLowerCase()
                if k1_l != "":
                    atype = k1_l
            if aname != "":
                args.push({"name": aname, "type": atype})
    return {"name": fname, "args": args}

func parse_api_rune(source):
    local raw = replace_all(source ?? "", "\r\n", "\n")
    if raw.trim() == "":
        return {"error": "Paste a Vectrune REST or GraphQL .rune file first."}

    local doc = rune.parse(raw)
    if (doc.sections ?? []).length == 0:
        return {"error": "No @App, @Authentication, @Schema, @Route, or @GraphQL sections found."}

    local proto = "rest"
    local aname = "ImportedAPI"
    local aver = "1.0.0"
    local aport = 8080
    local aswag = true
    local acors_mode = "off"
    local acors_orig = ""
    local adef_auth = "none"
    local arl_on = false
    local arl_req = 60
    local arl_win = 60
    local arl_key = "ip"

    local parsed_auth = []
    local parsed_schemas = []
    local parsed_routes = []
    local parsed_resolvers = []
    local parsed_memory = []
    local aid = 1
    local sid = 1
    local rid = 1
    local gid = 1

    for sec in doc.sections:
        match sec.kind:
            "App":
                local app_type = (sec.kv.type ?? "REST").toUpperCase()
                if app_type == "GRAPHQL":
                    proto = "graphql"
                else if app_type != "REST":
                    return {"error": "API Studio imports REST and GraphQL applications."}
                aname = sec.kv.name ?? aname
                aver = "" + (sec.kv.version ?? aver)
                aport = clamp(round(to_number(sec.kv.port, proto == "graphql" ? 4000 : 8080)), 1, 65535)
                aswag = sec.kv.swagger != false
                if sec.kv.cors == true or sec.kv.cors == "*":
                    acors_mode = "all"
                else if sec.kv.cors != null and sec.kv.cors != false:
                    acors_mode = "origins"
                    acors_orig = arr_to_csv(sec.kv.cors)
                if sec.kv.default_auth != null:
                    adef_auth = "" + sec.kv.default_auth
                if sec.kv.rate_limit != null and sec.kv.rate_limit != "none" and sec.kv.rate_limit != false:
                    arl_on = true
                    if sec.kv.rate_limit.requests != null:
                        arl_req = round(to_number(sec.kv.rate_limit.requests, 60))
                        arl_win = round(to_number(sec.kv.rate_limit.window, 60))
                        arl_key = sec.kv.rate_limit.key ?? "ip"
            "Authentication":
                local stype = (sec.kv.type ?? "jwt").toLowerCase()
                if stype == "apikey":
                    stype = "api_key"
                local entries = []
                for u in (sec.series.users ?? []):
                    if u != null and u.username != null:
                        local ur = arr_to_csv(u.roles)
                        local us = arr_to_csv(u.scopes)
                        entries.push({"k": u.username ?? "user", "v": u.password ?? "", "roles": ur, "scopes": us})
                for k in (sec.series.keys ?? []):
                    if k != null and k.key != null:
                        local kr = arr_to_csv(k.roles)
                        local ks = arr_to_csv(k.scopes)
                        entries.push({"k": k.key ?? "", "v": k.sub ?? "api-key", "roles": kr, "scopes": ks})
                for t in (sec.series.tokens ?? []):
                    if t != null and t.token != null:
                        local tr = arr_to_csv(t.roles)
                        local ts = arr_to_csv(t.scopes)
                        entries.push({"k": t.token ?? "", "v": t.sub ?? "client", "roles": tr, "scopes": ts})
                if entries.length == 0 and (sec.kv.username ?? "") != "":
                    local ur0 = arr_to_csv(sec.kv.roles)
                    local us0 = arr_to_csv(sec.kv.scopes)
                    entries.push({"k": sec.kv.username, "v": sec.kv.password ?? "", "roles": ur0, "scopes": us0})
                if entries.length == 0 and (sec.kv.key ?? "") != "":
                    local kr0 = arr_to_csv(sec.kv.roles)
                    local ks0 = arr_to_csv(sec.kv.scopes)
                    entries.push({"k": sec.kv.key, "v": sec.kv.sub ?? "api-key", "roles": kr0, "scopes": ks0})
                if entries.length == 0 and (sec.kv.token ?? "") != "":
                    local tr0 = arr_to_csv(sec.kv.roles)
                    local ts0 = arr_to_csv(sec.kv.scopes)
                    entries.push({"k": sec.kv.token, "v": sec.kv.sub ?? "client", "roles": tr0, "scopes": ts0})
                local a_roles = arr_to_csv(sec.kv.roles)
                local a_scopes = arr_to_csv(sec.kv.scopes)
                local cfg = {"algorithm": sec.kv.algorithm ?? "HS256", "secret": sec.kv.secret ?? "", "public_key": sec.kv.public_key ?? "", "jwks_url": sec.kv.jwks_url ?? "", "issuer": sec.kv.issuer ?? "", "audience": sec.kv.audience ?? "", "leeway": to_number(sec.kv.leeway, 60), "expiration": to_number(sec.kv.expiration, 3600), "token_endpoint": sec.kv.token_endpoint ?? "", "roles_claim": sec.kv.roles_claim ?? "roles", "scopes_claim": sec.kv.scopes_claim ?? "scope", "introspection_url": sec.kv.introspection_url ?? "", "client_id": sec.kv.client_id ?? "", "client_secret": sec.kv.client_secret ?? "", "authorization_url": sec.kv.authorization_url ?? "", "token_url": sec.kv.token_url ?? "", "header": sec.kv.header ?? "X-API-Key", "query": sec.kv.query ?? "", "realm": sec.kv.realm ?? "Vectrune API", "prefix": sec.kv.prefix ?? "sha256=", "encoding": sec.kv.encoding ?? "hex", "cookie_name": sec.kv.cookie_name ?? "vectrune_session", "sub": sec.kv.sub ?? "webhook-sender", "roles": a_roles, "scopes": a_scopes, "entries": entries}
                local sch = make_auth_scheme(aid, sec.name != "" ? sec.name : ("Auth" + aid), stype, cfg)
                parsed_auth.push(sch)
                aid += 1
            "Schema":
                local flds = []
                for k in keys(sec.kv):
                    flds.push({"name": k, "type": "" + sec.kv[k]})
                local sm = make_schema(sid, sec.name != "" ? sec.name : ("Schema" + sid), flds)
                parsed_schemas.push(sm)
                sid += 1
            "Route":
                local method = sec.path.length > 1 ? sec.path[1].toUpperCase() : "GET"
                local rpath = sec.path.length > 2 ? ("/" + sec.path.slice(2).join("/")) : "/"
                local amode = "inherit"
                local aschemes = []
                if sec.kv.auth != null:
                    local raw_a = arr_to_csv(sec.kv.auth)
                    if raw_a.toLowerCase() == "none":
                        amode = "none"
                    else:
                        amode = "custom"
                        aschemes = split_csv(raw_a)
                local rl_mode = "inherit"
                local rl_r = 20
                local rl_w = 60
                local rl_k = "ip"
                if sec.kv.rate_limit == "none" or sec.kv.rate_limit == false:
                    rl_mode = "none"
                else if sec.kv.rate_limit != null and sec.kv.rate_limit.requests != null:
                    rl_mode = "custom"
                    rl_r = round(to_number(sec.kv.rate_limit.requests, 20))
                    rl_w = round(to_number(sec.kv.rate_limit.window, 60))
                    rl_k = sec.kv.rate_limit.key ?? "ip"
                local steps_txt = render_imported_steps(sec.series.run ?? [], "")
                local rroles = arr_to_csv(sec.kv.roles)
                local rscopes = arr_to_csv(sec.kv.scopes)
                local exp = sec.kv.expect ?? sec.kv.schema ?? ""
                local rt = make_route(rid, method, rpath, amode, aschemes, rroles, rscopes, exp, rl_mode, rl_r, rl_w, rl_k, steps_txt)
                parsed_routes.push(rt)
                rid += 1
            "GraphQL":
                proto = "graphql"
                local gkind_raw = sec.path.length > 1 ? sec.path[1].toLowerCase() : "query"
                local gkind = gkind_raw == "mutation" ? "mutation" : "query"
                local gret = sec.path.length > 2 ? sec.path[2] : "JSON"
                local groles = arr_to_csv(sec.kv.roles)
                local gscopes = arr_to_csv(sec.kv.scopes)
                for sig_key in keys(sec.series ?? {}):
                    local parsed_sig = parse_gql_field_sig(sig_key)
                    local gsteps = render_imported_steps(sec.series[sig_key] ?? [], "")
                    local gres = make_resolver(gid, gkind, parsed_sig.name, gret, parsed_sig.args, groles, gscopes, gsteps)
                    parsed_resolvers.push(gres)
                    gid += 1
            "Memory":
                local mname = sec.name != "" ? sec.name : "items"
                local mrecs = sec.records ?? []
                parsed_memory.push({"name": mname, "records": mrecs})

    if parsed_auth.length == 0 and parsed_schemas.length == 0 and parsed_routes.length == 0 and parsed_resolvers.length == 0:
        return {"error": "No @Authentication, @Schema, @Route, or @GraphQL sections were recognized."}

    local pid_raw = sanitize_ident(aname, "imported")
    local pid = pid_raw.toLowerCase()
    local snap = {"api_protocol": proto, "project_id": pid, "app_name": aname, "app_version": aver, "app_port": aport, "swagger_enabled": aswag, "cors_mode": acors_mode, "cors_origins": acors_orig, "default_auth": adef_auth, "rate_limit_enabled": arl_on, "rate_limit_requests": arl_req, "rate_limit_window": arl_win, "rate_limit_key": arl_key, "auth_schemes": parsed_auth, "schemas": parsed_schemas, "routes": parsed_routes, "resolvers": parsed_resolvers, "memory_collections": parsed_memory}
    return {"snapshot": snap}
parts/logic/editor.rune
@Logic/api_studio

func api_history_keys():
    return ["api_protocol", "selected_preset", "project_id", "app_name", "app_version", "app_port", "swagger_enabled", "cors_mode", "cors_origins", "default_auth", "rate_limit_enabled", "rate_limit_requests", "rate_limit_window", "rate_limit_key", "auth_schemes", "schemas", "routes", "resolvers", "memory_collections", "selected_auth_id", "selected_schema_id", "selected_route_id", "selected_resolver_id"]

func capture_api_snapshot(proto, pid, aname, aver, aport, aswag, acors_m, acors_o, adef, arl_on, arl_r, arl_w, arl_k, alist, slist, rlist, glist, mlist):
    return {"api_protocol": proto, "project_id": pid, "app_name": aname, "app_version": aver, "app_port": aport, "swagger_enabled": aswag, "cors_mode": acors_m, "cors_origins": acors_o, "default_auth": adef, "rate_limit_enabled": arl_on, "rate_limit_requests": arl_r, "rate_limit_window": arl_w, "rate_limit_key": arl_k, "auth_schemes": deep_clone(alist), "schemas": deep_clone(slist), "routes": deep_clone(rlist), "resolvers": deep_clone(glist), "memory_collections": deep_clone(mlist)}

action pushApiUndo:
    history.checkpoint(api_history_keys(), 40)

action applyApiSnapshot(snap):
    api_protocol = snap.api_protocol == "graphql" ? "graphql" : "rest"
    project_id = snap.project_id ?? "custom_api"
    app_name = snap.app_name ?? "MyRestAPI"
    app_version = snap.app_version ?? "1.0.0"
    app_port = clamp(round(to_number(snap.app_port, 8080)), 1, 65535)
    swagger_enabled = snap.swagger_enabled != false
    cors_mode = snap.cors_mode ?? "off"
    cors_origins = snap.cors_origins ?? ""
    default_auth = snap.default_auth ?? "none"
    rate_limit_enabled = snap.rate_limit_enabled == true
    rate_limit_requests = clamp(round(to_number(snap.rate_limit_requests, 60)), 1, 100000)
    rate_limit_window = clamp(round(to_number(snap.rate_limit_window, 60)), 1, 86400)
    rate_limit_key = snap.rate_limit_key ?? "ip"
    auth_schemes = deep_clone(snap.auth_schemes ?? [])
    schemas = deep_clone(snap.schemas ?? [])
    routes = deep_clone(snap.routes ?? [])
    resolvers = deep_clone(snap.resolvers ?? [])
    memory_collections = deep_clone(snap.memory_collections ?? [])
    selected_auth_id = auth_schemes.length > 0 ? auth_schemes[0].id : 0
    selected_schema_id = schemas.length > 0 ? schemas[0].id : 0
    selected_route_id = routes.length > 1 ? routes[1].id : (routes.length > 0 ? routes[0].id : 0)
    selected_resolver_id = resolvers.length > 0 ? resolvers[0].id : 0
    show_add_auth_picker = false
    call resetApiSimulation

action initApiStudio:
    saved_apis = storage.get("rune_api_studio_library")
    if saved_apis == null:
        saved_apis = []
    local requested = storage.get("rune_api_studio_preset")
    if requested != null and requested != "":
        storage.set("rune_api_studio_preset", "")
    local is_gql_req = requested == "book_graphql" or requested == "starter_graphql"
    local initial_key = (is_gql_req or requested == "hello_world" or requested == "saas_multi_auth" or requested == "webhook_gateway" or requested == "blank_rest" or requested == "secure_orders") ? requested : "secure_orders"
    local preset = is_gql_req ? build_graphql_preset(initial_key) : build_api_preset(initial_key)
    selected_preset = initial_key
    call applyApiSnapshot preset
    status_message = "Loaded example: " + app_name

action selectPreset(key):
    call pushApiUndo
    local is_gql = key == "book_graphql" or key == "starter_graphql"
    local preset = is_gql ? build_graphql_preset(key) : build_api_preset(key)
    selected_preset = key
    call applyApiSnapshot preset
    status_message = "Loaded example: " + app_name

action openSavedOrPreset(key):
    match key:
        "hello_world", "secure_orders", "saas_multi_auth", "webhook_gateway", "blank_rest", "book_graphql", "starter_graphql":
            call selectPreset key
        else:
            for entry in saved_apis:
                if entry.id == key:
                    local stored = storage.get("rune_api_studio_doc_" + key)
                    if stored != null:
                        call pushApiUndo
                        selected_preset = key
                        call applyApiSnapshot stored
                        status_message = "Loaded saved API: " + app_name

action saveApiToStorage:
    local safe_raw = sanitize_ident(app_name, "api")
    local safe_id = "saved:" + safe_raw.toLowerCase()
    project_id = safe_id
    local snap = capture_api_snapshot(api_protocol, project_id, app_name, app_version, app_port, swagger_enabled, cors_mode, cors_origins, default_auth, rate_limit_enabled, rate_limit_requests, rate_limit_window, rate_limit_key, auth_schemes, schemas, routes, resolvers, memory_collections)
    storage.set("rune_api_studio_doc_" + safe_id, snap)
    local next_lib = saved_apis.filter(item => item.id != safe_id)
    local entry = {"id": safe_id, "name": app_name}
    saved_apis = insert_at(next_lib, 0, entry)
    selected_preset = safe_id
    storage.set("rune_api_studio_library", saved_apis)
    status_message = "Saved " + app_name + " to browser storage."

action undoApiEdit:
    if !history.can_undo:
        stop
    history.undo()
    call resetApiSimulation
    status_message = "Undid last change."

action redoApiEdit:
    if !history.can_redo:
        stop
    history.redo()
    call resetApiSimulation
    status_message = "Redid change."

action toggleFullscreen:
    fullscreen.toggle()

action toggleCodePanel:
    show_code_panel = !show_code_panel

action toggleAddAuthPicker:
    show_add_auth_picker = !show_add_auth_picker

action setActiveSection(sec):
    active_section = sec
    show_add_auth_picker = false

action selectAuth(id):
    selected_auth_id = to_number(id, selected_auth_id)
    active_section = "auth"

action selectSchema(id):
    selected_schema_id = to_number(id, selected_schema_id)
    active_section = "schema"

action selectRoute(id):
    selected_route_id = to_number(id, selected_route_id)
    active_section = "route"

action openRouteInSimulator(id):
    call selectSimRoute id
    active_section = "simulator"
    call runSimRequest

action setAppName(val):
    app_name = val

action setAppVersion(val):
    app_version = val

action setAppPort(val):
    app_port = clamp(round(to_number(val, 8080)), 1, 65535)

action toggleSwagger:
    swagger_enabled = !swagger_enabled

action setCorsMode(val):
    cors_mode = val

action setCorsOrigins(val):
    cors_origins = val

action setDefaultAuth(val):
    call pushApiUndo
    default_auth = val
    status_message = val == "none" ? "Default auth disabled (routes opt in)." : ("Default auth set to " + val)

action toggleRateLimit:
    call pushApiUndo
    rate_limit_enabled = !rate_limit_enabled

action setRateLimitRequests(val):
    rate_limit_requests = clamp(round(to_number(val, 60)), 1, 100000)

action setRateLimitWindow(val):
    rate_limit_window = clamp(round(to_number(val, 60)), 1, 86400)

action setRateLimitKey(val):
    rate_limit_key = val

action setNewAuthType(val):
    new_auth_type = val

action addAuthScheme(kind):
    call pushApiUndo
    local stype = (kind ?? new_auth_type)
    local id = next_id
    next_id += 1
    local base_name = "Auth" + id
    local cfg = {}
    match stype:
        "jwt":
            base_name = "JWTAuth" + id
            cfg = {"algorithm": "HS256", "secret": "change-me-secret", "issuer": "api.example.com", "audience": "api-clients", "token_endpoint": "/auth/token", "entries": [{"k": "demo", "v": "demo-pass", "roles": "user", "scopes": "read"}]}
        "oauth2":
            base_name = "OAuth2Auth" + id
            cfg = {"issuer": "https://idp.example.com", "audience": "api-clients", "authorization_url": "https://idp.example.com/oauth/authorize", "token_url": "https://idp.example.com/oauth/token", "entries": [{"k": "oauth_tok_demo", "v": "oauth-client", "roles": "service", "scopes": "read"}]}
        "api_key":
            base_name = "ApiKeyAuth" + id
            cfg = {"header": "X-API-Key", "entries": [{"k": "pk_live_demo_" + id, "v": "partner-" + id, "roles": "partner", "scopes": "read"}]}
        "basic":
            base_name = "BasicAuth" + id
            cfg = {"realm": "Vectrune API", "entries": [{"k": "admin", "v": "admin-pass", "roles": "admin", "scopes": "read, write"}]}
        "bearer":
            base_name = "BearerAuth" + id
            cfg = {"entries": [{"k": "tok_service_" + id, "v": "worker-" + id, "roles": "service", "scopes": "read"}]}
        "hmac":
            base_name = "WebhookHmac" + id
            cfg = {"header": "X-Webhook-Signature", "secret": "whsec_demo_" + id, "prefix": "sha256=", "encoding": "hex", "sub": "webhook-" + id, "roles": "webhook", "scopes": "webhooks:ingest"}
        "cookie":
            base_name = "SessionCookie" + id
            cfg = {"cookie_name": "vectrune_session", "secret": "cookie-hmac-secret", "entries": [{"k": "sess_demo_" + id, "v": "user-" + id, "roles": "member", "scopes": "read"}]}
    local created = make_auth_scheme(id, base_name, stype, cfg)
    local next_list = json.parse(json.stringify(auth_schemes))
    next_list.push(created)
    auth_schemes = next_list
    selected_auth_id = id
    active_section = "auth"
    show_add_auth_picker = false
    status_message = "Added @Authentication/" + base_name + " (" + stype + ")"

action deleteSelectedAuth:
    if selected_auth == null:
        stop
    call pushApiUndo
    local removed_name = selected_auth.name
    auth_schemes = auth_schemes.filter(a => a.id != selected_auth_id)
    if default_auth == removed_name:
        default_auth = "none"
    local next_routes = json.parse(json.stringify(routes))
    for r in next_routes:
        r.auth_schemes = (r.auth_schemes ?? []).filter(n => n != removed_name)
    routes = next_routes
    selected_auth_id = auth_schemes.length > 0 ? auth_schemes[0].id : 0
    if sim_auth_mode == removed_name:
        call selectSimRoute sim_route_id
    status_message = "Removed @Authentication/" + removed_name

action updateAuthField(pair):
    local field = pair[0]
    local val = pair[1]
    local next_list = json.parse(json.stringify(auth_schemes))
    local old_name = ""
    local new_name = ""
    for a in next_list:
        if a.id == selected_auth_id:
            if field == "name":
                old_name = a.name
                new_name = sanitize_ident(val, a.name)
                a.name = new_name
            else if field == "leeway" or field == "expiration":
                a[field] = round(to_number(val, 0))
            else:
                a[field] = val
    auth_schemes = next_list
    if old_name != "" and new_name != "" and old_name != new_name:
        if default_auth == old_name:
            default_auth = new_name
        if sim_auth_mode == old_name:
            sim_auth_mode = new_name
        local next_routes = json.parse(json.stringify(routes))
        for r in next_routes:
            local mapped = []
            for n in (r.auth_schemes ?? []):
                mapped.push(n == old_name ? new_name : n)
            r.auth_schemes = mapped
        routes = next_routes

action setNewCredA(val):
    new_cred_a = val

action setNewCredB(val):
    new_cred_b = val

action setNewCredRoles(val):
    new_cred_roles = val

action setNewCredScopes(val):
    new_cred_scopes = val

action addAuthEntry:
    if selected_auth == null:
        stop
    local ka = new_cred_a.trim()
    if ka == "":
        status_message = "Enter a username, key, or token before adding."
        stop
    call pushApiUndo
    local next_list = json.parse(json.stringify(auth_schemes))
    for a in next_list:
        if a.id == selected_auth_id:
            local ent = a.entries ?? []
            ent.push({"k": ka, "v": (new_cred_b.trim() != "" ? new_cred_b.trim() : "subject"), "roles": new_cred_roles.trim(), "scopes": new_cred_scopes.trim()})
            a.entries = ent
    auth_schemes = next_list
    new_cred_a = ""
    new_cred_b = ""
    status_message = "Added credential entry to @" + sel_auth_name

action removeAuthEntry(key_val):
    if selected_auth == null:
        stop
    call pushApiUndo
    local next_list = json.parse(json.stringify(auth_schemes))
    for a in next_list:
        if a.id == selected_auth_id:
            a.entries = (a.entries ?? []).filter(e => e.k != key_val)
    auth_schemes = next_list
    status_message = "Removed credential entry."

action addSchema:
    call pushApiUndo
    local id = next_id
    next_id += 1
    local created = make_schema(id, "Resource" + id, [{"name": "id", "type": "string"}, {"name": "title", "type": "string"}])
    local next_list = json.parse(json.stringify(schemas))
    next_list.push(created)
    schemas = next_list
    selected_schema_id = id
    active_section = "schema"
    status_message = "Added @Schema/Resource" + id

action deleteSelectedSchema:
    if selected_schema == null:
        stop
    call pushApiUndo
    local removed = selected_schema.name
    schemas = schemas.filter(s => s.id != selected_schema_id)
    routes = routes.map(r => r.expect == removed ? {...r, "expect": ""} : r)
    resolvers = resolvers.map(g => g.return_type == removed ? {...g, "return_type": "JSON"} : g)
    selected_schema_id = schemas.length > 0 ? schemas[0].id : 0
    status_message = "Deleted @Schema/" + removed

action renameSelectedSchema(val):
    if selected_schema == null:
        stop
    local old_name = selected_schema.name
    local new_name = sanitize_ident(val, old_name)
    if old_name == new_name:
        stop
    if schemas.some(s => s.name == new_name):
        status_message = "A data model already uses that name."
        stop
    call pushApiUndo
    schemas = schemas.map(s => s.id == selected_schema_id ? {...s, "name": new_name} : s)
    routes = routes.map(r => r.expect == old_name ? {...r, "expect": new_name} : r)
    resolvers = resolvers.map(g => g.return_type == old_name ? {...g, "return_type": new_name} : g)

action setNewFieldName(val):
    new_field_name = val

action setNewFieldType(val):
    new_field_type = val

action addSchemaField:
    if selected_schema == null:
        stop
    local fname = sanitize_ident(new_field_name, "")
    if fname == "":
        status_message = "Enter a valid field name first."
        stop
    call pushApiUndo
    local next_list = json.parse(json.stringify(schemas))
    for s in next_list:
        if s.id == selected_schema_id:
            local flds = s.fields ?? []
            flds.push({"name": fname, "type": new_field_type})
            s.fields = flds
    schemas = next_list
    new_field_name = ""
    status_message = "Added field " + fname + " to @Schema/" + sel_schema_name

action removeSchemaField(fname):
    if selected_schema == null:
        stop
    call pushApiUndo
    local next_list = json.parse(json.stringify(schemas))
    for s in next_list:
        if s.id == selected_schema_id:
            s.fields = (s.fields ?? []).filter(f => f.name != fname)
    schemas = next_list

action addRoute:
    call pushApiUndo
    local id = next_id
    next_id += 1
    local created = make_route(id, "GET", "/resource-" + id, "inherit", [], "", "", "", "inherit", 30, 60, "ip", "return {\"caller\": auth.sub, \"scheme\": auth.scheme, \"ok\": true}")
    local next_list = json.parse(json.stringify(routes))
    next_list.push(created)
    routes = next_list
    selected_route_id = id
    active_section = "route"
    status_message = "Added @Route/GET /resource-" + id

action deleteSelectedRoute:
    if selected_route == null:
        stop
    call pushApiUndo
    local removed_id = selected_route_id
    routes = routes.filter(r => r.id != removed_id)
    if sim_route_id == removed_id:
        call resetApiSimulation
    selected_route_id = routes.length > 0 ? routes[0].id : 0
    status_message = "Deleted route."

action updateRouteField(pair):
    call pushApiUndo
    local field = pair[0]
    local val = pair[1]
    local next_list = json.parse(json.stringify(routes))
    for r in next_list:
        if r.id == selected_route_id:
            if field == "rl_requests":
                r.rl_requests = clamp(round(to_number(val, 20)), 1, 100000)
            else if field == "rl_window":
                r.rl_window = clamp(round(to_number(val, 60)), 1, 86400)
            else:
                r[field] = val
    routes = next_list

action toggleRouteAuthScheme(sname):
    call pushApiUndo
    local next_list = json.parse(json.stringify(routes))
    for r in next_list:
        if r.id == selected_route_id:
            r.auth_mode = "custom"
            local cur = r.auth_schemes ?? []
            if cur.includes(sname):
                r.auth_schemes = cur.filter(x => x != sname)
            else:
                cur.push(sname)
                r.auth_schemes = cur
    routes = next_list

action applyRouteSnippet(kind):
    local snippet = "return {\"ok\": true}"
    match kind:
        "auth_echo":
            snippet = "return {\"sub\": auth.sub, \"scheme\": auth.scheme, \"roles\": auth.roles, \"scopes\": auth.scopes}"
        "create_echo":
            snippet = "return {\"created\": true, \"owner\": auth.sub, \"payload\": body}"
        "patch_echo":
            snippet = "return {\"updated\": id, \"actor\": auth.sub, \"changes\": body}"
    call updateRouteField ["steps", snippet]
    status_message = "Applied handler snippet."

action setOutputTab(tab):
    active_output_tab = tab
    show_code_panel = true

action setImportCode(val):
    import_code = val

action importApiRuneCode:
    local res = parse_api_rune(import_code)
    if (res.error ?? "") != "":
        status_message = res.error
        stop
    call pushApiUndo
    selected_preset = ""
    call applyApiSnapshot res.snapshot
    active_output_tab = "rune"
    active_section = "route"
    if api_protocol == "graphql":
        status_message = "Imported GraphQL API " + app_name + " (" + auth_schemes.length + " auth, " + schemas.length + " schemas, " + resolvers.length + " resolvers)."
    else:
        status_message = "Imported " + app_name + " (" + auth_schemes.length + " auth, " + schemas.length + " schemas, " + routes.length + " routes)."

action copyRuneSource:
    clipboard.copy(exported_rune)
    status_message = "Copied generated .rune API to clipboard."

action downloadRuneSource:
    local safe_name = sanitize_ident(app_name, "Api")
    local fname = safe_name.toLowerCase() + ".rune"
    download(fname, exported_rune)
    status_message = "Downloaded " + fname

action copyTestSuite:
    clipboard.copy(exported_tests)
    status_message = "Copied @Test suite to clipboard."

action downloadTestSuite:
    local safe_name = sanitize_ident(app_name, "Api")
    local fname = safe_name.toLowerCase() + ".test.rune"
    download(fname, exported_tests)
    status_message = "Downloaded " + fname

action copyOpenApiJson:
    clipboard.copy(exported_openapi)
    status_message = "Copied OpenAPI 3.0 JSON to clipboard."

action downloadOpenApiJson:
    local safe_name = sanitize_ident(app_name, "Api")
    local fname = safe_name.toLowerCase() + ".openapi.json"
    download(fname, exported_openapi)
    status_message = "Downloaded " + fname
parts/logic/graphql.rune
@Logic/api_studio

func make_resolver(id, kind, name, return_type, args, roles, scopes, steps):
    return {"id": id, "kind": kind, "name": name, "return_type": return_type, "args": args, "roles": roles, "scopes": scopes, "steps": steps}

func build_graphql_preset(key):
    match key:
        "starter_graphql":
            local s1 = make_schema(1, "Greeting", [{"name": "message", "type": "string"}, {"name": "target", "type": "string"}])
            local g1 = make_resolver(1, "query", "hello", "Greeting", [{"name": "name", "type": "string"}], "", "", "return { message: \"Hello from Vectrune GraphQL\", target: name }")
            return {"api_protocol": "graphql", "project_id": "starter_graphql", "app_name": "StarterGraphQL", "app_version": "1.0.0", "app_port": 4000, "swagger_enabled": false, "cors_mode": "all", "cors_origins": "", "default_auth": "none", "rate_limit_enabled": false, "rate_limit_requests": 60, "rate_limit_window": 60, "rate_limit_key": "ip", "auth_schemes": [], "schemas": [s1], "routes": [], "resolvers": [g1], "memory_collections": []}

        else:
            local a1 = make_auth_scheme(1, "JWTAuth", "jwt", {"algorithm": "HS256", "secret": "books-graphql-secret-change-me", "issuer": "books.vectrune.dev", "audience": "books-graphql", "leeway": 60, "expiration": 3600, "token_endpoint": "/auth/token", "entries": [{"k": "alice", "v": "alice-pass", "roles": "admin", "scopes": "books:read, books:write"}, {"k": "bob", "v": "bob-pass", "roles": "viewer", "scopes": "books:read"}]})
            local s1 = make_schema(1, "Book", [{"name": "id", "type": "number"}, {"name": "title", "type": "string"}, {"name": "author", "type": "string"}, {"name": "owner", "type": "string"}])
            local g1 = make_resolver(1, "query", "books", "Book", [], "", "books:read", "books = memory.get \"books\"\nreturn books")
            local g2 = make_resolver(2, "query", "book", "Book", [{"name": "id", "type": "number"}], "", "books:read", "books = memory.get \"books\"\nbook = books.find it.id == id\nreturn book")
            local g3 = make_resolver(3, "mutation", "addBook", "Book", [{"name": "title", "type": "string"}, {"name": "author", "type": "string"}], "admin", "books:write", "books = memory.get \"books\"\nnew_id = books.max it.id + 1\nnew_book = { id: new_id, title: title, author: author, owner: auth.sub }\nmemory.append \"books\" new_book\nreturn new_book")
            local mem = [{"name": "books", "records": [{"id": 1, "title": "The Rust Programming Language", "author": "Steve Klabnik", "owner": "alice"}, {"id": 2, "title": "Vectrune in Action", "author": "Dave Thomas", "owner": "alice"}]}]
            return {"api_protocol": "graphql", "project_id": "book_graphql", "app_name": "BookCatalogGraphQL", "app_version": "1.0.0", "app_port": 4000, "swagger_enabled": false, "cors_mode": "all", "cors_origins": "", "default_auth": "JWTAuth", "rate_limit_enabled": true, "rate_limit_requests": 4, "rate_limit_window": 60, "rate_limit_key": "auth", "auth_schemes": [a1], "schemas": [s1], "routes": [], "resolvers": [g1, g2, g3], "memory_collections": mem}

func gql_scalar_name(rune_type):
    match (rune_type ?? "string").toLowerCase():
        "number":
            return "Float!"
        "bool", "boolean":
            return "Boolean!"
        "string":
            return "String!"
        else:
            return (rune_type ?? "String") + "!"

func resolver_sdl_return(r):
    local rtype = (r.return_type ?? "").trim()
    if rtype == "" or rtype == "JSON":
        return "JSON"
    if r.kind == "query" and r.name.endsWith("s"):
        return "[" + rtype + "!]!"
    return rtype + "!"

func build_resolver_rows(res_list, sel_id):
    local out = []
    for r in res_list:
        local is_sel = r.id == sel_id
        local badge = r.kind == "mutation" ? "MUTATION" : "QUERY"
        local cls = r.kind == "mutation" ? "method-patch" : "method-get"
        local lock = ((r.roles ?? "").trim() != "" or (r.scopes ?? "").trim() != "") ? ("RBAC") : "App auth"
        local ret = resolver_sdl_return(r)
        out.push({"id": r.id, "kind": r.kind, "badge": badge, "cls": cls, "name": r.name, "ret": ret, "lock": lock, "selected": is_sel})
    return out

func format_graphql_sdl(schema_list, res_list):
    local out = ["scalar JSON", ""]
    for s in schema_list:
        local sname = sanitize_ident(s.name, "Record")
        out.push("type " + sname + " {")
        for f in (s.fields ?? []):
            local fname = sanitize_ident(f.name, "field")
            local ft = gql_scalar_name(f.type)
            out.push("  " + fname + ": " + ft)
        out.push("}")
        out.push("")
    local queries = res_list.filter(r => r.kind == "query")
    out.push("type Query {")
    out.push("  health: String!")
    for q in queries:
        local arg_parts = []
        for a in (q.args ?? []):
            local at = gql_scalar_name(a.type)
            arg_parts.push(a.name + ": " + at)
        local sig = q.name + (arg_parts.length > 0 ? ("(" + arg_parts.join(", ") + ")") : "")
        local ret = resolver_sdl_return(q)
        out.push("  " + sig + ": " + ret)
    out.push("}")
    local muts = res_list.filter(r => r.kind == "mutation")
    if muts.length > 0:
        out.push("")
        out.push("type Mutation {")
        for m in muts:
            local arg_parts = []
            for a in (m.args ?? []):
                local at = gql_scalar_name(a.type)
                arg_parts.push(a.name + ": " + at)
            local sig = m.name + (arg_parts.length > 0 ? ("(" + arg_parts.join(", ") + ")") : "")
            local ret = resolver_sdl_return(m)
            out.push("  " + sig + ": " + ret)
        out.push("}")
    return out.join("\n").trim() + "\n"

func format_graphql_rune(app_name, app_version, app_port, cors_mode, cors_origins, default_auth, rl_enabled, rl_req, rl_win, rl_key, auth_list, schema_list, res_list, mem_list):
    local out = ["#!RUNE", "# Generated by Rune API Studio (GraphQL)", ""]
    local safe_app = sanitize_ident(app_name, "MyGraphQLAPI")
    out.push("@App")
    out.push("name = " + safe_app)
    out.push("version = " + ((app_version ?? "").trim() != "" ? app_version.trim() : "1.0.0"))
    out.push("type = GraphQL")
    out.push("port = " + clamp(round(to_number(app_port, 4000)), 1, 65535))
    if cors_mode == "all":
        out.push("cors = true")
    else if cors_mode == "origins":
        local origins = split_csv(cors_origins)
        if origins.length > 0:
            out.push("cors = " + json.stringify(origins))
    if (default_auth ?? "") != "" and default_auth != "none":
        out.push("default_auth = " + default_auth)
    if rl_enabled:
        local rl_obj = {"requests": clamp(round(to_number(rl_req, 60)), 1, 100000), "window": clamp(round(to_number(rl_win, 60)), 1, 86400), "key": (rl_key ?? "ip")}
        out.push("rate_limit = " + json.stringify(rl_obj))
    out.push("")

    for a in auth_list:
        local aname = sanitize_ident(a.name, "AuthScheme")
        out.push("@Authentication/" + aname)
        out.push("type = " + a.type)
        match a.type:
            "jwt":
                out.push("algorithm = " + (a.algorithm != "" ? a.algorithm : "HS256"))
                if (a.secret ?? "") != "":
                    out.push("secret = \"" + a.secret + "\"")
                if (a.issuer ?? "") != "":
                    out.push("issuer = \"" + a.issuer + "\"")
                if (a.audience ?? "") != "":
                    out.push("audience = \"" + a.audience + "\"")
                if to_number(a.expiration, 3600) > 0:
                    out.push("expiration = " + round(to_number(a.expiration, 3600)))
                if (a.token_endpoint ?? "") != "":
                    out.push("token_endpoint = \"" + a.token_endpoint + "\"")
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("users:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"username": e.k, "password": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
            "oauth2":
                if (a.introspection_url ?? "") != "":
                    out.push("introspection_url = \"" + a.introspection_url + "\"")
                if (a.issuer ?? "") != "":
                    out.push("issuer = \"" + a.issuer + "\"")
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("tokens:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"token": e.k, "sub": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
            "api_key":
                out.push("header = \"" + ((a.header ?? "") != "" ? a.header : "X-API-Key") + "\"")
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("keys:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"key": e.k, "sub": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
            "basic":
                out.push("realm = \"" + ((a.realm ?? "") != "" ? a.realm : "Vectrune API") + "\"")
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("users:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"username": e.k, "password": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
            "bearer", "cookie":
                if a.type == "cookie":
                    out.push("cookie_name = \"" + ((a.cookie_name ?? "") != "" ? a.cookie_name : "vectrune_session") + "\"")
                    if (a.secret ?? "") != "":
                        out.push("secret = \"" + a.secret + "\"")
                local entries = a.entries ?? []
                if entries.length > 0:
                    out.push("tokens:")
                    for e in entries:
                        local rlist = split_csv(e.roles)
                        local slist = split_csv(e.scopes)
                        local row = {"token": e.k, "sub": e.v, "roles": rlist, "scopes": slist}
                        out.push("    " + json.stringify(row))
            "hmac":
                out.push("header = \"" + ((a.header ?? "") != "" ? a.header : "X-Webhook-Signature") + "\"")
                out.push("secret = \"" + (a.secret ?? "webhook-secret") + "\"")
        out.push("")

    for s in schema_list:
        local sname = sanitize_ident(s.name, "Record")
        out.push("@Schema/" + sname)
        for f in (s.fields ?? []):
            local fname = sanitize_ident(f.name, "field")
            out.push(fname + " = " + (f.type ?? "string"))
        out.push("")

    for r in res_list:
        local kind_hdr = r.kind == "mutation" ? "Mutation" : "Query"
        local rtype = (r.return_type ?? "").trim()
        local hdr = "@GraphQL/" + kind_hdr
        if rtype != "" and rtype != "JSON" and !(r.kind == "query" and r.name.endsWith("s")):
            hdr = hdr + "/" + rtype
        out.push(hdr)
        local rroles = split_csv(r.roles)
        if rroles.length > 0:
            out.push("roles = " + json.stringify(rroles))
        local rscopes = split_csv(r.scopes)
        if rscopes.length > 0:
            out.push("scopes = " + json.stringify(rscopes))
        local arg_parts = []
        for a in (r.args ?? []):
            arg_parts.push(a.name + ": " + (a.type ?? "string"))
        local sig = sanitize_ident(r.name, "field") + (arg_parts.length > 0 ? ("(" + arg_parts.join(", ") + ")") : "")
        out.push(sig + ":")
        local raw_steps = (r.steps ?? "").trim()
        if raw_steps == "":
            out.push("    return {}")
        else:
            for line in raw_steps.split("\n"):
                if line.trim() != "":
                    out.push("    " + line.trim())
        out.push("")

    for m in (mem_list ?? []):
        out.push("@Memory/" + sanitize_ident(m.name, "items"))
        for rec in (m.records ?? []):
            local rec_keys = keys(rec)
            local first = true
            for k in rec_keys:
                local v = rec[k]
                local v_str = v.split != null ? json.stringify(v) : ("" + v)
                out.push((first ? "+ " : "  ") + k + " = " + v_str)
                first = false
        out.push("")

    return out.join("\n").trim() + "\n"

func format_graphql_tests(app_name, default_auth, res_list):
    local safe_app = sanitize_ident(app_name, "GraphQLApi")
    local out = ["#!RUNE", "# Auto-generated native GraphQL tests — run with: vectrune test", ""]
    local has_auth = (default_auth ?? "") != "" and default_auth != "none"
    if has_auth:
        out.push("@Test/" + safe_app + "/RejectsUnauthGraphQL")
        out.push("run:")
        out.push("    req = { method: \"POST\", path: \"/graphql\", body: \"{\\\"query\\\":\\\"{ health }\\\"}\" }")
        out.push("    res = test-request req")
        out.push("    assert res.status == 401")
    else:
        out.push("@Test/" + safe_app + "/HealthQuery")
        out.push("run:")
        out.push("    req = { method: \"POST\", path: \"/graphql\", body: \"{\\\"query\\\":\\\"{ health }\\\"}\" }")
        out.push("    res = test-request req")
        out.push("    assert res.status == 200")
        out.push("    assert res.text contains \"OK\"")
    return out.join("\n").trim() + "\n"

func build_sample_gql_operation(resolver, schema_list):
    if resolver == null:
        return {"query": "query {\n  health\n}", "variables": "{}"}
    local op_kind = resolver.kind == "mutation" ? "mutation" : "query"
    local op_name = resolver.name.slice(0, 1).toUpperCase() + resolver.name.slice(1)
    local var_defs = []
    local call_args = []
    local vars_obj = {}
    for a in (resolver.args ?? []):
        local gql_t = gql_scalar_name(a.type)
        var_defs.push("$" + a.name + ": " + gql_t)
        call_args.push(a.name + ": $" + a.name)
        match (a.type ?? "string").toLowerCase():
            "number":
                vars_obj[a.name] = 1
            "bool":
                vars_obj[a.name] = true
            else:
                if a.name == "name":
                    vars_obj[a.name] = "World"
                else if a.name == "title":
                    vars_obj[a.name] = "New Book"
                else if a.name == "author":
                    vars_obj[a.name] = "Ada Lovelace"
                else:
                    vars_obj[a.name] = "sample"

    local sel_fields = []
    local matched_schema = schema_list.find(s => s.name == resolver.return_type)
    if matched_schema != null:
        for f in (matched_schema.fields ?? []):
            sel_fields.push(f.name)

    local header_args = var_defs.length > 0 ? ("(" + var_defs.join(", ") + ")") : ""
    local field_args = call_args.length > 0 ? ("(" + call_args.join(", ") + ")") : ""
    local body_sel = sel_fields.length > 0 ? (" {\n    " + sel_fields.join("\n    ") + "\n  }") : ""
    local q_str = op_kind + " " + op_name + header_args + " {\n  " + resolver.name + field_args + body_sel + "\n}"
    return {"query": q_str, "variables": json.stringify(vars_obj, null, 2)}

action setApiProtocol(proto):
    if proto == api_protocol:
        stop
    if proto == "graphql":
        call selectPreset "book_graphql"
    else:
        call selectPreset "secure_orders"

action selectResolver(id):
    selected_resolver_id = to_number(id, selected_resolver_id)
    active_section = "route"

action addResolver(kind):
    call pushApiUndo
    local id = next_id
    next_id += 1
    local k = kind == "mutation" ? "mutation" : "query"
    local rname = k == "mutation" ? ("createItem" + id) : ("item" + id)
    local rtype = schemas.length > 0 ? schemas[0].name : "JSON"
    local created = make_resolver(id, k, rname, rtype, [], "", "", "return { caller: auth.sub, ok: true }")
    local next_list = deep_clone(resolvers)
    next_list.push(created)
    resolvers = next_list
    selected_resolver_id = id
    active_section = "route"
    status_message = "Added GraphQL " + k + ": " + rname

action deleteSelectedResolver:
    if selected_resolver == null:
        stop
    call pushApiUndo
    resolvers = resolvers.filter(r => r.id != selected_resolver_id)
    selected_resolver_id = resolvers.length > 0 ? resolvers[0].id : 0
    status_message = "Deleted GraphQL resolver."

action updateResolverField(pair):
    local field = pair[0]
    local val = pair[1]
    local next_list = deep_clone(resolvers)
    for r in next_list:
        if r.id == selected_resolver_id:
            if field == "name":
                r.name = sanitize_ident(val, r.name)
            else:
                r[field] = val
    resolvers = next_list

action setNewArgName(val):
    new_arg_name = val

action setNewArgType(val):
    new_arg_type = val

action addResolverArg:
    if selected_resolver == null:
        stop
    local aname = sanitize_ident(new_arg_name, "")
    if aname == "":
        status_message = "Enter an argument name first."
        stop
    call pushApiUndo
    local next_list = deep_clone(resolvers)
    for r in next_list:
        if r.id == selected_resolver_id:
            local args = r.args ?? []
            args.push({"name": aname, "type": new_arg_type})
            r.args = args
    resolvers = next_list
    new_arg_name = ""
    status_message = "Added argument " + aname

action removeResolverArg(aname):
    if selected_resolver == null:
        stop
    call pushApiUndo
    local next_list = deep_clone(resolvers)
    for r in next_list:
        if r.id == selected_resolver_id:
            r.args = (r.args ?? []).filter(a => a.name != aname)
    resolvers = next_list

action applyResolverSnippet(kind):
    local snippet = "return { ok: true }"
    match kind:
        "mem_list":
            snippet = "items = memory.get \"books\"\nreturn items"
        "mem_find":
            snippet = "items = memory.get \"books\"\nfound = items.find it.id == id\nreturn found"
        "auth_echo":
            snippet = "return { caller: auth.sub, scheme: auth.scheme, roles: auth.roles }"
    call updateResolverField ["steps", snippet]
    status_message = "Applied resolver snippet."

func build_sim_gql_arg_rows(resolver, vars_str):
    local out = []
    if resolver == null:
        return out
    local parsed = json.try_parse(vars_str)
    if parsed == null:
        parsed = {}
    for a in (resolver.args ?? []):
        local existing = parsed[a.name]
        local val_str = existing != null ? ("" + existing) : ""
        out.push({"name": a.name, "type": (a.type ?? "string"), "value": val_str})
    return out

action selectSimResolver(id):
    sim_resolver_id = to_number(id, sim_resolver_id)
    local res = resolvers.find(r => r.id == sim_resolver_id)
    local sample = build_sample_gql_operation(res, schemas)
    sim_gql_query = sample.query
    sim_gql_vars = sample.variables

action openResolverInSimulator(id):
    call selectSimResolver id
    active_section = "simulator"
    call runSimRequest

action setSimGqlQuery(val):
    sim_gql_query = val

action setSimGqlVars(val):
    sim_gql_vars = val

action setSimGqlArg(aname, atype, val):
    local parsed = json.try_parse(sim_gql_vars)
    if parsed == null:
        parsed = {}
    local t = (atype ?? "string").toLowerCase()
    if t == "number":
        parsed[aname] = to_number(val, 0)
    else if t == "bool" or t == "boolean":
        parsed[aname] = (val == "true" or val == true)
    else:
        parsed[aname] = "" + val
    sim_gql_vars = json.stringify(parsed, null, 2)

action copyGraphqlSdl:
    clipboard.copy(exported_sdl)
    status_message = "Copied GraphQL SDL schema to clipboard."

action downloadGraphqlSdl:
    local safe_name = sanitize_ident(app_name, "schema")
    local fname = safe_name.toLowerCase() + ".graphql"
    download(fname, exported_sdl)
    status_message = "Downloaded " + fname
parts/logic/presets.rune
@Logic/api_studio

func make_auth_scheme(id, name, stype, cfg):
    local entries = cfg.entries ?? []
    return {"id": id, "name": name, "type": stype, "algorithm": cfg.algorithm ?? "HS256", "secret": cfg.secret ?? "", "public_key": cfg.public_key ?? "", "jwks_url": cfg.jwks_url ?? "", "issuer": cfg.issuer ?? "", "audience": cfg.audience ?? "", "leeway": cfg.leeway ?? 60, "expiration": cfg.expiration ?? 3600, "token_endpoint": cfg.token_endpoint ?? "", "roles_claim": cfg.roles_claim ?? "roles", "scopes_claim": cfg.scopes_claim ?? "scope", "introspection_url": cfg.introspection_url ?? "", "client_id": cfg.client_id ?? "", "client_secret": cfg.client_secret ?? "", "authorization_url": cfg.authorization_url ?? "", "token_url": cfg.token_url ?? "", "header": cfg.header ?? "X-API-Key", "query": cfg.query ?? "", "realm": cfg.realm ?? "Vectrune API", "prefix": cfg.prefix ?? "sha256=", "encoding": cfg.encoding ?? "hex", "cookie_name": cfg.cookie_name ?? "vectrune_session", "sub": cfg.sub ?? "webhook-sender", "roles": cfg.roles ?? "", "scopes": cfg.scopes ?? "", "entries": entries}

func make_schema(id, name, fields):
    return {"id": id, "name": name, "fields": fields}

func make_route(id, method, path, auth_mode, auth_schemes, roles, scopes, expect, rl_mode, rl_requests, rl_window, rl_key, steps):
    return {"id": id, "method": method, "path": path, "auth_mode": auth_mode, "auth_schemes": auth_schemes, "roles": roles, "scopes": scopes, "expect": expect, "rl_mode": rl_mode, "rl_requests": rl_requests, "rl_window": rl_window, "rl_key": rl_key, "steps": steps}

func build_api_preset(key):
    match key:
        "hello_world":
            local r1 = make_route(1, "GET", "/health", "none", [], "", "", "", "none", 60, 60, "ip", "respond 200 \"OK\"")
            local r2 = make_route(2, "GET", "/hello/{name}", "none", [], "", "", "", "inherit", 60, 60, "ip", "return {\"message\": \"Hello from Vectrune\", \"name\": name}")
            local r3 = make_route(3, "POST", "/echo", "none", [], "", "", "", "inherit", 60, 60, "ip", "respond 201 {\"echo\": body}")
            return {"project_id": "hello_world", "app_name": "ExampleAPI", "app_version": "1.0.0", "app_port": 3000, "swagger_enabled": true, "cors_mode": "all", "cors_origins": "", "default_auth": "none", "rate_limit_enabled": false, "rate_limit_requests": 60, "rate_limit_window": 60, "rate_limit_key": "ip", "auth_schemes": [], "schemas": [], "routes": [r1, r2, r3]}

        "saas_multi_auth":
            local a1 = make_auth_scheme(1, "StaffBasic", "basic", {"realm": "SaaS Operations", "entries": [{"k": "ops", "v": "ops-secret", "roles": "admin, ops", "scopes": "metrics:read, billing:write"}, {"k": "viewer", "v": "view-only", "roles": "viewer", "scopes": "metrics:read"}]})
            local a2 = make_auth_scheme(2, "PartnerKey", "api_key", {"header": "X-API-Key", "query": "api_key", "entries": [{"k": "pk_live_partner_01", "v": "partner-acme", "roles": "partner", "scopes": "metrics:read, events:write"}]})
            local a3 = make_auth_scheme(3, "ServiceToken", "bearer", {"entries": [{"k": "svc_tok_billing_99", "v": "billing-worker", "roles": "service", "scopes": "billing:write"}]})
            local a4 = make_auth_scheme(4, "WebSession", "cookie", {"cookie_name": "saas_session", "secret": "session-hmac-key-change-me", "entries": [{"k": "sess_demo_alice", "v": "[email protected]", "roles": "member", "scopes": "metrics:read"}]})
            local s1 = make_schema(1, "MetricEvent", [{"name": "source", "type": "string"}, {"name": "value", "type": "number"}, {"name": "alert", "type": "bool"}])
            local r1 = make_route(1, "GET", "/health", "none", [], "", "", "", "none", 60, 60, "ip", "return {\"status\": \"ok\", \"service\": \"SaaSGateway\"}")
            local r2 = make_route(2, "GET", "/metrics", "custom", ["StaffBasic", "PartnerKey", "WebSession"], "", "metrics:read", "", "inherit", 60, 60, "ip", "return {\"caller\": auth.sub, \"scheme\": auth.scheme, \"scopes\": auth.scopes}")
            local r3 = make_route(3, "POST", "/events", "custom", ["PartnerKey"], "", "events:write", "MetricEvent", "custom", 30, 60, "auth", "return {\"accepted\": true, \"by\": auth.sub, \"event\": body}")
            local r4 = make_route(4, "PATCH", "/billing/plan", "custom", ["StaffBasic", "ServiceToken"], "", "billing:write", "", "custom", 5, 60, "auth", "return {\"updated\": true, \"actor\": auth.sub, \"auth_type\": auth.type}")
            return {"project_id": "saas_multi_auth", "app_name": "SaaSMultiAuthAPI", "app_version": "1.2.0", "app_port": 8080, "swagger_enabled": true, "cors_mode": "all", "cors_origins": "", "default_auth": "StaffBasic", "rate_limit_enabled": true, "rate_limit_requests": 100, "rate_limit_window": 60, "rate_limit_key": "ip", "auth_schemes": [a1, a2, a3, a4], "schemas": [s1], "routes": [r1, r2, r3, r4]}

        "webhook_gateway":
            local a1 = make_auth_scheme(1, "StripeWebhook", "hmac", {"header": "X-Webhook-Signature", "secret": "whsec_demo_signing_key", "prefix": "sha256=", "encoding": "hex", "sub": "stripe-events", "roles": "webhook", "scopes": "webhooks:ingest"})
            local a2 = make_auth_scheme(2, "AdminBearer", "bearer", {"entries": [{"k": "adm_tok_super_secret", "v": "platform-admin", "roles": "admin", "scopes": "webhooks:admin, webhooks:read"}]})
            local s1 = make_schema(1, "WebhookPayload", [{"name": "event_id", "type": "string"}, {"name": "kind", "type": "string"}])
            local r1 = make_route(1, "POST", "/webhooks/payments", "custom", ["StripeWebhook"], "", "webhooks:ingest", "WebhookPayload", "custom", 120, 60, "ip", "return {\"verified\": true, \"sender\": auth.sub, \"payload\": body}")
            local r2 = make_route(2, "GET", "/admin/deliveries", "custom", ["AdminBearer"], "admin", "webhooks:read", "", "inherit", 30, 60, "auth", "return {\"admin\": auth.sub, \"deliveries\": []}")
            local r3 = make_route(3, "GET", "/status", "none", [], "", "", "", "none", 60, 60, "ip", "return {\"gateway\": \"online\"}")
            return {"project_id": "webhook_gateway", "app_name": "WebhookGatewayAPI", "app_version": "1.0.0", "app_port": 8081, "swagger_enabled": true, "cors_mode": "off", "cors_origins": "", "default_auth": "AdminBearer", "rate_limit_enabled": true, "rate_limit_requests": 60, "rate_limit_window": 60, "rate_limit_key": "ip", "auth_schemes": [a1, a2], "schemas": [s1], "routes": [r1, r2, r3]}

        "blank_rest":
            local a1 = make_auth_scheme(1, "AppJWT", "jwt", {"algorithm": "HS256", "secret": "replace-with-env-secret", "issuer": "starter-api", "audience": "starter-clients", "token_endpoint": "/auth/token", "entries": [{"k": "admin", "v": "change-me", "roles": "admin", "scopes": "items:read, items:write"}]})
            local s1 = make_schema(1, "Item", [{"name": "id", "type": "string"}, {"name": "name", "type": "string"}])
            local r1 = make_route(1, "GET", "/health", "none", [], "", "", "", "none", 60, 60, "ip", "return {\"ok\": true}")
            local r2 = make_route(2, "GET", "/items", "inherit", [], "", "items:read", "", "inherit", 60, 60, "ip", "return {\"user\": auth.sub, \"items\": []}")
            local r3 = make_route(3, "POST", "/items", "inherit", [], "admin", "items:write", "Item", "inherit", 60, 60, "ip", "return {\"created\": body, \"by\": auth.sub}")
            return {"project_id": "blank_rest", "app_name": "StarterRestAPI", "app_version": "0.1.0", "app_port": 8080, "swagger_enabled": true, "cors_mode": "all", "cors_origins": "", "default_auth": "AppJWT", "rate_limit_enabled": false, "rate_limit_requests": 60, "rate_limit_window": 60, "rate_limit_key": "ip", "auth_schemes": [a1], "schemas": [s1], "routes": [r1, r2, r3]}

        else:
            local a1 = make_auth_scheme(1, "JWTAuth", "jwt", {"algorithm": "HS256", "secret": "orders-jwt-secret-change-me", "issuer": "orders.vectrune.dev", "audience": "orders-api", "leeway": 60, "expiration": 3600, "token_endpoint": "/auth/token", "entries": [{"k": "alice", "v": "alice-pass", "roles": "admin, editor", "scopes": "orders:read, orders:write, admin:audit"}, {"k": "bob", "v": "bob-pass", "roles": "viewer", "scopes": "orders:read"}]})
            local a2 = make_auth_scheme(2, "OAuth2IdP", "oauth2", {"introspection_url": "", "jwks_url": "", "issuer": "https://idp.example.com", "audience": "orders-api", "authorization_url": "https://idp.example.com/oauth/authorize", "token_url": "https://idp.example.com/oauth/token", "entries": [{"k": "oauth_tok_checkout", "v": "checkout-client", "roles": "service", "scopes": "orders:read, orders:write"}]})
            local a3 = make_auth_scheme(3, "PartnerKey", "api_key", {"header": "X-API-Key", "query": "", "entries": [{"k": "pk_orders_partner_77", "v": "partner-fulfillment", "roles": "partner", "scopes": "orders:read"}]})
            local s1 = make_schema(1, "Order", [{"name": "id", "type": "string"}, {"name": "item", "type": "string"}, {"name": "amount", "type": "number"}])
            local s2 = make_schema(2, "OrderPatch", [{"name": "status", "type": "string"}, {"name": "notes", "type": "string"}])
            local r1 = make_route(1, "GET", "/health", "none", [], "", "", "", "none", 60, 60, "ip", "return {\"status\": \"healthy\", \"auth\": auth.authenticated}")
            local r2 = make_route(2, "GET", "/orders", "custom", ["JWTAuth", "OAuth2IdP", "PartnerKey"], "", "orders:read", "", "inherit", 60, 60, "ip", "return {\"caller\": auth.sub, \"scheme\": auth.scheme, \"roles\": auth.roles, \"orders\": []}")
            local r3 = make_route(3, "POST", "/orders", "custom", ["JWTAuth", "OAuth2IdP"], "", "orders:write", "Order", "custom", 3, 60, "auth", "respond 201 {\"created\": true, \"owner\": auth.sub, \"order\": body}")
            local r4 = make_route(4, "PATCH", "/orders/{id}", "inherit", [], "admin, editor", "orders:write", "OrderPatch", "inherit", 60, 60, "ip", "return {\"updated\": id, \"actor\": auth.sub, \"patch\": body}")
            local r5 = make_route(5, "GET", "/admin/audit", "inherit", [], "admin", "admin:audit", "", "custom", 2, 60, "auth", "return {\"auditor\": auth.sub, \"scheme\": auth.scheme, \"events\": 14}")
            return {"project_id": "secure_orders", "app_name": "SecureOrdersAPI", "app_version": "1.0.0", "app_port": 8080, "swagger_enabled": true, "cors_mode": "origins", "cors_origins": "https://app.example.com, http://localhost:3000", "default_auth": "JWTAuth", "rate_limit_enabled": true, "rate_limit_requests": 60, "rate_limit_window": 60, "rate_limit_key": "ip", "auth_schemes": [a1, a2, a3], "schemas": [s1, s2], "routes": [r1, r2, r3, r4, r5]}

func auth_type_description(stype):
    match stype:
        "jwt":
            return "Verifies Bearer JWTs (HS256/384/512, RS256, ES256, or OIDC JWKS), checks iss/aud/exp, and optionally serves a token_endpoint."
        "oauth2":
            return "Validates OAuth2 Bearer access tokens via RFC 7662 introspection_url, JWKS/JWT verification, or local tokens map, and emits OpenAPI oauth2 flows."
        "api_key":
            return "Extracts API keys from a custom HTTP header (and optional query param) with constant-time matching and per-key sub/roles/scopes."
        "basic":
            return "Parses Authorization: Basic credentials with WWW-Authenticate realm challenge and supports plaintext or sha256: hashed passwords."
        "bearer":
            return "Validates opaque Authorization: Bearer service tokens with constant-time comparison and per-token roles/scopes."
        "hmac":
            return "Verifies HMAC-SHA256 request body signatures (hex or base64, optional sha256= prefix) for secure webhook ingestion."
        "cookie":
            return "Authenticates browser sessions from a Cookie header using HMAC-SHA256 signed cookies or a static token table."
        else:
            return "Custom authentication scheme."

func auth_type_title(stype):
    match stype:
        "jwt":
            return "JWT Bearer Token"
        "oauth2":
            return "OAuth 2.0 / OIDC"
        "api_key":
            return "API Key"
        "basic":
            return "HTTP Basic Auth"
        "bearer":
            return "Opaque Bearer Token"
        "hmac":
            return "HMAC-SHA256 Webhook"
        "cookie":
            return "Signed Session Cookie"
        else:
            return "Authentication Scheme"

func auth_type_label(stype):
    match stype:
        "jwt":
            return "JWT"
        "oauth2":
            return "OAuth2"
        "api_key":
            return "API Key"
        "basic":
            return "Basic"
        "bearer":
            return "Bearer"
        "hmac":
            return "HMAC"
        "cookie":
            return "Cookie"
        else:
            return "Auth"

func route_auth_summary(route, def_auth):
    if route == null:
        return "None"
    local eff = effective_route_auth_names(route, def_auth)
    if eff.length == 0:
        return "Public (no auth)"
    return eff.join(" or ")

func route_access_summary(route):
    if route == null:
        return "Any authenticated caller"
    local r = (route.roles ?? "").trim()
    local s = (route.scopes ?? "").trim()
    if r == "" and s == "":
        return "Any authenticated caller"
    local parts = []
    if r != "":
        parts.push("roles: " + r)
    if s != "":
        parts.push("scopes: " + s)
    return parts.join(" · ")

func route_rl_summary(route, rl_enabled, rl_req, rl_win, rl_key):
    if route == null:
        return "Off"
    if route.rl_mode == "none":
        return "Exempt (unlimited)"
    if route.rl_mode == "custom":
        return route.rl_requests + " / " + route.rl_window + "s (" + route.rl_key + ")"
    if rl_enabled:
        return rl_req + " / " + rl_win + "s (" + rl_key + ")"
    return "Off"

func split_csv(raw):
    local out = []
    local text = (raw ?? "").trim()
    if text == "":
        return out
    for part in text.split(","):
        local p = part.trim()
        if p != "":
            out.push(p)
    return out

func effective_route_auth_names(route, def_auth):
    if route == null:
        return []
    if route.auth_mode == "none":
        return []
    if route.auth_mode == "custom":
        return route.auth_schemes ?? []
    if (def_auth ?? "") != "" and def_auth != "none":
        return [def_auth]
    return []

func count_protected_routes(rlist, def_auth):
    local n = 0
    for r in rlist:
        local eff = effective_route_auth_names(r, def_auth)
        if eff.length > 0:
            n += 1
    return n

func build_auth_rows(alist, sel_id):
    local out = []
    for a in alist:
        local badge = auth_type_label(a.type)
        local is_sel = a.id == sel_id
        local count = (a.entries ?? []).length
        local meta = a.type == "hmac" ? (a.header ?? "X-Signature") : (count + " cred" + (count == 1 ? "" : "s"))
        out.push({"id": a.id, "name": a.name, "badge": badge, "type": a.type, "meta": meta, "selected": is_sel})
    return out

func build_schema_rows(slist, sel_id):
    local out = []
    for s in slist:
        local count = (s.fields ?? []).length
        local is_sel = s.id == sel_id
        out.push({"id": s.id, "name": s.name, "meta": count + " field" + (count == 1 ? "" : "s"), "selected": is_sel})
    return out

func build_route_rows(rlist, sel_id, def_auth):
    local out = []
    for r in rlist:
        local eff = effective_route_auth_names(r, def_auth)
        local lock_txt = eff.length > 0 ? eff.join(" | ") : "PUBLIC"
        local is_pub = eff.length == 0
        local is_sel = r.id == sel_id
        local m_lower = r.method.toLowerCase()
        out.push({"id": r.id, "method": r.method, "method_cls": "method-" + m_lower, "path": r.path, "lock": lock_txt, "is_public": is_pub, "selected": is_sel})
    return out

func build_route_scheme_toggles(alist, active_names):
    local out = []
    for a in alist:
        local is_on = active_names.includes(a.name)
        local badge = auth_type_label(a.type)
        out.push({"name": a.name, "badge": badge, "active": is_on})
    return out

func describe_route_policy(route, def_auth, rl_enabled, rl_req, rl_win, rl_key):
    if route == null:
        return "Select a route to inspect its effective policy."
    local eff = effective_route_auth_names(route, def_auth)
    local auth_txt = eff.length > 0 ? ("Auth: " + eff.join(" OR ")) : "Auth: Public (no auth)"
    local roles_txt = (route.roles ?? "").trim() != "" ? (" · Roles: [" + route.roles.trim() + "]") : ""
    local scopes_txt = (route.scopes ?? "").trim() != "" ? (" · Scopes: [" + route.scopes.trim() + "]") : ""
    local rl_txt = " · Rate Limit: off"
    if route.rl_mode == "none":
        rl_txt = " · Rate Limit: exempt (none)"
    else if route.rl_mode == "custom":
        rl_txt = " · Rate Limit: " + route.rl_requests + " req / " + route.rl_window + "s (key=" + route.rl_key + ")"
    else if rl_enabled:
        rl_txt = " · Rate Limit: " + rl_req + " req / " + rl_win + "s (key=" + rl_key + ", inherited)"
    return route.method + " " + route.path + " — " + auth_txt + roles_txt + scopes_txt + rl_txt
parts/logic/simulator.rune
@Logic/api_studio

func sample_param_value(pname):
    match pname:
        "name":
            return "world"
        "id":
            return "ord-42"
        else:
            return "demo-1"

func build_sim_param_rows(route, param_map):
    local out = []
    if route == null:
        return out
    local seen = []
    local normalized = normalize_api_path(route.path)
    for seg in normalized.split("/"):
        if seg.startsWith("{") and seg.endsWith("}") and seg.length > 2:
            local pname = seg.slice(1, seg.length - 1).trim()
            if pname != "" and !seen.includes(pname):
                seen.push(pname)
                local existing = param_map != null ? param_map[pname] : null
                local val = (existing != null and ("" + existing) != "") ? ("" + existing) : sample_param_value(pname)
                out.push({"name": pname, "value": val})
    return out

func resolve_sim_path(raw_path, param_map):
    local resolved = normalize_api_path(raw_path)
    for seg in resolved.split("/"):
        if seg.startsWith("{") and seg.endsWith("}") and seg.length > 2:
            local pname = seg.slice(1, seg.length - 1).trim()
            local existing = param_map != null ? param_map[pname] : null
            local pval = (existing != null and ("" + existing).trim() != "") ? ("" + existing).trim() : sample_param_value(pname)
            resolved = replace_all(resolved, seg, pval)
    return resolved

func build_sim_curl(route, scheme_obj, user, pass, tok, api_key, hmac_valid, body_str, port, param_map):
    local method = route.method == "CRUD" ? "GET" : route.method
    local resolved_path = resolve_sim_path(route.path, param_map)
    local url = "http://127.0.0.1:" + port + resolved_path
    local parts = ["curl -i -X " + method + " \"" + url + "\""]
    if scheme_obj != null:
        match scheme_obj.type:
            "jwt":
                parts.push("-H \"Authorization: Bearer <jwt-for-" + (user != "" ? user : "user") + ">\"")
            "oauth2", "bearer":
                parts.push("-H \"Authorization: Bearer " + (tok != "" ? tok : "<token>") + "\"")
            "api_key":
                parts.push("-H \"" + (scheme_obj.header != "" ? scheme_obj.header : "X-API-Key") + ": " + (api_key != "" ? api_key : "<key>") + "\"")
            "basic":
                parts.push("-u \"" + user + ":" + pass + "\"")
            "hmac":
                local sig = hmac_valid ? (scheme_obj.prefix + "<valid-hmac-sha256>") : (scheme_obj.prefix + "deadbeef_invalid")
                parts.push("-H \"" + (scheme_obj.header != "" ? scheme_obj.header : "X-Webhook-Signature") + ": " + sig + "\"")
            "cookie":
                parts.push("-H \"Cookie: " + (scheme_obj.cookie_name != "" ? scheme_obj.cookie_name : "vectrune_session") + "=" + (tok != "" ? tok : "<session>") + "\"")
    if method == "POST" or method == "PUT" or method == "PATCH":
        parts.push("-H \"Content-Type: application/json\"")
        parts.push("-d '" + body_str + "'")
    return parts.join(" \\\n  ")

func build_gql_curl(scheme_obj, user, pass, tok, api_key, hmac_valid, body_str, port):
    local url = "http://127.0.0.1:" + port + "/graphql"
    local parts = ["curl -i -X POST \"" + url + "\""]
    if scheme_obj != null:
        match scheme_obj.type:
            "jwt":
                parts.push("-H \"Authorization: Bearer <jwt-for-" + (user != "" ? user : "user") + ">\"")
            "oauth2", "bearer":
                parts.push("-H \"Authorization: Bearer " + (tok != "" ? tok : "<token>") + "\"")
            "api_key":
                parts.push("-H \"" + (scheme_obj.header != "" ? scheme_obj.header : "X-API-Key") + ": " + (api_key != "" ? api_key : "<key>") + "\"")
            "basic":
                parts.push("-u \"" + user + ":" + pass + "\"")
            "hmac":
                local sig = hmac_valid ? (scheme_obj.prefix + "<valid-hmac-sha256>") : (scheme_obj.prefix + "deadbeef_invalid")
                parts.push("-H \"" + (scheme_obj.header != "" ? scheme_obj.header : "X-Webhook-Signature") + ": " + sig + "\"")
            "cookie":
                parts.push("-H \"Cookie: " + (scheme_obj.cookie_name != "" ? scheme_obj.cookie_name : "vectrune_session") + "=" + (tok != "" ? tok : "<session>") + "\"")
    parts.push("-H \"Content-Type: application/json\"")
    parts.push("-d '" + body_str + "'")
    return parts.join(" \\\n  ")

action resetApiSimulation:
    stop-timer
    local _r = rune.emulate_reset()
    sim_is_sending = false
    sim_pending_mode = ""
    sim_path_params = {}
    sim_buckets = {}
    sim_request_count = 0
    sim_last_status = 0
    sim_last_headers = []
    sim_last_body = ""
    sim_last_auth_json = ""
    sim_last_curl = ""
    sim_auth_mode = "none"
    sim_route_id = 0
    sim_resolver_id = 0
    if api_protocol == "graphql":
        sim_last_reason = "Choose a resolver and click Execute Query, or try a quick demo."
        if default_auth != "" and default_auth != "none":
            call selectSimAuthMode default_auth
        if resolvers.length > 0:
            call selectSimResolver resolvers[0].id
        else:
            sim_gql_query = "query {\n  health\n}"
            sim_gql_vars = "{}"
    else:
        sim_last_reason = "Choose a route and click Send Request, or try a quick demo."
        if routes.length > 0:
            local target = routes.length > 1 ? routes[1] : routes[0]
            call selectSimRoute target.id

action selectSimRoute(route_id):
    sim_route_id = to_number(route_id, sim_route_id)
    local route = routes.find(r => r.id == sim_route_id)
    if route != null:
        local eff = effective_route_auth_names(route, default_auth)
        if eff.length > 0:
            call selectSimAuthMode eff[0]
        else:
            sim_auth_mode = "none"

action selectSimAuthMode(mode_name):
    sim_auth_mode = mode_name
    local sch = auth_schemes.find(a => a.name == mode_name)
    if sch != null:
        local entries = sch.entries ?? []
        if entries.length > 0:
            local first = entries[0]
            if sch.type == "jwt" or sch.type == "basic":
                sim_username = first.k ?? ""
                sim_password = first.v ?? ""
            else if sch.type == "api_key":
                sim_api_key = first.k ?? ""
            else if sch.type == "oauth2" or sch.type == "bearer" or sch.type == "cookie":
                sim_token = first.k ?? ""
        if sch.type == "hmac":
            sim_hmac_valid = true

action setSimUsername(val):
    sim_username = val

action setSimPassword(val):
    sim_password = val

action setSimToken(val):
    sim_token = val

action setSimApiKey(val):
    sim_api_key = val

action toggleSimHmacValid:
    sim_hmac_valid = !sim_hmac_valid

action setSimBody(val):
    sim_body = val

action setSimPathParam(pname, val):
    local next_params = deep_clone(sim_path_params ?? {})
    next_params[pname] = val
    sim_path_params = next_params

action resetSimBuckets:
    local _r = rune.emulate_reset()
    sim_buckets = {}
    sim_request_count = 0
    status_message = "Emulator state & rate-limit buckets reset."

action sendSimRequest:
    if sim_is_sending:
        stop
    sim_is_sending = true
    sim_pending_mode = "single"
    sim_last_reason = "Executing against Rune emulator…"
    start-timer finishSimRequest 200ms

action sendBurstRequests:
    if sim_is_sending:
        stop
    sim_is_sending = true
    sim_pending_mode = "burst"
    sim_last_reason = "Sending 5x burst through Rune emulator…"
    start-timer finishSimRequest 240ms

action triggerQuickScenario(kind):
    if sim_is_sending:
        stop
    sim_is_sending = true
    sim_pending_mode = kind
    sim_last_reason = "Running scenario…"
    start-timer finishSimRequest 200ms

action finishSimRequest:
    stop-timer
    local mode = sim_pending_mode
    sim_is_sending = false
    sim_pending_mode = ""
    match mode:
        "single":
            call runSimRequest
        "burst":
            call burstSimRequests
        "anon", "valid", "forbidden", "burst_demo":
            call simQuickScenario (mode == "burst_demo" ? "burst" : mode)

action burstSimRequests:
    for n in range(5):
        call runSimRequest

action simQuickScenario(kind):
    if api_protocol == "graphql":
        match kind:
            "anon":
                if resolvers.length > 0:
                    call selectSimResolver resolvers[0].id
                sim_auth_mode = "none"
                call runSimRequest
            "valid":
                local picked = false
                for g in resolvers:
                    if !picked and g.kind == "query":
                        call selectSimResolver g.id
                        picked = true
                if !picked and resolvers.length > 0:
                    call selectSimResolver resolvers[0].id
                if default_auth != "" and default_auth != "none":
                    call selectSimAuthMode default_auth
                call resetSimBuckets
                call runSimRequest
            "forbidden":
                local picked = false
                for g in resolvers:
                    if !picked and (g.roles ?? "").trim() != "":
                        call selectSimResolver g.id
                        picked = true
                if !picked:
                    for g in resolvers:
                        if !picked and (g.scopes ?? "").trim() != "":
                            call selectSimResolver g.id
                            picked = true
                if default_auth != "" and default_auth != "none":
                    call selectSimAuthMode default_auth
                else if auth_schemes.length > 0:
                    call selectSimAuthMode auth_schemes[0].name
                local sch = auth_schemes.find(a => a.name == sim_auth_mode)
                if sch != null and (sch.entries ?? []).length > 1:
                    local low = sch.entries[1]
                    if sch.type == "jwt" or sch.type == "basic":
                        sim_username = low.k ?? ""
                        sim_password = low.v ?? ""
                    else if sch.type == "api_key":
                        sim_api_key = low.k ?? ""
                    else:
                        sim_token = low.k ?? ""
                call runSimRequest
            "burst":
                if resolvers.length > 0:
                    call selectSimResolver resolvers[0].id
                if default_auth != "" and default_auth != "none":
                    call selectSimAuthMode default_auth
                call resetSimBuckets
                call burstSimRequests
        stop

    match kind:
        "anon":
            local found = false
            for r in routes:
                local eff = effective_route_auth_names(r, default_auth)
                if !found and eff.length > 0:
                    sim_route_id = r.id
                    found = true
            sim_auth_mode = "none"
            call runSimRequest
        "valid":
            local found = false
            for r in routes:
                local eff = effective_route_auth_names(r, default_auth)
                if !found and eff.length > 0:
                    call selectSimRoute r.id
                    found = true
            call resetSimBuckets
            call runSimRequest
        "forbidden":
            local picked = false
            for r in routes:
                if !picked and (r.roles ?? "").trim() != "":
                    call selectSimRoute r.id
                    picked = true
            if !picked:
                for r in routes:
                    if !picked and (r.scopes ?? "").trim() != "":
                        call selectSimRoute r.id
                        picked = true
            local sch = auth_schemes.find(a => a.name == sim_auth_mode)
            if sch != null and (sch.entries ?? []).length > 1:
                local low = sch.entries[1]
                if sch.type == "jwt" or sch.type == "basic":
                    sim_username = low.k ?? ""
                    sim_password = low.v ?? ""
                else if sch.type == "api_key":
                    sim_api_key = low.k ?? ""
                else:
                    sim_token = low.k ?? ""
            call runSimRequest
        "burst":
            local found = false
            for r in routes:
                if !found and r.rl_mode == "custom":
                    call selectSimRoute r.id
                    found = true
            call resetSimBuckets
            call burstSimRequests

action runSimRequest:
    local sch = auth_schemes.find(a => a.name == sim_auth_mode)
    if api_protocol == "graphql":
        local parsed_vars = json.try_parse(sim_gql_vars)
        if parsed_vars == null:
            parsed_vars = {}
        local payload = {"query": sim_gql_query, "variables": parsed_vars}
        local body_str = json.stringify(payload)
        sim_last_curl = build_gql_curl(sch, sim_username, sim_password, sim_token, sim_api_key, sim_hmac_valid, body_str, app_port)
        sim_request_count += 1

        local req_headers = {"Content-Type": "application/json"}
        local jwt_login = null
        if sim_auth_mode != "none" and sch != null:
            match sch.type:
                "jwt":
                    jwt_login = {"scheme": sch.name, "username": sim_username, "password": sim_password}
                "oauth2", "bearer":
                    req_headers["Authorization"] = "Bearer " + sim_token
                "api_key":
                    local hdr_name = (sch.header ?? "") != "" ? sch.header : "X-API-Key"
                    req_headers[hdr_name] = sim_api_key
                "basic":
                    local raw_basic = sim_username + ":" + sim_password
                    req_headers["Authorization"] = "Basic " + rune.base64(raw_basic)
                "hmac":
                    local sig_hdr = (sch.header ?? "") != "" ? sch.header : "X-Webhook-Signature"
                    local prefix = sch.prefix ?? ""
                    local sig_val = sim_hmac_valid ? rune.hmac_sha256(sch.secret ?? "", body_str, sch.encoding ?? "hex") : "deadbeef_invalid"
                    req_headers[sig_hdr] = prefix + sig_val
                "cookie":
                    local cname = (sch.cookie_name ?? "") != "" ? sch.cookie_name : "vectrune_session"
                    req_headers["Cookie"] = cname + "=" + sim_token

        local emu_req = {"method": "POST", "path": "/graphql", "headers": req_headers, "body": body_str}
        if jwt_login != null:
            emu_req.jwt_login = jwt_login

        local res = rune.emulate(exported_rune, emu_req)
        sim_last_status = res.status ?? 500
        sim_last_headers = res.header_lines ?? []
        sim_last_body = res.body_text ?? ""
        sim_last_auth_json = json.stringify(res.auth ?? {}, null, 2)

        local auth_info = res.auth ?? {}
        local gql_errs = (res.body != null and res.body.errors != null) ? res.body.errors : []
        if sim_last_status == 401:
            sim_last_reason = "401 Unauthorized — rejected by @Authentication middleware"
        else if sim_last_status == 429:
            sim_last_reason = "429 Too Many Requests — rate limit exceeded"
        else if gql_errs.length > 0:
            local first_msg = gql_errs[0].message ?? "GraphQL error"
            sim_last_reason = "GraphQL error — " + first_msg
        else if sim_last_status >= 200 and sim_last_status < 300:
            sim_last_reason = sim_last_status + " OK — GraphQL executed by Rune emulator (" + (auth_info.authenticated == true ? (auth_info.scheme + ": " + auth_info.sub) : "public") + ")"
        else:
            sim_last_reason = "HTTP " + sim_last_status
        status_message = sim_last_reason
        stop

    local route = routes.find(r => r.id == sim_route_id)
    if route == null:
        status_message = "No route selected to simulate."
        stop

    local req_method = route.method == "CRUD" ? "GET" : route.method
    local req_path = resolve_sim_path(route.path, sim_path_params)
    local send_body = (req_method == "POST" or req_method == "PUT" or req_method == "PATCH") ? sim_body : null
    sim_last_curl = build_sim_curl(route, sch, sim_username, sim_password, sim_token, sim_api_key, sim_hmac_valid, sim_body, app_port, sim_path_params)
    sim_request_count += 1

    local req_headers = {}
    local jwt_login = null

    if sim_auth_mode != "none" and sch != null:
        match sch.type:
            "jwt":
                jwt_login = {"scheme": sch.name, "username": sim_username, "password": sim_password}
            "oauth2", "bearer":
                req_headers["Authorization"] = "Bearer " + sim_token
            "api_key":
                local hdr_name = (sch.header ?? "") != "" ? sch.header : "X-API-Key"
                req_headers[hdr_name] = sim_api_key
            "basic":
                local raw_basic = sim_username + ":" + sim_password
                req_headers["Authorization"] = "Basic " + rune.base64(raw_basic)
            "hmac":
                local sig_hdr = (sch.header ?? "") != "" ? sch.header : "X-Webhook-Signature"
                local prefix = sch.prefix ?? ""
                local body_for_sig = send_body ?? ""
                local sig_val = sim_hmac_valid ? rune.hmac_sha256(sch.secret ?? "", body_for_sig, sch.encoding ?? "hex") : "deadbeef_invalid"
                req_headers[sig_hdr] = prefix + sig_val
            "cookie":
                local cname = (sch.cookie_name ?? "") != "" ? sch.cookie_name : "vectrune_session"
                req_headers["Cookie"] = cname + "=" + sim_token

    local emu_req = {"method": req_method, "path": req_path, "headers": req_headers}
    if send_body != null:
        emu_req.body = send_body
    if jwt_login != null:
        emu_req.jwt_login = jwt_login

    local res = rune.emulate(exported_rune, emu_req)
    sim_last_status = res.status ?? 500
    sim_last_headers = res.header_lines ?? []
    sim_last_body = res.body_text ?? ""
    sim_last_auth_json = json.stringify(res.auth ?? {}, null, 2)

    local auth_info = res.auth ?? {}
    if sim_last_status >= 200 and sim_last_status < 300:
        sim_last_reason = sim_last_status + " OK — executed by Rune emulator (" + (auth_info.authenticated == true ? (auth_info.scheme + ": " + auth_info.sub) : "public route") + ")"
    else if sim_last_status == 401:
        sim_last_reason = "401 Unauthorized — rejected by @Authentication middleware"
    else if sim_last_status == 403:
        sim_last_reason = "403 Forbidden — caller \"" + (auth_info.sub ?? "") + "\" lacks required roles or scopes"
    else if sim_last_status == 429:
        sim_last_reason = "429 Too Many Requests — rate limit exceeded"
    else:
        sim_last_reason = "HTTP " + sim_last_status

    status_message = sim_last_reason
parts/logic/state.rune
@Logic/api_studio

state:
    api_protocol = "rest"
    selected_preset = "secure_orders"
    project_id = "secure_orders"
    app_name = "SecureOrdersAPI"
    app_version = "1.0.0"
    app_port = 8080
    swagger_enabled = true
    cors_mode = "origins"
    cors_origins = "https://app.example.com, http://localhost:3000"
    default_auth = "JWTAuth"
    rate_limit_enabled = true
    rate_limit_requests = 60
    rate_limit_window = 60
    rate_limit_key = "ip"

    saved_apis = []
    auth_schemes = []
    schemas = []
    routes = []
    resolvers = []
    memory_collections = []

    active_section = "route"
    selected_auth_id = 1
    selected_schema_id = 1
    selected_route_id = 2
    selected_resolver_id = 0
    next_id = 100
    show_code_panel = true
    show_add_auth_picker = false

    new_auth_type = "jwt"
    new_field_name = ""
    new_field_type = "string"
    new_arg_name = ""
    new_arg_type = "string"
    new_cred_a = ""
    new_cred_b = ""
    new_cred_roles = "user"
    new_cred_scopes = "orders:read"

    sim_route_id = 2
    sim_resolver_id = 0
    sim_gql_query = ""
    sim_gql_vars = "{}"
    sim_auth_mode = "JWTAuth"
    sim_username = "alice"
    sim_password = "alice-pass"
    sim_token = ""
    sim_api_key = ""
    sim_hmac_valid = true
    sim_path_params = {}
    sim_body = "{\"id\":\"ord-42\",\"item\":\"Laser Sword\",\"amount\":199}"
    sim_buckets = {}
    sim_last_status = 0
    sim_last_reason = "Choose a route and click Send Request, or try a 1-click scenario above."
    sim_last_headers = []
    sim_last_body = ""
    sim_last_auth_json = ""
    sim_last_curl = ""
    sim_request_count = 0
    sim_is_sending = false
    sim_pending_mode = ""

    active_output_tab = "rune"
    import_code = ""
    is_fullscreen = false
    status_message = "Ready"

computed:
    is_graphql = api_protocol == "graphql"
    can_undo = history.can_undo
    can_redo = history.can_redo
    has_sidebar = active_section == "route" or active_section == "auth" or active_section == "schema"
    wb_layout_cls = has_sidebar ? (show_code_panel ? "wb-body wb-3col" : "wb-body wb-2col-list") : (show_code_panel ? "wb-body wb-2col-code" : "wb-body wb-1col")
    auth_count = auth_schemes.length
    schema_count = schemas.length
    route_count = routes.length
    resolver_count = resolvers.length
    protected_route_count = count_protected_routes(routes, default_auth)
    public_route_count = routes.length - protected_route_count
    auth_rows = build_auth_rows(auth_schemes, selected_auth_id)
    schema_rows = build_schema_rows(schemas, selected_schema_id)
    route_rows = build_route_rows(routes, selected_route_id, default_auth)
    resolver_rows = build_resolver_rows(resolvers, selected_resolver_id)

    selected_auth = auth_schemes.find(a => a.id == selected_auth_id)
    has_selected_auth = selected_auth != null
    sel_auth_name = selected_auth != null ? selected_auth.name : ""
    sel_auth_type = selected_auth != null ? selected_auth.type : "jwt"
    sel_auth_title = auth_type_title(sel_auth_type)
    sel_auth_desc = auth_type_description(sel_auth_type)
    sel_auth_entries = selected_auth != null ? (selected_auth.entries ?? []) : []

    selected_schema = schemas.find(s => s.id == selected_schema_id)
    has_selected_schema = selected_schema != null
    sel_schema_name = selected_schema != null ? selected_schema.name : ""
    sel_schema_fields = selected_schema != null ? (selected_schema.fields ?? []) : []

    selected_route = routes.find(r => r.id == selected_route_id)
    has_selected_route = selected_route != null
    sel_route_method = selected_route != null ? selected_route.method : "GET"
    sel_route_method_cls = "method-" + sel_route_method.toLowerCase()
    sel_route_path = selected_route != null ? selected_route.path : "/"
    sel_route_auth_mode = selected_route != null ? selected_route.auth_mode : "inherit"
    sel_route_auth_schemes = selected_route != null ? (selected_route.auth_schemes ?? []) : []
    sel_route_scheme_toggles = build_route_scheme_toggles(auth_schemes, sel_route_auth_schemes)
    sel_route_roles = selected_route != null ? (selected_route.roles ?? "") : ""
    sel_route_scopes = selected_route != null ? (selected_route.scopes ?? "") : ""
    sel_route_expect = selected_route != null ? (selected_route.expect ?? "") : ""
    sel_route_rl_mode = selected_route != null ? (selected_route.rl_mode ?? "inherit") : "inherit"
    sel_route_rl_requests = selected_route != null ? (selected_route.rl_requests ?? 20) : 20
    sel_route_rl_window = selected_route != null ? (selected_route.rl_window ?? 60) : 60
    sel_route_rl_key = selected_route != null ? (selected_route.rl_key ?? "ip") : "ip"
    sel_route_steps = selected_route != null ? (selected_route.steps ?? "") : ""
    sel_route_auth_pill = route_auth_summary(selected_route, default_auth)
    sel_route_effective_auth = effective_route_auth_names(selected_route, default_auth)
    sel_route_is_public = sel_route_effective_auth.length == 0
    sel_route_access_pill = route_access_summary(selected_route)
    sel_route_rl_pill = route_rl_summary(selected_route, rate_limit_enabled, rate_limit_requests, rate_limit_window, rate_limit_key)

    selected_resolver = resolvers.find(r => r.id == selected_resolver_id)
    has_selected_resolver = selected_resolver != null
    sel_resolver_kind = selected_resolver != null ? selected_resolver.kind : "query"
    sel_resolver_badge = sel_resolver_kind == "mutation" ? "MUTATION" : "QUERY"
    sel_resolver_cls = sel_resolver_kind == "mutation" ? "method-patch" : "method-get"
    sel_resolver_name = selected_resolver != null ? selected_resolver.name : ""
    sel_resolver_return_type = selected_resolver != null ? (selected_resolver.return_type ?? "JSON") : "JSON"
    sel_resolver_args = selected_resolver != null ? (selected_resolver.args ?? []) : []
    sel_resolver_roles = selected_resolver != null ? (selected_resolver.roles ?? "") : ""
    sel_resolver_scopes = selected_resolver != null ? (selected_resolver.scopes ?? "") : ""
    sel_resolver_steps = selected_resolver != null ? (selected_resolver.steps ?? "") : ""
    sel_resolver_ret = selected_resolver != null ? resolver_sdl_return(selected_resolver) : "JSON"
    sel_resolver_access_pill = ((sel_resolver_roles.trim() != "" or sel_resolver_scopes.trim() != "") ? ("RBAC: " + (sel_resolver_roles.trim() != "" ? sel_resolver_roles.trim() : sel_resolver_scopes.trim())) : "Any authenticated caller")

    sim_route = routes.find(r => r.id == sim_route_id)
    sim_route_method = sim_route != null ? sim_route.method : "GET"
    sim_route_method_cls = "method-" + sim_route_method.toLowerCase()
    sim_route_has_body = sim_route_method == "POST" or sim_route_method == "PUT" or sim_route_method == "PATCH"
    sim_route_param_rows = build_sim_param_rows(sim_route, sim_path_params)
    sim_route_has_params = sim_route_param_rows.length > 0
    sim_route_summary = describe_route_policy(sim_route, default_auth, rate_limit_enabled, rate_limit_requests, rate_limit_window, rate_limit_key)
    sim_resolver = resolvers.find(r => r.id == sim_resolver_id)
    sim_gql_arg_rows = build_sim_gql_arg_rows(sim_resolver, sim_gql_vars)
    sim_gql_has_args = sim_gql_arg_rows.length > 0
    sim_scheme_obj = auth_schemes.find(a => a.name == sim_auth_mode)
    sim_scheme_type = sim_scheme_obj != null ? sim_scheme_obj.type : "none"
    sim_status_class = sim_last_status == 429 ? "warn" : (sim_last_status >= 400 ? "err" : "ok")

    exported_rune = is_graphql ? format_graphql_rune(app_name, app_version, app_port, cors_mode, cors_origins, default_auth, rate_limit_enabled, rate_limit_requests, rate_limit_window, rate_limit_key, auth_schemes, schemas, resolvers, memory_collections) : format_api_rune(app_name, app_version, app_port, swagger_enabled, cors_mode, cors_origins, default_auth, rate_limit_enabled, rate_limit_requests, rate_limit_window, rate_limit_key, auth_schemes, schemas, routes)
    exported_tests = is_graphql ? format_graphql_tests(app_name, default_auth, resolvers) : format_api_tests(app_name, default_auth, routes)
    exported_openapi = format_openapi_json(app_name, app_version, default_auth, rate_limit_enabled, auth_schemes, schemas, routes)
    exported_sdl = format_graphql_sdl(schemas, resolvers)
parts/style/base.rune
@Style/api_studio

tokens:
    bg_canvas = #f6f8fa
    bg_surface = #ffffff
    bg_subtle = #f1f5f9
    bg_hover = #f8fafc
    border_soft = #e2e8f0
    border_strong = #cbd5e1
    ink_primary = #0f172a
    ink_secondary = #475569
    ink_muted = #64748b
    brand = #0f766e
    brand_dark = #115e59
    brand_tint = #f0fdfa
    brand_border = #99f6e4
    code_bg = #0f172a
    code_surface = #1e293b
    code_border = #334155
    code_ink = #e2e8f0
    danger = #dc2626
    danger_tint = #fef2f2

rules:
    *:
        box-sizing = border-box

    html, body:
        margin = 0
        padding = 0
        height = 100%
        background = {bg_canvas}
        color = {ink_primary}
        font-family = -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, sans-serif
        -webkit-font-smoothing = antialiased

    .wb-shell:
        min-height = 100vh
        display = flex
        flex-direction = column
        background = {bg_canvas}
        color = {ink_primary}

    .wb-topbar:
        display = flex
        justify-content = space-between
        align-items = center
        flex-wrap = wrap
        gap = 0.5rem 0.75rem
        padding = 0.52rem 0.85rem
        background = {bg_surface}
        border-bottom = 1px solid {border_soft}

    .wb-brand-group:
        display = flex
        align-items = center
        flex-wrap = wrap
        gap = 0.45rem

    .wb-logo-mark:
        width = 30px
        height = 30px
        border-radius = 8px
        background = {brand}
        color = #ffffff
        font-size = 0.68rem
        font-weight = 800
        letter-spacing = 0.4px
        display = flex
        align-items = center
        justify-content = center
        flex-shrink = 0

    .wb-title-row:
        display = flex
        align-items = center
        gap = 0.4rem

    .wb-title:
        margin = 0
        font-size = 0.96rem
        font-weight = 700
        color = {ink_primary}
        letter-spacing = -0.01em

    .wb-proto-switch:
        display = inline-flex
        align-items = center
        background = {bg_subtle}
        border = 1px solid {border_soft}
        border-radius = 999px
        padding = 2px
        gap = 2px

    .wb-proto-btn:
        border = none
        background = transparent
        color = {ink_muted}
        font-size = 0.68rem
        font-weight = 700
        padding = 0.16rem 0.52rem
        border-radius = 999px
        cursor = pointer
        transition = background 120ms ease, color 120ms ease

    .wb-proto-btn.active:
        background = {brand}
        color = #ffffff

    .wb-add-group:
        display = flex
        align-items = center
        gap = 0.25rem
        flex-shrink = 0

    .wb-divider:
        width = 1px
        height = 22px
        background = {border_soft}

    .wb-app-field, .wb-example-picker:
        display = inline-flex
        align-items = center
        gap = 0.35rem
        background = {bg_canvas}
        border = 1px solid {border_soft}
        border-radius = 8px
        padding = 0.2rem 0.45rem

    .wb-app-prefix:
        font-size = 0.72rem
        font-weight = 700
        color = {brand}
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace

    .wb-app-input:
        border = none
        background = transparent
        color = {ink_primary}
        font-size = 0.8rem
        font-weight = 600
        width = 128px
        padding = 0.14rem 0.15rem
        font-family = inherit

    .wb-app-input:focus:
        outline = none

    .wb-preset-select:
        padding = 0.14rem 0.2rem
        border = none
        background = transparent
        color = {ink_primary}
        font-size = 0.76rem
        font-weight = 600
        font-family = inherit
        max-width = 200px
        cursor = pointer

    .wb-preset-select:focus:
        outline = none

    .wb-top-actions:
        display = flex
        align-items = center
        gap = 0.4rem
        flex-wrap = wrap

    button:
        font-family = inherit

    .wb-btn-primary, .wb-btn-subtle, .wb-btn-icon, .wb-btn-danger, .wb-btn-ghost-danger, .wb-btn-add, .wb-btn-try, .wb-btn-chip, .wb-btn-code:
        border-radius = 8px
        font-weight = 600
        cursor = pointer
        transition = all 0.14s ease
        display = inline-flex
        align-items = center
        justify-content = center
        gap = 0.35rem
        white-space = nowrap

    .wb-btn-primary:
        padding = 0.42rem 0.85rem
        font-size = 0.78rem
        background = {brand}
        border = 1px solid {brand}
        color = #ffffff

    .wb-btn-primary:hover:
        background = {brand_dark}
        border-color = {brand_dark}

    .wb-btn-try:
        padding = 0.42rem 0.85rem
        font-size = 0.78rem
        background = #ecfdf5
        border = 1px solid #6ee7b7
        color = #047857

    .wb-btn-try:hover:
        background = #059669
        border-color = #059669
        color = #ffffff

    .wb-btn-subtle:
        padding = 0.4rem 0.75rem
        font-size = 0.77rem
        background = {bg_surface}
        border = 1px solid {border_strong}
        color = {ink_primary}

    .wb-btn-subtle:hover:
        background = {bg_subtle}
        border-color = #94a3b8

    .wb-btn-subtle.active:
        background = {brand_tint}
        border-color = {brand_border}
        color = {brand}

    .wb-btn-icon:
        padding = 0.38rem 0.62rem
        font-size = 0.76rem
        background = transparent
        border = 1px solid {border_soft}
        color = {ink_secondary}

    .wb-btn-icon:hover:not(:disabled):
        background = {bg_subtle}
        color = {ink_primary}

    .wb-btn-icon:disabled:
        opacity = 0.4
        cursor = default

    .wb-btn-add:
        padding = 0.32rem 0.65rem
        font-size = 0.74rem
        background = {brand_tint}
        border = 1px solid {brand_border}
        color = {brand}

    .wb-btn-add:hover:
        background = {brand}
        border-color = {brand}
        color = #ffffff

    .wb-btn-danger:
        padding = 0.38rem 0.72rem
        font-size = 0.76rem
        background = {danger_tint}
        border = 1px solid #fecaca
        color = {danger}

    .wb-btn-danger:hover:
        background = {danger}
        border-color = {danger}
        color = #ffffff

    .wb-btn-ghost-danger:
        padding = 0.24rem 0.52rem
        font-size = 0.72rem
        background = transparent
        border = 1px solid transparent
        color = {ink_muted}

    .wb-btn-ghost-danger:hover:
        background = {danger_tint}
        border-color = #fecaca
        color = {danger}

    .wb-btn-chip:
        padding = 0.24rem 0.56rem
        font-size = 0.72rem
        background = {bg_subtle}
        border = 1px solid {border_soft}
        color = {ink_secondary}

    .wb-btn-chip:hover:
        border-color = {brand}
        color = {brand}

    .wb-stepbar:
        display = flex
        justify-content = space-between
        align-items = center
        flex-wrap = wrap
        gap = 0.5rem 1rem
        padding = 0.45rem 1rem
        background = {bg_surface}
        border-bottom = 1px solid {border_soft}

    .wb-tabs:
        display = flex
        align-items = center
        gap = 0.3rem
        flex-wrap = wrap

    .wb-tab:
        display = inline-flex
        align-items = center
        gap = 0.45rem
        padding = 0.42rem 0.78rem
        border-radius = 8px
        border = 1px solid transparent
        background = transparent
        color = {ink_secondary}
        font-size = 0.8rem
        font-weight = 600
        cursor = pointer
        transition = all 0.14s ease

    .wb-tab:hover:
        background = {bg_subtle}
        color = {ink_primary}

    .wb-tab.active:
        background = {brand_tint}
        border-color = {brand_border}
        color = {brand_dark}

    .wb-tab-num:
        width = 18px
        height = 18px
        border-radius = 999px
        background = {bg_subtle}
        color = {ink_muted}
        font-size = 0.68rem
        font-weight = 700
        display = inline-flex
        align-items = center
        justify-content = center

    .wb-tab.active .wb-tab-num:
        background = {brand}
        color = #ffffff

    .wb-tab-count:
        font-size = 0.7rem
        font-weight = 700
        padding = 0.08rem 0.42rem
        border-radius = 999px
        background = {bg_subtle}
        color = {ink_muted}

    .wb-tab.active .wb-tab-count:
        background = #ccfbf1
        color = {brand_dark}

    .wb-tab-try:
        margin-left = 0.25rem
        border-color = #d1fae5
        background = #f0fdf4
        color = #047857

    .wb-tab-try:hover:
        background = #dcfce7

    .wb-tab-try.active:
        background = #059669
        border-color = #059669
        color = #ffffff

    .wb-try-dot:
        width = 7px
        height = 7px
        border-radius = 999px
        background = #10b981

    .wb-tab-try.active .wb-try-dot:
        background = #ffffff

    .wb-status-bar:
        display = flex
        align-items = center
        gap = 0.65rem
        font-size = 0.75rem
        color = {ink_muted}

    .wb-posture-summary:
        font-weight = 700
        color = {brand}
        background = {brand_tint}
        border = 1px solid {brand_border}
        padding = 0.16rem 0.55rem
        border-radius = 999px
        font-size = 0.71rem

    .wb-status-msg:
        max-width = 360px
        overflow = hidden
        text-overflow = ellipsis
        white-space = nowrap
parts/style/workspace.rune
@Style/api_studio

rules:
    .wb-body:
        flex = 1
        display = grid
        min-height = 0
        width = 100%

    .wb-3col:
        grid-template-columns = 236px minmax(0, 1fr) 360px

    .wb-2col-list:
        grid-template-columns = 248px minmax(0, 1fr)

    .wb-2col-code:
        grid-template-columns = minmax(0, 1fr) 360px

    .wb-1col:
        grid-template-columns = minmax(0, 1fr)

    .wb-list-pane:
        background = {bg_surface}
        border-right = 1px solid {border_soft}
        padding = 0.85rem 0.75rem
        display = flex
        flex-direction = column
        gap = 0.75rem

    .wb-list-head:
        display = flex
        justify-content = space-between
        align-items = flex-start
        gap = 0.5rem
        padding = 0 0.15rem

    .wb-list-title:
        margin = 0
        font-size = 0.85rem
        font-weight = 700
        color = {ink_primary}

    .wb-list-sub:
        margin = 0.18rem 0 0
        font-size = 0.73rem
        color = {ink_muted}
        line-height = 1.35

    .wb-list-items:
        display = grid
        gap = 0.4rem
        align-content = start

    .wb-item-card:
        width = 100%
        text-align = left
        padding = 0.6rem 0.68rem
        border-radius = 10px
        border = 1px solid {border_soft}
        background = {bg_surface}
        cursor = pointer
        display = grid
        gap = 0.35rem
        transition = all 0.13s ease

    .wb-item-card:hover:
        border-color = {border_strong}
        background = {bg_hover}

    .wb-item-card.selected:
        background = {brand_tint}
        border-color = {brand}
        box-shadow = 0 1px 3px rgba(15, 118, 110, 0.12)

    .wb-item-top:
        display = flex
        align-items = center
        gap = 0.45rem
        min-width = 0

    .wb-item-path, .wb-item-name:
        font-size = 0.8rem
        font-weight = 600
        color = {ink_primary}
        overflow = hidden
        text-overflow = ellipsis
        white-space = nowrap
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace

    .wb-item-foot:
        display = flex
        align-items = center
        justify-content = space-between
        gap = 0.4rem

    .wb-item-meta:
        font-size = 0.72rem
        color = {ink_muted}

    .wb-method:
        font-size = 0.65rem
        font-weight = 800
        letter-spacing = 0.03em
        padding = 0.15rem 0.42rem
        border-radius = 5px
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace
        border = 1px solid transparent
        flex-shrink = 0

    .wb-method-lg:
        font-size = 0.74rem
        padding = 0.24rem 0.58rem
        border-radius = 7px

    .method-get:
        background = #ecfdf5
        color = #047857
        border-color = #a7f3d0

    .method-post:
        background = #eff6ff
        color = #1d4ed8
        border-color = #bfdbfe

    .method-put:
        background = #fffbeb
        color = #b45309
        border-color = #fde68a

    .method-patch:
        background = #f5f3ff
        color = #6d28d9
        border-color = #ddd6fe

    .method-delete:
        background = #fef2f2
        color = #b91c1c
        border-color = #fecaca

    .method-crud:
        background = #f0fdfa
        color = #0f766e
        border-color = #99f6e4

    .wb-lock-pill:
        font-size = 0.67rem
        font-weight = 600
        padding = 0.1rem 0.42rem
        border-radius = 999px
        background = #f1f5f9
        color = #334155
        max-width = 100%
        overflow = hidden
        text-overflow = ellipsis
        white-space = nowrap

    .wb-lock-pill.public:
        background = #fffbeb
        color = #b45309

    .wb-scheme-badge:
        font-size = 0.65rem
        font-weight = 700
        padding = 0.14rem 0.44rem
        border-radius = 6px
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace
        flex-shrink = 0

    .scheme-jwt:
        background = #eef2ff
        color = #4338ca

    .scheme-oauth2:
        background = #eff6ff
        color = #1d4ed8

    .scheme-api_key:
        background = #fffbeb
        color = #b45309

    .scheme-basic:
        background = #f1f5f9
        color = #334155

    .scheme-bearer:
        background = #f0fdfa
        color = #0f766e

    .scheme-hmac:
        background = #f5f3ff
        color = #6d28d9

    .scheme-cookie:
        background = #fdf2f8
        color = #be185d

    .wb-stage:
        padding = 1.1rem 1.25rem 1.5rem
        overflow-y = auto
        min-width = 0

    .wb-view:
        display = grid
        gap = 0.9rem
        max-width = 920px
        margin = 0 auto

    .wb-view-wide:
        max-width = 1120px

    .wb-view-head:
        display = flex
        justify-content = space-between
        align-items = flex-start
        flex-wrap = wrap
        gap = 0.75rem

    .wb-route-headline:
        display = flex
        align-items = center
        gap = 0.6rem
        flex-wrap = wrap

    .wb-head-actions:
        display = flex
        align-items = center
        gap = 0.45rem

    .wb-eyebrow:
        display = inline-block
        font-size = 0.67rem
        font-weight = 700
        letter-spacing = 0.08em
        color = {brand}
        margin-bottom = 0.2rem

    .wb-view-title:
        margin = 0
        font-size = 1.2rem
        font-weight = 700
        color = {ink_primary}
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace

    .wb-view-desc:
        margin = 0.28rem 0 0
        font-size = 0.82rem
        color = {ink_secondary}
        line-height = 1.45

    .wb-pipeline:
        display = flex
        align-items = center
        flex-wrap = wrap
        gap = 0.45rem
        padding = 0.65rem 0.85rem
        background = {bg_surface}
        border = 1px solid {border_soft}
        border-radius = 12px

    .wb-pipe-step:
        display = grid
        gap = 0.1rem
        padding = 0.28rem 0.55rem
        border-radius = 8px
        background = {bg_canvas}
        border = 1px solid {border_soft}

    .wb-pipe-label:
        font-size = 0.64rem
        font-weight = 700
        text-transform = uppercase
        letter-spacing = 0.05em
        color = {ink_muted}

    .wb-pipe-val:
        font-size = 0.76rem
        font-weight = 600
        color = {ink_primary}

    .wb-pipe-val.is-public:
        color = #b45309

    .wb-pipe-arrow:
        color = #94a3b8
        font-weight = 700
        font-size = 0.85rem

    .wb-section-card:
        background = {bg_surface}
        border = 1px solid {border_soft}
        border-radius = 12px
        padding = 0.95rem 1.05rem
        display = grid
        gap = 0.75rem
        box-shadow = 0 1px 2px rgba(15, 23, 42, 0.03)

    .wb-card-header:
        display = flex
        justify-content = space-between
        align-items = flex-start
        flex-wrap = wrap
        gap = 0.5rem

    .wb-card-title:
        margin = 0
        font-size = 0.88rem
        font-weight = 700
        color = {ink_primary}

    .wb-card-hint, .wb-helper:
        margin = 0.18rem 0 0
        font-size = 0.76rem
        color = {ink_muted}
        line-height = 1.4

    .wb-form-grid, .wb-two-col, .wb-sim-split:
        display = grid
        grid-template-columns = repeat(2, minmax(0, 1fr))
        gap = 0.75rem
        align-items = start

    .wb-form-grid-3:
        display = grid
        grid-template-columns = repeat(3, minmax(0, 1fr))
        gap = 0.75rem

    .wb-field:
        display = grid
        gap = 0.3rem

    .wb-label:
        font-size = 0.74rem
        font-weight = 600
        color = {ink_secondary}

    .wb-input, .wb-select, .wb-select-sm, .wb-code-area:
        width = 100%
        padding = 0.46rem 0.65rem
        border-radius = 8px
        border = 1px solid {border_strong}
        background = {bg_surface}
        color = {ink_primary}
        font-size = 0.82rem
        font-family = inherit
        transition = border-color 0.14s ease

    .wb-input:focus, .wb-select:focus, .wb-select-sm:focus, .wb-code-area:focus:
        outline = none
        border-color = {brand}
        box-shadow = 0 0 0 3px rgba(15, 118, 110, 0.12)

    .wb-mono:
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace
        font-size = 0.8rem

    .wb-code-area:
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace
        font-size = 0.79rem
        line-height = 1.5
        background = #f8fafc
        resize = vertical

    .wb-segmented:
        display = inline-flex
        flex-wrap = wrap
        gap = 0.25rem
        padding = 0.24rem
        background = {bg_subtle}
        border-radius = 10px
        width = fit-content

    .wb-seg-btn:
        padding = 0.36rem 0.72rem
        border-radius = 7px
        border = none
        background = transparent
        color = {ink_secondary}
        font-size = 0.77rem
        font-weight = 600
        cursor = pointer

    .wb-seg-btn.active:
        background = {bg_surface}
        color = {ink_primary}
        box-shadow = 0 1px 2px rgba(15, 23, 42, 0.08)

    .wb-chip-picker:
        display = flex
        flex-wrap = wrap
        gap = 0.45rem

    .wb-check-chip:
        display = inline-flex
        align-items = center
        gap = 0.4rem
        padding = 0.38rem 0.7rem
        border-radius = 999px
        border = 1px solid {border_strong}
        background = {bg_surface}
        color = {ink_secondary}
        font-size = 0.77rem
        font-weight = 600
        cursor = pointer

    .wb-check-chip.active:
        background = {brand_tint}
        border-color = {brand}
        color = {brand_dark}

    .wb-chip-dot:
        width = 8px
        height = 8px
        border-radius = 999px
        background = {border_strong}

    .wb-check-chip.active .wb-chip-dot:
        background = {brand}

    .wb-chip-type:
        font-size = 0.66rem
        color = {ink_muted}
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace

    .wb-snippet-bar:
        display = flex
        gap = 0.35rem
        flex-wrap = wrap

    .wb-toggle-row:
        display = inline-flex
        align-items = center
        gap = 0.5rem
        font-size = 0.8rem
        color = {ink_primary}
        cursor = pointer

    .wb-picker-panel:
        background = {bg_surface}
        border = 1px solid {brand_border}
        border-radius = 12px
        padding = 1rem
        display = grid
        gap = 0.75rem
        box-shadow = 0 4px 14px rgba(15, 118, 110, 0.08)

    .wb-picker-grid:
        display = grid
        grid-template-columns = repeat(auto-fill, minmax(210px, 1fr))
        gap = 0.55rem

    .wb-picker-card:
        text-align = left
        padding = 0.72rem 0.8rem
        border-radius = 10px
        border = 1px solid {border_soft}
        background = {bg_canvas}
        cursor = pointer
        display = grid
        gap = 0.28rem
        align-content = start
        color = {ink_primary}
        font-size = 0.8rem

    .wb-picker-card:hover:
        border-color = {brand}
        background = {brand_tint}

    .wb-picker-desc:
        font-size = 0.73rem
        color = {ink_secondary}
        line-height = 1.38

    .wb-table-list:
        display = grid
        gap = 0.4rem

    .wb-table-row, .wb-cred-item:
        display = flex
        align-items = center
        justify-content = space-between
        flex-wrap = wrap
        gap = 0.5rem
        padding = 0.5rem 0.7rem
        border-radius = 8px
        background = {bg_canvas}
        border = 1px solid {border_soft}

    .wb-cred-primary:
        display = flex
        align-items = center
        gap = 0.45rem

    .wb-mono-bold:
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace
        font-size = 0.8rem
        font-weight = 700
        color = {ink_primary}

    .wb-cred-arrow:
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace
        font-size = 0.77rem
        color = {ink_muted}

    .wb-cred-badges:
        display = flex
        gap = 0.35rem
        flex-wrap = wrap

    .wb-role-badge, .wb-scope-badge, .wb-type-pill:
        font-size = 0.69rem
        font-weight = 600
        padding = 0.14rem 0.48rem
        border-radius = 999px
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace

    .wb-role-badge:
        background = #f5f3ff
        color = #6d28d9

    .wb-scope-badge:
        background = #ecfdf5
        color = #047857

    .wb-type-pill:
        background = #e2e8f0
        color = #334155

    .wb-cred-form:
        display = grid
        grid-template-columns = 1fr 1fr 1fr 1fr auto
        gap = 0.45rem
        align-items = center

    .wb-inline-form:
        display = grid
        grid-template-columns = 1fr 120px auto
        gap = 0.45rem
        align-items = center

    .wb-callout:
        display = flex
        align-items = center
        flex-wrap = wrap
        gap = 0.6rem
        padding = 0.75rem 0.95rem
        border-radius = 10px
        background = {brand_tint}
        border = 1px solid {brand_border}

    .wb-callout-tag:
        font-size = 0.66rem
        font-weight = 800
        letter-spacing = 0.07em
        color = {brand_dark}

    .wb-callout-text:
        margin = 0
        font-size = 0.8rem
        color = {ink_primary}

    .wb-empty-state:
        text-align = center
        padding = 2.5rem 1.5rem
        background = {bg_surface}
        border = 1px dashed {border_strong}
        border-radius = 12px
        display = grid
        justify-items = center
        gap = 0.5rem

    .wb-empty-state h2:
        margin = 0
        font-size = 1rem

    .wb-empty-state p:
        margin = 0
        font-size = 0.82rem
        color = {ink_muted}
        max-width = 420px

    .wb-sim-scenarios:
        display = flex
        align-items = center
        flex-wrap = wrap
        gap = 0.45rem

    .wb-scenario-label:
        font-size = 0.75rem
        font-weight = 700
        color = {ink_secondary}

    .wb-scenario-pill:
        padding = 0.34rem 0.72rem
        border-radius = 999px
        border = 1px solid {border_strong}
        background = {bg_surface}
        color = {ink_primary}
        font-size = 0.75rem
        font-weight = 600
        cursor = pointer

    .wb-scenario-pill:hover:
        border-color = {brand}
        background = {brand_tint}
        color = {brand_dark}

    .wb-request-bar:
        display = flex
        align-items = center
        flex-wrap = wrap
        gap = 0.5rem
        padding = 0.6rem 0.75rem
        background = {bg_surface}
        border = 1px solid {border_strong}
        border-radius = 12px
        box-shadow = 0 1px 3px rgba(15, 23, 42, 0.04)

    .wb-url-select, .wb-auth-select:
        flex = 1 1 200px
        padding = 0.45rem 0.65rem
        border-radius = 8px
        border = 1px solid {border_soft}
        background = {bg_canvas}
        color = {ink_primary}
        font-size = 0.81rem
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace

    .wb-policy-banner:
        margin = 0
        padding = 0.5rem 0.75rem
        border-radius = 8px
        background = {bg_subtle}
        color = {ink_secondary}
        font-size = 0.77rem

    .wb-resp-head:
        display = flex
        justify-content = space-between
        align-items = center
        gap = 0.5rem

    .wb-resp-card:
        transition = opacity 0.16s ease, border-color 0.16s ease

    .wb-resp-card.is-sending:
        border-color = {brand}
        opacity = 0.88

    .badge-sending:
        background = {brand_tint}
        border = 1px solid {brand_border}
        color = {brand_dark}

    .wb-http-badge:
        display = none
        font-size = 0.74rem
        font-weight = 700
        padding = 0.2rem 0.6rem
        border-radius = 999px
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace

    .wb-http-badge.visible:
        display = inline-block

    .badge-ok:
        background = #ecfdf5
        border = 1px solid #6ee7b7
        color = #047857

    .badge-warn:
        background = #fffbeb
        border = 1px solid #fcd34d
        color = #b45309

    .badge-err:
        background = #fef2f2
        border = 1px solid #fca5a5
        color = #b91c1c

    .wb-resp-reason:
        margin = 0
        font-size = 0.8rem
        color = {ink_secondary}

    .wb-hdr-box, .wb-sub-code:
        display = grid
        gap = 0.3rem

    .wb-sub-code-label:
        font-size = 0.68rem
        font-weight = 700
        text-transform = uppercase
        letter-spacing = 0.06em
        color = {ink_muted}

    .wb-hdr-item:
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace
        font-size = 0.74rem
        padding = 0.24rem 0.5rem
        border-radius = 6px
        background = #f8fafc
        border = 1px solid {border_soft}
        color = #0f766e

    .wb-dark-pre:
        margin = 0
        padding = 0.7rem 0.85rem
        border-radius = 8px
        background = {code_bg}
        color = {code_ink}
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace
        font-size = 0.74rem
        line-height = 1.48
        white-space = pre-wrap
        word-break = break-word
        max-height = 240px
        overflow = auto

    .wb-code-drawer:
        background = {code_bg}
        color = {code_ink}
        border-left = 1px solid {code_border}
        display = flex
        flex-direction = column
        min-height = 0

    .wb-drawer-tabs:
        display = flex
        gap = 0.2rem
        padding = 0.5rem 0.65rem 0
        background = #0b1120
        border-bottom = 1px solid {code_border}

    .wb-drawer-tab:
        padding = 0.44rem 0.72rem
        font-size = 0.74rem
        font-weight = 600
        background = transparent
        border = none
        border-bottom = 2px solid transparent
        color = #94a3b8
        cursor = pointer

    .wb-drawer-tab.active:
        color = #5eead4
        border-bottom-color = #2dd4bf

    .wb-drawer-toolbar:
        display = flex
        justify-content = space-between
        align-items = center
        gap = 0.5rem
        padding = 0.5rem 0.75rem
        background = {code_surface}
        border-bottom = 1px solid {code_border}

    .wb-drawer-hint:
        margin = 0
        font-size = 0.72rem
        color = #94a3b8

    .wb-drawer-actions:
        display = flex
        gap = 0.35rem

    .wb-btn-code:
        padding = 0.26rem 0.6rem
        font-size = 0.72rem
        background = transparent
        border = 1px solid {code_border}
        color = #cbd5e1

    .wb-btn-code:hover:
        border-color = #5eead4
        color = #5eead4

    .wb-btn-code.accent:
        background = #115e59
        border-color = #14b8a6
        color = #f0fdfa

    .wb-drawer-pre:
        flex = 1
        margin = 0
        padding = 0.85rem 0.9rem
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace
        font-size = 0.74rem
        line-height = 1.52
        color = #e2e8f0
        overflow = auto
        white-space = pre
        max-height = calc(100vh - 175px)

    .wb-import-drawer:
        padding = 0.85rem
        display = grid
        gap = 0.65rem

    .wb-import-area:
        width = 100%
        padding = 0.65rem
        border-radius = 8px
        background = #0b1120
        border = 1px solid {code_border}
        color = #e2e8f0
        font-family = ui-monospace, SFMono-Regular, Menlo, monospace
        font-size = 0.75rem
        line-height = 1.45
        resize = vertical

responsive:
    (max-width: 1020px):
        .wb-3col:
            grid-template-columns = 220px minmax(0, 1fr)

        .wb-2col-code:
            grid-template-columns = minmax(0, 1fr)

        .wb-code-drawer:
            grid-column = 1 / -1
            border-left = none
            border-top = 1px solid {code_border}

        .wb-drawer-pre:
            max-height = 320px

    (max-width: 760px):
        .wb-status-bar:
            max-width = 100%

        .wb-status-msg:
            min-width = 0

        .wb-posture-summary:
            flex-shrink = 0

        .wb-field, .wb-code-drawer, .wb-url-select, .wb-auth-select:
            min-width = 0

        .wb-view-title, .wb-hdr-item, .wb-policy-banner:
            overflow-wrap = anywhere

        .wb-3col:
            grid-template-columns = minmax(0, 1fr)

        .wb-2col-list:
            grid-template-columns = minmax(0, 1fr)

        .wb-list-pane:
            border-right = none
            border-bottom = 1px solid {border_soft}

        .wb-form-grid:
            grid-template-columns = minmax(0, 1fr)

        .wb-form-grid-3:
            grid-template-columns = minmax(0, 1fr)

        .wb-two-col:
            grid-template-columns = minmax(0, 1fr)

        .wb-sim-split:
            grid-template-columns = minmax(0, 1fr)

        .wb-cred-form:
            grid-template-columns = minmax(0, 1fr)

        .wb-inline-form:
            grid-template-columns = minmax(0, 1fr)

Elige un preajuste, explora los 7 esquemas de autenticación (JWT, OAuth2, API Key, Basic, Bearer, HMAC, Cookie) y abre Auth & Rate Simulator para probar respuestas 401, 403, 200 y 429.

Cómo funciona este ejemplo

7 esquemas nativos de @Authentication

Configura JWT (HS/RS/ES/JWKS), OAuth 2.0 (introspección/OIDC), API Keys (cabecera o query), HTTP Basic (texto plano o sha256:), Bearer opaco, webhooks HMAC-SHA256 y cookies de sesión firmadas.

Multi-esquema OR, RBAC, Scopes y Rate Limit

Define @App default_auth, sobrescribe rutas con auth = none o [EsquemaA, EsquemaB], exige roles/scopes (403 Forbidden) y configura rate_limit global o por ruta (429 + Retry-After).

Simulador interactivo de Auth y Rate Limit

Simula peticiones con credenciales de ejemplo, inspecciona el contexto auth.* y la plantilla curl, y ejecuta la prueba de ráfaga de Secure Orders para ver una respuesta 429.

.rune compilable, suite @Test y OpenAPI 3.0

Exporta código .rune listo para vectrune check y vectrune run, bloques @Test generados automáticamente y OpenAPI 3.0 JSON con components.securitySchemes, o importa un .rune existente.

Cómo usar

Configura @App (puerto, CORS, default_auth, rate_limit global), crea esquemas @Authentication y modelos @Schema, y conecta rutas @Route (GET, POST, PUT, PATCH, DELETE, CRUD) con roles y scopes.

Abre Auth & Rate Simulator para verificar 401 Unauthorized, 403 Forbidden, 200 OK y 429 Too Many Requests antes de exportar tu API .rune y el archivo OpenAPI 3.0.

Ejecutar localmente

Para ejecutar el ejemplo completo, instala Vectrune y Git. Clona el repositorio una vez y conserva la carpeta parts junto al archivo principal.

Inicio rápido
git clone https://github.com/davethomas11/vectrune.git
cd vectrune

Ejecuta estos comandos desde la raíz del repositorio. Si ya tienes una copia, abre una terminal en su raíz y omite la clonación.

vectrune examples/rune-web/api_studio/api_studio.rune
vectrune examples/rune-web/api_studio/api_studio.rune -o html > api_studio.html
Sitio creado íntegramente con Rune-Web