Orchardcore scripting

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore scripting is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for using Orchard Core scripting and creating custom IGlobalMethodProvider implementations. Covers JavaScript evaluation with Jint, IScriptingManager and IScriptingEngine, disposing scripting scopes, built-in global methods, custom scripting providers that stay correct under lazy globals and e

How to use this skill

Skill file

Orchard Core Scripting - Prompt Templates

Use the Orchard Core Scripting Engine

You are an Orchard Core expert. Generate code and configuration for scripting, JavaScript evaluation, global methods, custom scripting providers, JavaScript engine limits, and recipe scripting expressions.

Guidelines

Enabling Scripting Features

{
  "steps": [
    {
      "name": "Feature",
      "enable": [
        "OrchardCore.Scripting",
        "OrchardCore.Scripting.JavaScript"
      ],
      "disable": []
    }
  ]
}

Evaluating JavaScript from Code

Prefer IScriptingManager, which handles the scope lifetime and accepts a cancellation token that actually stops the script:

using OrchardCore.Scripting;

namespace MyModule.Services;

public sealed class ScriptEvaluationService
{
    private readonly IScriptingManager _scriptingManager;

    public ScriptEvaluationService(IScriptingManager scriptingManager)
    {
        _scriptingManager = scriptingManager;
    }

    public Task<object> EvaluateAsync(string script, CancellationToken cancellationToken)
        // The directive carries the engine prefix.
        => _scriptingManager.EvaluateAsync($"js: {script}", null, null, [], cancellationToken);
}

When you need to evaluate several scripts against the same scope, talk to the engine directly and dispose the scope when you are done:

using OrchardCore.Scripting;

namespace MyModule.Services;

public sealed class BatchScriptEvaluator
{
    private readonly IScriptingManager _scriptingManager;
    private readonly IServiceProvider _serviceProvider;

    public BatchScriptEvaluator(IScriptingManager scriptingManager, IServiceProvider serviceProvider)
    {
        _scriptingManager = scriptingManager;
        _serviceProvider = serviceProvider;
    }

    public IReadOnlyList<object> Evaluate(IEnumerable<string> scripts)
    {
        var engine = _scriptingManager.GetScriptingEngine("js");

        var globalMethods = _scriptingManager
            .GlobalMethodProviders
            .SelectMany(x => x.GetMethods());

        var scope = engine.CreateScope(globalMethods, _serviceProvider, null, null);

        try
        {
            // No "js:" prefix here: the engine is already the JavaScript one.
            return scripts.Select(script => engine.Evaluate(scope, script)).ToList();
        }
        finally
        {
            // IScriptingScope is a marker interface; JavaScriptScope implements IDisposable.
            // Disposing resets the engine and returns it to the pool. Do it in a finally,
            // because a script that throws still leaves its declarations behind.
            (scope as IDisposable)?.Dispose();
        }
    }
}

Configuring the JavaScript Engine Safely

The engine is configured with Jint's own options type, registered as IOptions<Jint.Options>. One Jint.Options instance is shared by every engine of the tenant (recipes, workflow scripts, layer rules), so configure only tenant-wide policy.

using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Modules;
using OrchardCore.Scripting.JavaScript;

namespace MyModule;

public sealed class Startup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.Configure<Jint.Options>(options =>
        {
            // Each helper registers a constraint *factory*: every engine gets its own counter/deadline.
            options.MaxStatements(10_000);
            options.TimeoutInterval(TimeSpan.FromSeconds(5));
            options.LimitMemory(4_000_000);
            options.LimitRecursion(256);

            // Custom constraint: register a factory, never a shared instance.
            options.Constraint(() => new MaxLoopChecksConstraint(1_000_000));
        });

        // Optional: size the per-tenant engine pool (default 8, 0 disables reuse).
        services.Configure<JavaScriptEngineOptions>(options => options.EnginePoolSize = 16);
    }
}
using Jint;

namespace MyModule;

// Per-execution state lives in the instance, so each engine must get its own instance.
public sealed class MaxLoopChecksConstraint : Constraint
{
    private readonly long _maxChecks;
    private long _checks;

    public MaxLoopChecksConstraint(long maxChecks)
    {
        _maxChecks = maxChecks;
    }

    public override void Check()
    {
        if (++_checks > _maxChecks)
        {
            throw new TimeoutException("The script exceeded its check budget.");
        }
    }

    // Jint calls Reset() at the start of every evaluation, on a reused engine too.
    public override void Reset() => _checks = 0;
}

Rules for Jint.Options:

services.Configure<Jint.Options>(options =>
{
    options.Constraints.StackOverflowGuard = false;
});

Cancellation Stops the Script

AddJavaScriptEngine() registers a Jint.Constraints.OperationDeadlineConstraint factory, and JavaScriptEngine.EvaluateAsync() arms it with the call's CancellationToken.

Engines Are Reused Between Evaluations

Each tenant keeps a small pool of idle Jint engines. Disposing a scope restores the engine's global bindings and returns it to the pool. The reset undoes declared variables and functions, top-level let/const/class, overwritten globals, scope-only methods (such as a recipe's variables() or a workflow's workflow()), interop wrapper caches, and pending promises. Registered globals go back to their not-yet-created state so the next evaluation builds them from its own services, and the HostDefined services slot is cleared.

Jint 4.16 and 4.17 Behavior Changes for Script Authors

Built-In Global Methods

Generic Functions

| Function | Description |

|---|---|

| log(level, text, param) | Writes a log message at the specified log level |

| uuid() | Generates a unique content item identifier |

| base64(string) | Decodes a string from Base64 encoding |

| html(string) | Decodes a string from HTML encoding |

| gzip(string) | Decodes a string from gzip/base64 encoding |

| protect(purpose, value) | Protects a value using ASP.NET Core Data Protection with the given purpose string (development and testing only, do not store production secrets in recipes) |

| encrypt(value) | Encrypts a value and returns Base64 ciphertext |

| decrypt(value) | Decrypts Base64 ciphertext and returns an empty string if it cannot be decrypted |

Content Functions (`OrchardCore.Contents`)

| Function | Description |

|---|---|

| newContentItemAsync(contentTypeName) | Creates a new ContentItem instance (not persisted) |

| createContentItemAsync(contentTypeName, publish, properties) | Creates, persists, and optionally publishes a ContentItem |

| updateContentItemAsync(contentItem, properties) | Updates an existing ContentItem with properties |

| deleteContentItemAsync(contentItem) | Deletes an existing ContentItem |

| getUrlPrefix(path) | Prefixes a path with the tenant URL prefix |

Layer Rule Functions (`OrchardCore.Layers`)

| Function | Description |

|---|---|

| isHomepage() | Returns true if the current URL is the homepage |

| isAnonymous() | Returns true if no user is authenticated |

| isAuthenticated() | Returns true if a user is authenticated |

| url(url) | Returns true if the current URL matches (supports * wildcard) |

| culture(name) | Returns true if the current culture or its parent matches |

Query Functions (`OrchardCore.Queries`)

| Function | Description |

|---|---|

| executeQueryAsync(name, parameters) | Executes a named query and returns results |

HTTP Functions (`OrchardCore.Workflows.Http`)

| Function | Description |

|---|---|

| httpContext() | Returns the current HttpContext |

| queryString(name) | Returns the query string value as a string, a list of strings, or null; with no argument returns the whole query string |

| responseWriteAsync(text) | Writes text directly to the HTTP response |

| absoluteUrl(relativePath) | Converts a relative path to an absolute URL |

| readBodyAsync() | Returns the raw HTTP request body |

| requestForm(name) | Returns form field value(s) as a string, a list of strings, or null |

| deserializeRequestDataAsync() | Deserializes JSON or form request data to a dictionary; query and form values are strings or lists of strings |

Values read directly from ASP.NET Core, such as httpContext().Request.Query['name'], are still objects (they compare with == and concatenate without throwing). Use queryString('name') or requestForm('name') when you need a JavaScript string.

Recipe Functions (`OrchardCore.Recipes`)

| Function | Description |

|---|---|

| variables() | Declares and retrieves recipe variables |

| parameters() | Retrieves setup parameters (e.g., AdminUserId) |

| configuration(key, defaultValue) | Reads IShellConfiguration values with optional default |

Workflow Functions (`OrchardCore.Workflows`)

| Function | Description |

|---|---|

| workflow() | Returns the WorkflowExecutionContext |

| workflowId() | Returns the unique workflow ID |

| input(name) | Returns a workflow input parameter |

| output(name, value) | Sets a workflow output parameter |

| property(name) / setProperty(name, value) | Reads or writes a workflow property |

| lastResult() | Returns the previous activity's result |

| correlationId() / setCorrelationId(id) | Reads or sets the workflow correlation ID |

| signalUrl(signal) | Generates a protected signal trigger URL |

| setOutcome(outcome) | Adds an outcome to the current activity |

| createWorkflowToken(workflowTypeId, activityId, expiresInDays) | Generates a workflow SAS token |

See orchardcore-workflows for how workflow scripts fault the workflow when an execution limit stops them.

File Scripting Engine

The file: prefix reads file contents relative to the application root:

| Function | Example | Description |

|---|---|---|

| text | file:text('../wwwroot/template.html') | Returns file content as text |

| base64 | file:base64('../wwwroot/image.jpg') | Returns file content as Base64 |

Using Scripts in Recipes

Recipe steps support [js: expression] syntax for dynamic values:

{
  "steps": [
    {
      "name": "Content",
      "data": [
        {
          "ContentItemId": "[js: uuid()]",
          "ContentType": "BlogPost",
          "DisplayText": "Welcome Post",
          "Latest": true,
          "Published": true,
          "Owner": "[js: parameters('AdminUserId')]",
          "TitlePart": {
            "Title": "Welcome Post"
          }
        }
      ]
    }
  ]
}

Using Recipe Variables

Declare variables at the root of a recipe and reference them in steps:

{
  "variables": {
    "blogContentItemId": "[js: uuid()]",
    "homePageId": "[js: uuid()]"
  },
  "steps": [
    {
      "name": "Content",
      "data": [
        {
          "ContentItemId": "[js: variables('blogContentItemId')]",
          "ContentType": "Blog",
          "DisplayText": "My Blog"
        }
      ]
    }
  ]
}

Reading Configuration in Recipes

Use the configuration() function to read IShellConfiguration values. Use the Orchard Core 4.0 section names (Admin, not OrchardCore_Admin):

{
  "steps": [
    {
      "name": "Settings",
      "AdminUrlPrefix": "[js: configuration('Admin:AdminUrlPrefix', 'Admin')]"
    }
  ]
}

IGlobalMethodProvider — When and Why

Purpose

IGlobalMethodProvider is the extension point for exposing custom functions to the Orchard Core scripting engine. Any function registered through this interface becomes available to all scripting contexts — recipes, layer rules, workflow expressions, and programmatic IScriptingManager calls.

When to Use IGlobalMethodProvider

When NOT to Use IGlobalMethodProvider

Key Types

IGlobalMethodProvider   — Interface with a single method: GetMethods()
GlobalMethod            — Name (string), Method and AsyncMethod (Func<IServiceProvider, Delegate>)
IScriptingManager       — Aggregates all registered IGlobalMethodProvider instances
JavaScriptEngine        — Declares registered globals lazily on the shared Jint.Options

How Globals Are Created (Lazy Globals and Engine Reuse)

The GlobalMethod Delegate Pattern

Method and AsyncMethod have the type Func<IServiceProvider, Delegate>. Each is a factory that receives the evaluation's IServiceProvider (or null) and returns a strongly-typed delegate:

Writing a Provider That Is Correct Under Engine Reuse

using Microsoft.Extensions.DependencyInjection;
using OrchardCore.ContentManagement;
using OrchardCore.Modules;
using OrchardCore.Scripting;

namespace MyModule.Scripting;

public sealed class ContentHelpersMethodProvider : IGlobalMethodProvider
{
    // Static, immutable GlobalMethod definitions: no request state is captured here.
    private static readonly GlobalMethod _utcNow = new()
    {
        Name = "utcNowIso",
        Method = serviceProvider => (Func<string>)(() =>
        {
            // serviceProvider is null when the script runs outside a tenant.
            var clock = serviceProvider?.GetService<IClock>();
            var now = clock?.UtcNow ?? DateTime.UtcNow;

            return now.ToString("O");
        }),
    };

    private static readonly GlobalMethod _displayText = new()
    {
        // Exposed to scripts as displayTextAsync(contentItemId), which returns a Promise.
        Name = "displayText",
        AsyncMethod = serviceProvider => (Func<string, Task<string>>)(async contentItemId =>
        {
            if (serviceProvider is null)
            {
                throw new InvalidOperationException("displayTextAsync() requires a tenant scope.");
            }

            // Scoped service resolved from the evaluation's own provider, at call time.
            var contentManager = serviceProvider.GetRequiredService<IContentManager>();
            var contentItem = await contentManager.GetAsync(contentItemId);

            // Return a plain CLR value, not the ContentItem graph, so nothing large is
            // retained by a pooled engine's call-site caches after the request ends.
            return contentItem?.DisplayText;
        }),
    };

    public IEnumerable<GlobalMethod> GetMethods()
        => [_utcNow, _displayText];
}

Rules this example follows:

Other Provider Patterns

Static Methods (No Service Dependencies)

Reference: CommonGeneratorMethods in OrchardCore.Infrastructure — provides base64(), html(), and gzip().

using System.Net;
using OrchardCore.Scripting;

namespace MyModule;

public sealed class EncodingMethodProvider : IGlobalMethodProvider
{
    private static readonly GlobalMethod _urlEncode = new()
    {
        Name = "urlEncode",
        Method = serviceProvider => (Func<string, string>)(value => WebUtility.UrlEncode(value)),
    };

    private static readonly GlobalMethod _urlDecode = new()
    {
        Name = "urlDecode",
        Method = serviceProvider => (Func<string, string>)(value => WebUtility.UrlDecode(value)),
    };

    public IEnumerable<GlobalMethod> GetMethods()
        => [_urlEncode, _urlDecode];
}
Resolving Services from IServiceProvider

Reference: ProtectDataProvider in OrchardCore.Scripting resolves IDataProtectionProvider; IdGeneratorMethod resolves IIdGenerator.

using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Scripting;

namespace MyModule;

public sealed class ProtectDataProvider : IGlobalMethodProvider
{
    private static readonly GlobalMethod _protect = new()
    {
        Name = "protect",
        Method = serviceProvider => (Func<string, string, string>)((purpose, value) =>
        {
            ArgumentException.ThrowIfNullOrEmpty(purpose);
            ArgumentException.ThrowIfNullOrEmpty(value);

            var dataProtectionProvider = serviceProvider.GetRequiredService<IDataProtectionProvider>();

            return dataProtectionProvider.CreateProtector(purpose).Protect(value);
        }),
    };

    public IEnumerable<GlobalMethod> GetMethods()
        => [_protect];
}
Constructor Injection for Singleton Services

Reference: LogProvider in OrchardCore.Scripting injects ILogger<LogProvider>; ConfigurationMethodProvider injects IShellConfiguration.

using Microsoft.Extensions.Logging;
using OrchardCore.Scripting;

namespace MyModule;

public sealed class AuditLogMethodProvider : IGlobalMethodProvider
{
    private readonly GlobalMethod _audit;

    public AuditLogMethodProvider(ILogger<AuditLogMethodProvider> logger)
    {
        _audit = new GlobalMethod
        {
            Name = "audit",
            Method = serviceProvider => (Action<string>)(message =>
                logger.LogInformation("Script audit: {Message}", message)),
        };
    }

    public IEnumerable<GlobalMethod> GetMethods()
        => [_audit];
}

Registering a Custom Global Method Provider

Register the provider as a singleton in your module's Startup.cs:

using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Modules;
using OrchardCore.Scripting;

namespace MyModule;

public sealed class Startup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IGlobalMethodProvider, EncodingMethodProvider>();
        services.AddSingleton<IGlobalMethodProvider, ContentHelpersMethodProvider>();
    }
}

Common Delegate Signatures

| Signature | Use Case |

|---|---|

| Func<string> | No parameters, returns a string (e.g., uuid()) |

| Func<string, string> | One string parameter, returns a string (e.g., base64(encoded)) |

| Func<string, string, string> | Two string parameters, returns a string (e.g., protect(purpose, value)) |

| Func<string, bool> | One string parameter, returns a boolean (e.g., url(pattern)) |

| Action<string, string, object> | Multiple parameters, no return value (e.g., log(level, text, param)) |

| Func<string, Task<string>> | AsyncMethod, exposed as <name>Async() returning a Promise |

Anti-Patterns to Avoid

// ❌ WRONG — no natural delegate type, cannot become a global
Method = serviceProvider => (args) => $"Hello, {args[0]}!",

// ✅ CORRECT — strongly-typed Func delegate
Method = serviceProvider => (Func<string, string>)(name => $"Hello, {name}!"),
// ❌ WRONG — ISession is scoped, but IGlobalMethodProvider is a singleton (captive dependency)
public sealed class BadProvider : IGlobalMethodProvider
{
    private readonly ISession _session;

    public BadProvider(ISession session) => _session = session;

    public IEnumerable<GlobalMethod> GetMethods() => [];
}

// ❌ WRONG — caches the delegate built for the first request's services
private Delegate _cached;
Method = serviceProvider => _cached ??= (Func<string>)(() => serviceProvider.GetRequiredService<IFoo>().Value),

// ✅ CORRECT — resolve scoped services from the evaluation's provider every time
Method = serviceProvider => (Func<string, object>)(contentType =>
{
    var session = serviceProvider.GetRequiredService<ISession>();
    return null;
}),

Layer Rules with Scripting

Layer rules use JavaScript expressions to determine visibility. A JavaScript rule condition is bounded by HttpContext.RequestAborted, and saving a condition with a syntax error now shows a validation message (Jint.ScriptPreparationException) instead of an unhandled exception.

// Show only on the homepage
isHomepage()

// Show to authenticated users only
isAuthenticated()

// Show on URLs starting with /blog
url("~/blog*")

// Combine conditions
isAuthenticated() && !isHomepage()

// Culture-specific content
culture("en")

Upgrading from 3.x

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.