@diagonal-hq/cli 0.12.3 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -300524,1910 +300524,1917 @@ function pageKeyOf(path, ast) {
300524
300524
  }
300525
300525
  }
300526
300526
 
300527
- // scripts/lib/runtime-build/workflow-tests.mjs
300528
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300529
- var import_typescript2 = __toESM(require_typescript(), 1);
300530
- import { spawnSync } from "node:child_process";
300531
- import { mkdirSync, mkdtempSync, realpathSync as realpathSync2, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
300532
- import { tmpdir } from "node:os";
300533
- import { dirname as dirname4, join as join9, relative as relative3 } from "node:path";
300534
-
300535
- // scripts/lib/runtime-build/script-sdk.mjs
300527
+ // scripts/lib/runtime-build/workflow-config.mjs
300536
300528
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300537
- import { readFileSync as readFileSync6, readdirSync as readdirSync2, statSync as statSync3 } from "node:fs";
300538
- import { createRequire } from "node:module";
300539
- import { dirname as dirname3, join as join8, relative as relative2, resolve as resolve4 } from "node:path";
300540
- import { fileURLToPath } from "node:url";
300541
- var SCRIPT_SDK_ROOT = resolve4(
300542
- dirname3(fileURLToPath(import.meta.url)),
300543
- "../../../packages/workflows/src"
300544
- );
300545
- var SDK_RUNTIME_ENTRY_POINTS = {
300546
- workflow: join8(SCRIPT_SDK_ROOT, "index.ts"),
300547
- testing: join8(SCRIPT_SDK_ROOT, "testing/index.ts")
300529
+ var WORKFLOW_STAGE = "workflow";
300530
+ var UUID_PATTERN2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
300531
+ var ROUTE_PATTERN = /^\/[a-z0-9\-_/{}]*$/;
300532
+ var ROUTE_PARAM_PATTERN = /\{([^}]+)\}/g;
300533
+ var CRON_FIELD_PATTERN = /^[0-9A-Za-z*/,\-?#]+$/;
300534
+ var OFFSET_PATTERN = /^[+-]P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/i;
300535
+ var WORKFLOW_PATH_PATTERN = /^workflows\/[^/]+\.ts$/;
300536
+ var CONFIG_KEYS = /* @__PURE__ */ new Set(["uid", "title", "description", "trigger", "runAs", "authorizer"]);
300537
+ var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
300538
+ var RECORD_EVENTS = ["created", "updated", "deleted", "restored", "saved"];
300539
+ var LIFECYCLE_HOOKS = ["creating", "updating", "saving", "deleting", "restoring"];
300540
+ var WORKFLOW_EVENTS = ["execution.success", "execution.error", "execution.exception"];
300541
+ var SCHEDULE_FIELD_TYPES = /* @__PURE__ */ new Set(["date", "datetime"]);
300542
+ var TRIGGERS = {
300543
+ request: {
300544
+ type: "request",
300545
+ keys: ["type", "path", "method"],
300546
+ background: false,
300547
+ sync: true
300548
+ },
300549
+ recordEvent: {
300550
+ type: "event.record",
300551
+ keys: ["type", "resource", "event", "filters"],
300552
+ background: true,
300553
+ sync: false
300554
+ },
300555
+ recordLifecycle: {
300556
+ type: "lifecycle.record",
300557
+ keys: ["type", "resource", "hook"],
300558
+ background: false,
300559
+ sync: true
300560
+ },
300561
+ recordSchedule: {
300562
+ type: "schedule.record",
300563
+ keys: ["type", "resource", "dateField", "offsets"],
300564
+ background: true,
300565
+ sync: false
300566
+ },
300567
+ scheduled: {
300568
+ type: "scheduled",
300569
+ keys: ["type", "expression"],
300570
+ background: true,
300571
+ sync: false
300572
+ },
300573
+ workflowEvent: {
300574
+ type: "event.workflow",
300575
+ keys: ["type", "workflow", "event"],
300576
+ background: true,
300577
+ sync: false
300578
+ },
300579
+ manual: {
300580
+ type: "manual",
300581
+ keys: ["type"],
300582
+ background: false,
300583
+ sync: true
300584
+ }
300548
300585
  };
300549
- function walk(directory) {
300550
- return readdirSync2(directory).flatMap(
300551
- (name) => statSync3(join8(directory, name)).isDirectory() ? walk(join8(directory, name)) : [join8(directory, name)]
300552
- );
300586
+ function unwrap(node) {
300587
+ let current = node;
300588
+ while (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSNonNullExpression" || current.type === "ParenthesizedExpression") {
300589
+ current = current.expression;
300590
+ }
300591
+ return current;
300553
300592
  }
300554
- function readSandboxSdkFiles() {
300555
- return Object.fromEntries(
300556
- walk(SCRIPT_SDK_ROOT).filter(
300557
- (file2) => file2.endsWith(".ts") && !file2.includes("/testing/") && !file2.endsWith("/http-transport.ts") && !file2.endsWith("/workspace.generated.ts")
300558
- ).map((file2) => [`/sdk/${relative2(SCRIPT_SDK_ROOT, file2)}`, readFileSync6(file2, "utf8")])
300559
- );
300593
+ function propertyNodes(node) {
300594
+ const unwrapped = node === void 0 ? null : unwrap(node);
300595
+ const nodes = /* @__PURE__ */ new Map();
300596
+ if (unwrapped?.type !== "ObjectExpression") {
300597
+ return nodes;
300598
+ }
300599
+ for (const property of unwrapped.properties) {
300600
+ if (property.type === "ObjectProperty") {
300601
+ nodes.set(propertyKey(property), property);
300602
+ }
300603
+ }
300604
+ return nodes;
300560
300605
  }
300561
- function bundleSdkRuntime(buildSync) {
300562
- const result = buildSync({
300563
- entryPoints: SDK_RUNTIME_ENTRY_POINTS,
300564
- outdir: "/sdk",
300565
- bundle: true,
300566
- splitting: true,
300567
- platform: "node",
300568
- target: "node24",
300569
- format: "esm",
300570
- write: false,
300571
- logLevel: "silent"
300572
- });
300573
- return Object.fromEntries(
300574
- result.outputFiles.map((file2) => [relative2("/sdk", file2.path), file2.text])
300575
- );
300606
+ function listOf(values) {
300607
+ return values.map((value) => `'${value}'`).join(", ");
300576
300608
  }
300577
- var sdkFiles;
300578
- try {
300579
- ({ SDK_FILES: sdkFiles } = await Promise.resolve().then(() => (init_sdk_files_generated(), sdk_files_generated_exports)));
300580
- } catch (error) {
300581
- if (error?.code !== "ERR_MODULE_NOT_FOUND") {
300582
- throw error;
300583
- }
300584
- sdkFiles = readSandboxSdkFiles();
300609
+ function blank(text) {
300610
+ return text.replaceAll(/[^\n]/g, " ");
300585
300611
  }
300586
- var SCRIPT_SDK_FILES = sdkFiles;
300587
- var sdkRuntimeFiles = null;
300588
- function scriptSdkRuntimeFiles() {
300589
- sdkRuntimeFiles ??= define_globalThis_DIAGONAL_SDK_RUNTIME_default ?? bundleSdkRuntime(createRequire(import.meta.url)("esbuild").buildSync);
300590
- return sdkRuntimeFiles;
300612
+ function workflowConfigObject(ast) {
300613
+ const statements2 = ast.program.body.filter(isConfigExport);
300614
+ const declarations = statements2[0]?.declaration.declarations ?? [];
300615
+ const init = statements2.length === 1 && declarations.length === 1 ? declarations[0].init : null;
300616
+ const object = init === null || init === void 0 ? null : unwrap(init);
300617
+ return object?.type === "ObjectExpression" ? object : null;
300591
300618
  }
300592
-
300593
- // scripts/lib/runtime-build/workflow-tests.mjs
300594
- var WORKFLOW_TEST_STAGE = "workflow test";
300595
- var WORKFLOW_TEST_SUFFIX = ".test.ts";
300596
- var TEST_TIMEOUT_MS = 1e4;
300597
- var RUN_TIMEOUT_MS = 6e4;
300598
- var RESULT_PREFIX = "\0diagonal-test ";
300599
- var SDK_MODULES = {
300600
- "@diagonal/workflow": "sdk/workflow.js",
300601
- "@diagonal/workflow/testing": "sdk/testing.js",
300602
- "@diagonal/workflow/workspace": "sdk/workspace.js",
300603
- [AUTHORING_MODULE]: "sdk/runtime.js"
300604
- };
300605
- var NODE_TEST_MODULES = /* @__PURE__ */ new Set(["node:test", "node:assert", "node:assert/strict"]);
300606
- var TEST_MODULE_EXTERNALS = /* @__PURE__ */ new Set([...Object.keys(SDK_MODULES), ...NODE_TEST_MODULES]);
300607
- var RELATIVE_WORKFLOW = /^\.\/([^/]+?)(?:\.ts|\.js)?$/;
300608
- var REPORTER_SOURCE = `const PREFIX = ${JSON.stringify(RESULT_PREFIX)};
300609
- export default async function* reporter(source) {
300610
- const names = [];
300611
- for await (const event of source) {
300612
- const data = event.data;
300613
- if (event.type === 'test:start') {
300614
- names.length = data.nesting;
300615
- names.push(data.name);
300619
+ function isConfigExport(statement2) {
300620
+ return statement2.type === "ExportNamedDeclaration" && statement2.declaration?.type === "VariableDeclaration" && statement2.declaration.declarations.some(
300621
+ (declarator) => declarator.id.type === "Identifier" && declarator.id.name === "config"
300622
+ );
300623
+ }
300624
+ function splitWorkflowModule(path, source, ast) {
300625
+ const diagnostics = [];
300626
+ const ranges = [];
300627
+ let configNode = null;
300628
+ let configCount = 0;
300629
+ let hasDefault = false;
300630
+ for (const statement2 of ast.program.body) {
300631
+ if (statement2.type === "ImportDeclaration" && isAuthoringModule(statement2.source.value)) {
300632
+ ranges.push(statement2);
300616
300633
  continue;
300617
300634
  }
300618
- if (event.type !== 'test:pass' && event.type !== 'test:fail') {
300635
+ if (statement2.type === "ExportDefaultDeclaration") {
300636
+ hasDefault = true;
300619
300637
  continue;
300620
300638
  }
300621
- const error = data.details?.error;
300622
- if (data.details?.type === 'suite' && (event.type === 'test:pass' || error?.failureType === 'subtestsFailed')) {
300639
+ if (!isConfigExport(statement2)) {
300623
300640
  continue;
300624
300641
  }
300625
- const path = [...names.slice(0, data.nesting), data.name].join(' > ');
300626
- const cause = error?.cause ?? error;
300627
- yield PREFIX + JSON.stringify({
300628
- file: data.file ?? null,
300629
- name: path,
300630
- leaf: data.name,
300631
- ok: event.type === 'test:pass',
300632
- message: event.type === 'test:pass' ? null : String(cause?.message ?? cause ?? 'The test failed').trim()
300633
- }) + '\\n';
300634
- }
300635
- }
300636
- `;
300637
- function moduleSpecifierNodes(ast) {
300638
- return ast.program.body.filter(
300639
- (statement2) => (statement2.type === "ImportDeclaration" || statement2.type === "ExportNamedDeclaration" || statement2.type === "ExportAllDeclaration") && statement2.source
300640
- ).map((statement2) => statement2.source);
300641
- }
300642
- function transpile(path, source, ast, resolveSpecifier) {
300643
- let rewritten = source;
300644
- for (const node of moduleSpecifierNodes(ast).toSorted(
300645
- (left, right) => right.start - left.start
300646
- )) {
300647
- const target = resolveSpecifier(node.value);
300648
- if (target !== null) {
300649
- rewritten = `${rewritten.slice(0, node.start)}${JSON.stringify(target)}${rewritten.slice(node.end)}`;
300642
+ configCount++;
300643
+ ranges.push(statement2);
300644
+ const declaration = statement2.declaration;
300645
+ if (configCount > 1) {
300646
+ diagnostics.push(
300647
+ diagnosticAt(path, statement2, "A workflow can export only one config", {
300648
+ stage: WORKFLOW_STAGE
300649
+ })
300650
+ );
300651
+ continue;
300650
300652
  }
300651
- }
300652
- return import_typescript2.default.transpileModule(rewritten, {
300653
- fileName: path,
300654
- compilerOptions: {
300655
- target: import_typescript2.default.ScriptTarget.ES2023,
300656
- module: import_typescript2.default.ModuleKind.ESNext,
300657
- sourceMap: false
300653
+ if (declaration.kind !== "const" || declaration.declarations.length !== 1) {
300654
+ diagnostics.push(
300655
+ diagnosticAt(
300656
+ path,
300657
+ statement2,
300658
+ "Declare the config alone as `export const config = { ... }`",
300659
+ { stage: WORKFLOW_STAGE }
300660
+ )
300661
+ );
300662
+ continue;
300658
300663
  }
300659
- }).outputText;
300660
- }
300661
- function sdkSpecifier(fromDirectory) {
300662
- return (specifier) => Object.hasOwn(SDK_MODULES, specifier) ? `${fromDirectory}${SDK_MODULES[specifier]}` : null;
300663
- }
300664
- function testCallNode(ast, name) {
300665
- const pending = [ast.program];
300666
- while (pending.length > 0) {
300667
- const node = pending.pop();
300668
- const [first] = node.type === "CallExpression" ? node.arguments : [];
300669
- if (first !== void 0 && (first.type === "StringLiteral" || first.type === "TemplateLiteral" && first.expressions.length === 0) && (first.type === "StringLiteral" ? first.value : first.quasis[0].value.cooked) === name) {
300670
- return node;
300664
+ const init = declaration.declarations[0].init;
300665
+ if (init === null || init === void 0) {
300666
+ diagnostics.push(
300667
+ diagnosticAt(path, statement2, "The config needs a value", { stage: WORKFLOW_STAGE })
300668
+ );
300669
+ continue;
300671
300670
  }
300672
- pending.push(...childNodes(node));
300671
+ configNode = init;
300673
300672
  }
300674
- return null;
300675
- }
300676
- function importDiagnostics(test, workflowNames, workspaceRoot) {
300677
- const diagnostics = [];
300678
- for (const node of moduleSpecifierNodes(test.ast)) {
300679
- const specifier = node.value;
300680
- const relative5 = RELATIVE_WORKFLOW.exec(specifier);
300681
- if (NODE_TEST_MODULES.has(specifier) || Object.hasOwn(SDK_MODULES, specifier) || relative5 !== null && workflowNames.has(relative5[1]) || isAppSpecifier(specifier) && workspaceRoot !== null && resolveAppSpecifier(workspaceRoot, specifier) !== null) {
300682
- continue;
300683
- }
300673
+ if (configCount === 0) {
300684
300674
  diagnostics.push(
300685
300675
  diagnosticAt(
300686
- test.path,
300687
- node,
300688
- `A workflow test can import only node:test, node:assert, @diagonal/workflow, @diagonal/workflow/testing, @diagonal/workflow/workspace, the workflows in workflows/, and workspace files by @app/. "${specifier}" is not one of them`,
300689
- { stage: WORKFLOW_TEST_STAGE }
300676
+ path,
300677
+ null,
300678
+ "The workflow has no config. Add `export const config = { title, trigger }`",
300679
+ { stage: WORKFLOW_STAGE }
300690
300680
  )
300691
300681
  );
300692
300682
  }
300693
- return diagnostics;
300694
- }
300695
- function sandboxPath(path) {
300696
- return path.replace(/\.(ts|tsx|js|jsx)$/, ".js");
300697
- }
300698
- function sandboxPrefix(path) {
300699
- return "../".repeat(path.split("/").length - 1) || "./";
300700
- }
300701
- function relativeSandboxPath(from, target) {
300702
- const path = relative3(dirname4(from), sandboxPath(target));
300703
- return path.startsWith(".") ? path : `./${path}`;
300704
- }
300705
- function writeFile(root, path, content) {
300706
- mkdirSync(dirname4(join9(root, path)), { recursive: true });
300707
- writeFileSync3(join9(root, path), content);
300708
- }
300709
- function parseResults(stdout) {
300710
- return stdout.split("\n").filter((line) => line.startsWith(RESULT_PREFIX)).map((line) => JSON.parse(line.slice(RESULT_PREFIX.length)));
300683
+ if (!hasDefault) {
300684
+ diagnostics.push(
300685
+ diagnosticAt(
300686
+ path,
300687
+ null,
300688
+ "The workflow has no default export. Add `export default defineWorkflow(...)`",
300689
+ { stage: WORKFLOW_STAGE }
300690
+ )
300691
+ );
300692
+ }
300693
+ let scriptSource = source;
300694
+ for (const node of ranges.toSorted((left, right) => right.start - left.start)) {
300695
+ scriptSource = scriptSource.slice(0, node.start) + blank(scriptSource.slice(node.start, node.end)) + scriptSource.slice(node.end);
300696
+ }
300697
+ return { configNode, scriptSource, diagnostics };
300711
300698
  }
300712
- function runWorkflowTests({
300713
- tests,
300714
- workflows,
300715
- root: workspaceRoot = null,
300716
- appModules = /* @__PURE__ */ new Map()
300717
- }) {
300699
+ function readWorkflowConfig(path, configNode, context) {
300718
300700
  const diagnostics = [];
300719
- const workflowNames = new Map(
300720
- workflows.map((workflow) => [workflow.path.slice("workflows/".length, -".ts".length), workflow])
300721
- );
300722
- const runnable = [];
300723
- for (const test of tests) {
300724
- const workflowPath = `${test.path.slice(0, -WORKFLOW_TEST_SUFFIX.length)}.ts`;
300725
- if (!workflowNames.has(workflowPath.slice("workflows/".length, -".ts".length))) {
300726
- diagnostics.push(
300727
- diagnosticAt(
300728
- test.path,
300729
- null,
300730
- `The test file has no workflow. Add ${workflowPath} or remove the test file`,
300731
- { stage: WORKFLOW_TEST_STAGE }
300732
- )
300733
- );
300734
- continue;
300701
+ const report = (node, message) => diagnostics.push(diagnosticAt(path, node, message, { stage: WORKFLOW_STAGE }));
300702
+ let value;
300703
+ try {
300704
+ value = staticValue(configNode, { resources: context.resourcesBinding });
300705
+ } catch (error) {
300706
+ if (!(error instanceof SourceError)) {
300707
+ throw error;
300735
300708
  }
300736
- const imports = importDiagnostics(test, workflowNames, workspaceRoot);
300737
- diagnostics.push(...imports);
300738
- if (imports.length === 0) {
300739
- runnable.push({ ...test, workflow: workflowPath });
300709
+ report(error.node, error.message);
300710
+ return { config: null, diagnostics };
300711
+ }
300712
+ if (!isPlainObject(value)) {
300713
+ report(configNode, "The config must be an object literal");
300714
+ return { config: null, diagnostics };
300715
+ }
300716
+ const nodes = propertyNodes(configNode);
300717
+ const at = (key) => nodes.get(key) ?? configNode;
300718
+ for (const key of Object.keys(value)) {
300719
+ if (!CONFIG_KEYS.has(key)) {
300720
+ report(at(key), `Unknown workflow config option "${key}"`);
300740
300721
  }
300741
300722
  }
300742
- if (runnable.length === 0) {
300743
- return { workflowTests: [], diagnostics };
300723
+ const title = value.title;
300724
+ if (typeof title !== "string" || title.trim() === "") {
300725
+ report(at("title"), '"title" is required and must be a non-empty string');
300744
300726
  }
300745
- const modules = new Map(appModules);
300746
- for (const test of runnable) {
300747
- for (const [path, module] of appModuleClosure(
300748
- workspaceRoot,
300749
- workspaceRoot === null ? [] : appImportsOf(workspaceRoot, test.path, test.ast),
300750
- TEST_MODULE_EXTERNALS
300751
- )) {
300752
- modules.set(path, module);
300727
+ const description = value.description ?? null;
300728
+ if (description !== null && typeof description !== "string") {
300729
+ report(at("description"), '"description" must be a string');
300730
+ }
300731
+ const scoped = { ...context, path };
300732
+ const trigger = readTrigger(value.trigger, at("trigger"), scoped, report);
300733
+ const runAs = trigger === null ? null : readRunAs(value.runAs, at("runAs"), trigger, scoped, report);
300734
+ const authorizer = readAuthorizer(value.authorizer, at("authorizer"), trigger, report);
300735
+ if (diagnostics.length > 0 || trigger === null) {
300736
+ return { config: null, diagnostics };
300737
+ }
300738
+ return {
300739
+ config: {
300740
+ title,
300741
+ description,
300742
+ type: trigger.definition.type,
300743
+ settings: trigger.settings,
300744
+ run_as: runAs,
300745
+ authorizer,
300746
+ execution_mode: trigger.definition.sync ? "sync" : "async"
300747
+ },
300748
+ diagnostics
300749
+ };
300750
+ }
300751
+ function resolveResource(reference, node, context, report) {
300752
+ if (typeof reference !== "string" || reference === "") {
300753
+ report(node, '"resource" must be Resources.<Name>.slug');
300754
+ return null;
300755
+ }
300756
+ const resource = context.findResource(reference);
300757
+ if (resource === void 0) {
300758
+ if (context.reportUnknownResources) {
300759
+ report(node, referenceProblem(reference, context.resources, context.names).message);
300753
300760
  }
300761
+ return null;
300754
300762
  }
300755
- const root = realpathSync2(mkdtempSync(join9(tmpdir(), "diagonal-workflow-tests-")));
300756
- try {
300757
- writeFile(root, "package.json", '{"type":"module"}\n');
300758
- writeFile(root, "reporter.mjs", REPORTER_SOURCE);
300759
- for (const [path, content] of Object.entries(scriptSdkRuntimeFiles())) {
300760
- writeFile(root, `sdk/${path}`, content);
300763
+ return resource;
300764
+ }
300765
+ function oneOf(trigger, key, allowed, at, report) {
300766
+ const item = trigger[key];
300767
+ if (!allowed.includes(item)) {
300768
+ report(at(key), `"${key}" must be one of: ${listOf(allowed)}`);
300769
+ return null;
300770
+ }
300771
+ return item;
300772
+ }
300773
+ function readTrigger(trigger, triggerNode, context, report) {
300774
+ if (!isPlainObject(trigger)) {
300775
+ report(triggerNode, `"trigger" is required: { type: ${listOf(Object.keys(TRIGGERS))}, ... }`);
300776
+ return null;
300777
+ }
300778
+ const nodes = propertyNodes(triggerNode.value ?? triggerNode);
300779
+ const at = (key) => nodes.get(key) ?? triggerNode;
300780
+ const definition = Object.hasOwn(TRIGGERS, trigger.type) ? TRIGGERS[trigger.type] : void 0;
300781
+ if (definition === void 0) {
300782
+ report(at("type"), `"trigger.type" must be one of: ${listOf(Object.keys(TRIGGERS))}`);
300783
+ return null;
300784
+ }
300785
+ let failed = false;
300786
+ const fail = (node, message) => {
300787
+ failed = true;
300788
+ report(node, message);
300789
+ };
300790
+ for (const key of Object.keys(trigger)) {
300791
+ if (!definition.keys.includes(key)) {
300792
+ fail(at(key), `A ${trigger.type} trigger has no option "${key}"`);
300761
300793
  }
300762
- writeFile(root, "sdk/workspace.js", "export {};\n");
300763
- writeFile(root, "sdk/runtime.js", AUTHORING_HELPERS_MODULE);
300764
- for (const [path, module] of modules) {
300765
- const resolveSdk = sdkSpecifier(sandboxPrefix(path));
300766
- writeFile(
300767
- root,
300768
- sandboxPath(path),
300769
- transpile(
300770
- path,
300771
- module.source,
300772
- parseSource(module.source, { jsx: path.endsWith("x") }),
300773
- (specifier) => module.requires[specifier] === void 0 ? resolveSdk(specifier) : relativeSandboxPath(path, module.requires[specifier])
300774
- )
300775
- );
300794
+ }
300795
+ const settings = triggerSettings(trigger, at, context, fail);
300796
+ return failed || settings === null ? null : { definition, name: trigger.type, settings };
300797
+ }
300798
+ function triggerSettings(trigger, at, context, fail) {
300799
+ switch (trigger.type) {
300800
+ case "request": {
300801
+ const path = trigger.path;
300802
+ if (typeof path !== "string" || !ROUTE_PATTERN.test(path) || path.length > 255) {
300803
+ fail(
300804
+ at("path"),
300805
+ '"path" must start with "/" and contain only a-z, 0-9, -, _, /, and {param}'
300806
+ );
300807
+ return null;
300808
+ }
300809
+ const method = trigger.method === void 0 ? "GET" : oneOf(trigger, "method", HTTP_METHODS, at, fail);
300810
+ if (method === null) {
300811
+ return null;
300812
+ }
300813
+ const params = [...path.matchAll(ROUTE_PARAM_PATTERN)].map((match) => ({
300814
+ key: match[1],
300815
+ scope: null,
300816
+ relations: [],
300817
+ resource_id: null,
300818
+ lookup_field: null
300819
+ }));
300820
+ return { route: path, method, params };
300776
300821
  }
300777
- for (const workflow of workflows) {
300778
- writeFile(
300779
- root,
300780
- workflow.path.replace(/\.ts$/, ".js"),
300781
- transpile(workflow.path, workflow.source, workflow.ast, (specifier) => {
300782
- const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
300783
- return target === null ? sdkSpecifier("../")(specifier) : relativeSandboxPath(workflow.path, target);
300784
- })
300785
- );
300822
+ case "recordEvent": {
300823
+ const resource = resolveResource(trigger.resource, at("resource"), context, fail);
300824
+ const event = oneOf(trigger, "event", RECORD_EVENTS, at, fail);
300825
+ if (trigger.filters !== void 0 && trigger.filters !== null && typeof trigger.filters !== "object") {
300826
+ fail(at("filters"), '"filters" must be a filter object');
300827
+ }
300828
+ if (resource === null || event === null) {
300829
+ return null;
300830
+ }
300831
+ return trigger.filters === void 0 ? { event, resource: resource.slug } : { event, resource: resource.slug, filters: trigger.filters };
300786
300832
  }
300787
- for (const test of runnable) {
300788
- const resolveSdk = sdkSpecifier("../");
300789
- writeFile(
300790
- root,
300791
- test.path.replace(/\.ts$/, ".js"),
300792
- transpile(test.path, test.source, test.ast, (specifier) => {
300793
- const relative5 = RELATIVE_WORKFLOW.exec(specifier);
300794
- const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
300795
- if (target !== null) {
300796
- return relativeSandboxPath(test.path, target);
300797
- }
300798
- return relative5 !== null ? `./${relative5[1]}.js` : resolveSdk(specifier);
300799
- })
300800
- );
300833
+ case "recordLifecycle": {
300834
+ const resource = resolveResource(trigger.resource, at("resource"), context, fail);
300835
+ const hook = oneOf(trigger, "hook", LIFECYCLE_HOOKS, at, fail);
300836
+ return resource === null || hook === null ? null : { hook, resource: resource.slug };
300801
300837
  }
300802
- const run = spawnSync(
300803
- process.execPath,
300804
- [
300805
- "--permission",
300806
- `--allow-fs-read=${root}`,
300807
- "--test",
300808
- "--test-isolation=none",
300809
- `--test-timeout=${TEST_TIMEOUT_MS}`,
300810
- "--test-reporter=./reporter.mjs",
300811
- ...runnable.map((test) => test.path.replace(/\.ts$/, ".js"))
300812
- ],
300813
- {
300814
- cwd: root,
300815
- env: { TZ: "UTC" },
300816
- encoding: "utf8",
300817
- timeout: RUN_TIMEOUT_MS,
300818
- maxBuffer: 16 * 1024 * 1024
300838
+ case "recordSchedule": {
300839
+ const resource = resolveResource(trigger.resource, at("resource"), context, fail);
300840
+ const offsets = readOffsets(trigger.offsets, at("offsets"), fail);
300841
+ const dateField = trigger.dateField;
300842
+ if (typeof dateField !== "string" || dateField === "") {
300843
+ fail(at("dateField"), '"dateField" must be the key of a date or datetime field');
300844
+ return null;
300819
300845
  }
300820
- );
300821
- if (run.error !== void 0 && run.error.code !== "ETIMEDOUT") {
300822
- throw run.error;
300823
- }
300824
- const results = parseResults(run.stdout ?? "");
300825
- const timedOut = run.error?.code === "ETIMEDOUT" || run.signal !== null;
300826
- const workflowTests = runnable.map((test) => {
300827
- const file2 = join9(root, test.path.replace(/\.ts$/, ".js"));
300828
- const own = results.filter((result) => result.file === file2);
300829
- for (const result of own) {
300830
- if (!result.ok) {
300831
- const node = testCallNode(test.ast, result.leaf);
300832
- diagnostics.push(
300833
- diagnosticAt(test.path, node, `Test "${result.name}" failed: ${result.message}`, {
300834
- stage: WORKFLOW_TEST_STAGE
300835
- })
300846
+ if (resource !== null && resource.platform !== true) {
300847
+ const field2 = resource.fields.find((item) => item.key === dateField);
300848
+ if (field2 === void 0 || !SCHEDULE_FIELD_TYPES.has(field2.type)) {
300849
+ fail(
300850
+ at("dateField"),
300851
+ `"${dateField}" is not a date or datetime field of resource "${resource.slug}"`
300836
300852
  );
300853
+ return null;
300837
300854
  }
300838
300855
  }
300839
- if (timedOut) {
300840
- diagnostics.push(
300841
- diagnostic(
300842
- test.path,
300843
- 1,
300844
- 1,
300845
- `The workflow tests did not finish in ${RUN_TIMEOUT_MS / 1e3} seconds`,
300846
- { stage: WORKFLOW_TEST_STAGE }
300847
- )
300856
+ return resource === null || offsets === null ? null : { schedule: { offsets }, date_field: dateField, resource: resource.slug };
300857
+ }
300858
+ case "scheduled": {
300859
+ const expression2 = trigger.expression;
300860
+ const fields = typeof expression2 === "string" ? expression2.trim().split(/\s+/) : [];
300861
+ if (fields.length !== 5 || !fields.every((field2) => CRON_FIELD_PATTERN.test(field2))) {
300862
+ fail(
300863
+ at("expression"),
300864
+ '"expression" must be a cron expression with 5 fields, for example "0 2 * * *"'
300848
300865
  );
300849
- } else if (own.length === 0 && run.status !== 0) {
300850
- diagnostics.push(
300851
- diagnostic(
300852
- test.path,
300853
- 1,
300854
- 1,
300855
- `The workflow tests did not run: ${(run.stderr ?? "").trim().split("\n")[0] || `exit code ${run.status}`}`,
300856
- { stage: WORKFLOW_TEST_STAGE }
300857
- )
300866
+ return null;
300867
+ }
300868
+ return { expression: expression2 };
300869
+ }
300870
+ case "workflowEvent": {
300871
+ const workflow = trigger.workflow;
300872
+ const event = oneOf(trigger, "event", WORKFLOW_EVENTS, at, fail);
300873
+ if (typeof workflow !== "string" || !WORKFLOW_PATH_PATTERN.test(workflow)) {
300874
+ fail(
300875
+ at("workflow"),
300876
+ '"workflow" must be the path of a workflow, for example "workflows/welcome.ts"'
300858
300877
  );
300878
+ return null;
300859
300879
  }
300860
- return {
300861
- path: test.path,
300862
- workflow: test.workflow,
300863
- passed: own.filter((result) => result.ok).length,
300864
- failed: own.filter((result) => !result.ok).length,
300865
- results: own.map((result) => ({
300866
- name: result.name,
300867
- ok: result.ok,
300868
- message: result.message
300869
- }))
300870
- };
300871
- });
300872
- return { workflowTests, diagnostics };
300873
- } finally {
300874
- rmSync(root, { recursive: true, force: true });
300875
- }
300876
- }
300877
-
300878
- // scripts/lib/runtime-build/workflows.mjs
300879
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300880
-
300881
- // scripts/lib/workflow-script/compile.mjs
300882
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300883
- var import_typescript7 = __toESM(require_typescript(), 1);
300884
-
300885
- // scripts/lib/workflow-script/ast.mjs
300886
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300887
- var import_typescript3 = __toESM(require_typescript(), 1);
300888
- function unwrap(node) {
300889
- let current = node;
300890
- while (import_typescript3.default.isParenthesizedExpression(current) || import_typescript3.default.isAsExpression(current) || import_typescript3.default.isSatisfiesExpression(current)) {
300891
- current = current.expression;
300880
+ if (!context.workflowPaths.has(workflow)) {
300881
+ fail(at("workflow"), `Unknown workflow "${workflow}". Add the file or change the path`);
300882
+ return null;
300883
+ }
300884
+ if (workflow === context.path) {
300885
+ fail(at("workflow"), "A workflow cannot trigger on its own runs");
300886
+ return null;
300887
+ }
300888
+ return event === null ? null : { event, workflow: { path: workflow } };
300889
+ }
300890
+ case "manual":
300891
+ return {};
300892
+ default:
300893
+ return null;
300892
300894
  }
300893
- return current;
300894
- }
300895
- function propertyNameText(name) {
300896
- return import_typescript3.default.isIdentifier(name) || import_typescript3.default.isStringLiteral(name) ? name.text : null;
300897
300895
  }
300898
-
300899
- // scripts/lib/workflow-script/input-schema.mjs
300900
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300901
- var import_typescript4 = __toESM(require_typescript(), 1);
300902
- var SDK_MODULE = "@diagonal/workflow";
300903
- var SCALAR_KINDS = /* @__PURE__ */ new Set([
300904
- "text",
300905
- "email",
300906
- "url",
300907
- "uuid",
300908
- "phone",
300909
- "date",
300910
- "datetime",
300911
- "time",
300912
- "timezone",
300913
- "color",
300914
- "number",
300915
- "integer",
300916
- "money",
300917
- "boolean"
300918
- ]);
300919
- var SchemaError = class extends Error {
300920
- constructor(node, message) {
300921
- super(message);
300922
- this.node = node;
300923
- }
300924
- };
300925
- function extractInputSchema(file2, checker) {
300926
- const call = defineWorkflowCall(file2, checker);
300927
- if (call === null || call.arguments.length < 2) {
300928
- return { schema: null, findings: [] };
300896
+ function readOffsets(offsets, node, fail) {
300897
+ if (!Array.isArray(offsets) || offsets.length === 0) {
300898
+ fail(node, `"offsets" must be a list of signed ISO 8601 durations, for example ['-P1D']`);
300899
+ return null;
300929
300900
  }
300930
- try {
300931
- const schema = evaluate2(call.arguments[0], checker, /* @__PURE__ */ new Set());
300932
- if (schema.kind !== "object") {
300933
- throw new SchemaError(call.arguments[0], "The input schema must be v.object({ ... }).");
300934
- }
300935
- return { schema, findings: [] };
300936
- } catch (error) {
300937
- if (error instanceof SchemaError) {
300938
- return {
300939
- schema: null,
300940
- findings: [{ node: error.node, code: "static-input-schema", message: error.message }]
300941
- };
300901
+ for (const offset of offsets) {
300902
+ if (typeof offset !== "string" || !OFFSET_PATTERN.test(offset) || !/\d+[DHM]/i.test(offset)) {
300903
+ fail(
300904
+ node,
300905
+ `Offset ${JSON.stringify(offset)} must be a signed ISO 8601 duration in days, hours, or minutes, for example '-P1D' or '+PT2H'`
300906
+ );
300907
+ return null;
300942
300908
  }
300943
- throw error;
300944
300909
  }
300910
+ if (new Set(offsets).size !== offsets.length) {
300911
+ fail(node, "The offsets must be distinct");
300912
+ return null;
300913
+ }
300914
+ return offsets;
300945
300915
  }
300946
- function defineWorkflowCall(file2, checker) {
300947
- for (const statement2 of file2.statements) {
300948
- if (import_typescript4.default.isExportAssignment(statement2) && import_typescript4.default.isCallExpression(statement2.expression) && import_typescript4.default.isIdentifier(statement2.expression.expression) && sdkImportName(checker, statement2.expression.expression) === "defineWorkflow") {
300949
- return statement2.expression;
300916
+ function readRunAs(runAs, node, trigger, context, report) {
300917
+ const name = trigger.name;
300918
+ if (runAs === void 0 || runAs === null) {
300919
+ if (name === "request") {
300920
+ return { mode: "session" };
300921
+ }
300922
+ if (trigger.definition.background) {
300923
+ report(
300924
+ node,
300925
+ `A ${name} workflow runs in the background and needs an identity. Set runAs to 'system' or { resource, record }`
300926
+ );
300950
300927
  }
300928
+ return null;
300951
300929
  }
300952
- return null;
300953
- }
300954
- function sdkImportName(checker, identifier4) {
300955
- const declaration = checker.getSymbolAtLocation(identifier4)?.declarations?.[0];
300956
- if (declaration === void 0 || !import_typescript4.default.isImportSpecifier(declaration)) {
300930
+ if (name === "recordLifecycle") {
300931
+ report(node, "A recordLifecycle workflow runs inside the record write. Remove runAs");
300957
300932
  return null;
300958
300933
  }
300959
- const specifier = declaration.parent.parent.parent.moduleSpecifier;
300960
- return import_typescript4.default.isStringLiteral(specifier) && specifier.text === SDK_MODULE ? (declaration.propertyName ?? declaration.name).text : null;
300961
- }
300962
- var STATIC_HINT = "Build the input schema from v.* calls with literal arguments, so the platform can validate input before the script runs.";
300963
- function evaluate2(node, checker, visiting) {
300964
- const expression2 = unwrap(node);
300965
- if (import_typescript4.default.isIdentifier(expression2)) {
300966
- const declaration = checker.getSymbolAtLocation(expression2)?.valueDeclaration;
300967
- if (declaration === void 0 || !import_typescript4.default.isVariableDeclaration(declaration) || declaration.initializer === void 0 || !(import_typescript4.default.getCombinedNodeFlags(declaration) & import_typescript4.default.NodeFlags.Const) || !import_typescript4.default.isSourceFile(declaration.parent.parent.parent)) {
300968
- throw new SchemaError(
300969
- expression2,
300970
- `${expression2.text} is not a top-level const. ${STATIC_HINT}`
300934
+ if (runAs === "system") {
300935
+ return { mode: "system" };
300936
+ }
300937
+ if (runAs === "session") {
300938
+ if (name !== "request") {
300939
+ report(
300940
+ node,
300941
+ "runAs 'session' is only for request workflows. Use 'system' or { resource, record }"
300971
300942
  );
300943
+ return null;
300972
300944
  }
300973
- if (visiting.has(declaration)) {
300974
- throw new SchemaError(expression2, `${expression2.text} refers to itself.`);
300975
- }
300976
- visiting.add(declaration);
300977
- const spec = evaluate2(declaration.initializer, checker, visiting);
300978
- visiting.delete(declaration);
300979
- return spec;
300980
- }
300981
- if (!import_typescript4.default.isCallExpression(expression2) || !import_typescript4.default.isPropertyAccessExpression(expression2.expression)) {
300982
- throw new SchemaError(expression2, STATIC_HINT);
300945
+ return { mode: "session" };
300983
300946
  }
300984
- const method = expression2.expression.name.text;
300985
- const receiver = unwrap(expression2.expression.expression);
300986
- if (import_typescript4.default.isIdentifier(receiver) && sdkImportName(checker, receiver) === "v") {
300987
- return builder(method, expression2, checker, visiting);
300947
+ if (!isPlainObject(runAs)) {
300948
+ report(node, "runAs must be 'system', 'session', or { resource, record }");
300949
+ return null;
300988
300950
  }
300989
- return modifier(method, evaluate2(receiver, checker, visiting), expression2);
300990
- }
300991
- var base = (kind, extra = {}) => ({
300992
- kind,
300993
- optional: false,
300994
- nullable: false,
300995
- rules: [],
300996
- ...extra
300997
- });
300998
- function builder(method, call, checker, visiting) {
300999
- const args = call.arguments;
301000
- if (SCALAR_KINDS.has(method)) {
301001
- return base(method);
301002
- }
301003
- switch (method) {
301004
- case "select": {
301005
- const options2 = args[0] && unwrap(args[0]);
301006
- if (!options2 || !import_typescript4.default.isArrayLiteralExpression(options2) || options2.elements.length === 0) {
301007
- throw new SchemaError(call, "v.select() needs a literal array of its options.");
301008
- }
301009
- return base("select", { options: options2.elements.map((element) => literal(element)) });
301010
- }
301011
- case "list":
301012
- if (args.length !== 1) {
301013
- throw new SchemaError(call, "v.list() needs the item field.");
301014
- }
301015
- return base("list", { items: evaluate2(args[0], checker, visiting) });
301016
- case "object": {
301017
- const shape = args[0] && unwrap(args[0]);
301018
- if (!shape || !import_typescript4.default.isObjectLiteralExpression(shape)) {
301019
- throw new SchemaError(call, "v.object() needs an object literal of fields.");
301020
- }
301021
- const fields = {};
301022
- for (const property of shape.properties) {
301023
- if (import_typescript4.default.isPropertyAssignment(property) && (import_typescript4.default.isIdentifier(property.name) || import_typescript4.default.isStringLiteral(property.name))) {
301024
- fields[property.name.text] = evaluate2(property.initializer, checker, visiting);
301025
- } else if (import_typescript4.default.isShorthandPropertyAssignment(property)) {
301026
- fields[property.name.text] = evaluate2(property.name, checker, visiting);
301027
- } else {
301028
- throw new SchemaError(
301029
- property,
301030
- `Each field of v.object() must be a named field. ${STATIC_HINT}`
301031
- );
301032
- }
301033
- }
301034
- return base("object", { fields });
301035
- }
301036
- case "record": {
301037
- const type = args[0] ? checker.getTypeAtLocation(args[0]) : void 0;
301038
- if (!type?.isStringLiteral()) {
301039
- throw new SchemaError(
301040
- call,
301041
- "v.record() needs a resource, such as resources.Products from @diagonal/workflow/workspace or Resources.Products.slug from @app/generated/resources in a file-based workspace."
301042
- );
301043
- }
301044
- return base("record", { resource: type.value });
301045
- }
301046
- case "recordReference": {
301047
- const type = args[0] ? checker.getTypeAtLocation(args[0]) : void 0;
301048
- if (!type?.isStringLiteral()) {
301049
- throw new SchemaError(
301050
- call,
301051
- "v.recordReference() needs a resource, such as resources.Products from @diagonal/workflow/workspace or Resources.Products.slug from @app/generated/resources in a file-based workspace."
301052
- );
301053
- }
301054
- return base("recordReference", {
301055
- resource: type.value,
301056
- ...options(call, args[1], ["scope"])
301057
- });
301058
- }
301059
- case "roleReference":
301060
- return base("roleReference");
301061
- case "file":
301062
- return base("file", options(call, args[0], ["accept", "visibility"]));
301063
- case "content": {
301064
- const content = options(call, args[0], ["multiLine", "extensions", "allowedNodes"]);
301065
- return base("content", Object.keys(content).length === 0 ? {} : { content });
301066
- }
301067
- default:
301068
- throw new SchemaError(call.expression, `v.${method}() is not an input field.`);
301069
- }
301070
- }
301071
- function modifier(method, spec, call) {
301072
- const args = call.arguments;
301073
- const number = (index3) => {
301074
- const value = args[index3] === void 0 ? void 0 : literal(args[index3]);
301075
- if (typeof value !== "number") {
301076
- throw new SchemaError(call, `.${method}() needs number literals.`);
301077
- }
301078
- return value;
301079
- };
301080
- const string = () => {
301081
- const value = args[0] === void 0 ? void 0 : literal(args[0]);
301082
- if (typeof value !== "string") {
301083
- throw new SchemaError(call, `.${method}() needs a string literal.`);
301084
- }
301085
- return value;
301086
- };
301087
- const withRule = (rule) => ({ ...spec, rules: [...spec.rules, rule] });
301088
- switch (method) {
301089
- case "optional":
301090
- return { ...spec, optional: true };
301091
- case "nullable":
301092
- return { ...spec, nullable: true };
301093
- case "min":
301094
- case "max":
301095
- case "size":
301096
- return withRule(`${method}:${number(0)}`);
301097
- case "between":
301098
- return withRule(`between:${number(0)},${number(1)}`);
301099
- case "regex": {
301100
- const pattern = args[0] && unwrap(args[0]);
301101
- if (!pattern || pattern.kind !== import_typescript4.default.SyntaxKind.RegularExpressionLiteral) {
301102
- throw new SchemaError(call, ".regex() needs a regular expression literal.");
301103
- }
301104
- return withRule(`regex:${pattern.text}`);
300951
+ for (const key of Object.keys(runAs)) {
300952
+ if (key !== "resource" && key !== "record") {
300953
+ report(node, `runAs has no option "${key}". Use { resource, record }`);
300954
+ return null;
301105
300955
  }
301106
- case "rule":
301107
- return withRule(string());
301108
- case "label":
301109
- return { ...spec, label: string() };
301110
- case "description":
301111
- return { ...spec, description: string() };
301112
- default:
301113
- throw new SchemaError(call.expression, `.${method}() is not an input field modifier.`);
301114
- }
301115
- }
301116
- function options(call, node, keys2) {
301117
- if (node === void 0) {
301118
- return {};
301119
300956
  }
301120
- const value = literalData(node);
301121
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
301122
- throw new SchemaError(
301123
- node,
301124
- `v.${call.expression.name.text}() needs an object literal of options.`
301125
- );
301126
- }
301127
- const unknown = Object.keys(value).find((key) => !keys2.includes(key));
301128
- if (unknown !== void 0) {
301129
- throw new SchemaError(node, `v.${call.expression.name.text}() has no option "${unknown}".`);
301130
- }
301131
- return value;
301132
- }
301133
- function literalData(node) {
301134
- const expression2 = unwrap(node);
301135
- if (expression2.kind === import_typescript4.default.SyntaxKind.TrueKeyword) {
301136
- return true;
301137
- }
301138
- if (expression2.kind === import_typescript4.default.SyntaxKind.FalseKeyword) {
301139
- return false;
301140
- }
301141
- if (import_typescript4.default.isArrayLiteralExpression(expression2)) {
301142
- return expression2.elements.map((element) => literalData(element));
301143
- }
301144
- if (import_typescript4.default.isObjectLiteralExpression(expression2)) {
301145
- const result = {};
301146
- for (const property of expression2.properties) {
301147
- if (!import_typescript4.default.isPropertyAssignment(property) || !(import_typescript4.default.isIdentifier(property.name) || import_typescript4.default.isStringLiteral(property.name))) {
301148
- throw new SchemaError(
301149
- property,
301150
- `Use a named property with a literal value. ${STATIC_HINT}`
301151
- );
301152
- }
301153
- result[property.name.text] = literalData(property.initializer);
301154
- }
301155
- return result;
300957
+ const resource = resolveResource(runAs.resource, node, context, report);
300958
+ if (typeof runAs.record !== "string" || !UUID_PATTERN2.test(runAs.record)) {
300959
+ report(node, '"runAs.record" must be the lowercase UUID of a record');
300960
+ return null;
301156
300961
  }
301157
- return literal(expression2);
300962
+ return resource === null ? null : { mode: "fixed", resource: resource.slug, record_id: runAs.record };
301158
300963
  }
301159
- function literal(node) {
301160
- const expression2 = unwrap(node);
301161
- if (import_typescript4.default.isStringLiteral(expression2) || import_typescript4.default.isNoSubstitutionTemplateLiteral(expression2)) {
301162
- return expression2.text;
301163
- }
301164
- if (import_typescript4.default.isNumericLiteral(expression2)) {
301165
- return Number(expression2.text);
300964
+ function readAuthorizer(authorizer, node, trigger, report) {
300965
+ if (authorizer === void 0 || authorizer === null) {
300966
+ return null;
301166
300967
  }
301167
- if (import_typescript4.default.isPrefixUnaryExpression(expression2) && expression2.operator === import_typescript4.default.SyntaxKind.MinusToken && import_typescript4.default.isNumericLiteral(expression2.operand)) {
301168
- return -Number(expression2.operand.text);
300968
+ if (authorizer !== "authenticated") {
300969
+ report(node, "authorizer must be 'authenticated'");
300970
+ return null;
301169
300971
  }
301170
- throw new SchemaError(expression2, `Use a literal value here. ${STATIC_HINT}`);
301171
- }
301172
-
301173
- // scripts/lib/workflow-script/lib-files.mjs
301174
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301175
- import { readFileSync as readFileSync7 } from "node:fs";
301176
- import { createRequire as createRequire2 } from "node:module";
301177
- import { dirname as dirname5, join as join10 } from "node:path";
301178
- var ROOT_LIB = "lib.es2023.d.ts";
301179
- function libClosure(read, root = ROOT_LIB) {
301180
- const files = {};
301181
- const pending = [root];
301182
- while (pending.length > 0) {
301183
- const name = pending.pop();
301184
- if (Object.hasOwn(files, name)) {
301185
- continue;
301186
- }
301187
- files[name] = read(name);
301188
- for (const match of files[name].matchAll(/<reference lib="([^"]+)"/g)) {
301189
- pending.push(`lib.${match[1].toLowerCase()}.d.ts`);
301190
- }
300972
+ if (trigger !== null && trigger.name !== "request") {
300973
+ report(node, "Only a request workflow can have an authorizer");
300974
+ return null;
301191
300975
  }
301192
- return files;
301193
- }
301194
- function readLibClosure(root = ROOT_LIB) {
301195
- const libDir = dirname5(createRequire2(import.meta.url).resolve("typescript/lib/lib.d.ts"));
301196
- return libClosure((name) => readFileSync7(join10(libDir, name), "utf8"), root);
300976
+ return { requires_authentication: true };
301197
300977
  }
301198
300978
 
301199
- // scripts/lib/workflow-script/lint-rules.mjs
300979
+ // scripts/lib/runtime-build/workflow-tests.mjs
301200
300980
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301201
- var import_typescript6 = __toESM(require_typescript(), 1);
300981
+ var import_typescript2 = __toESM(require_typescript(), 1);
300982
+ import { spawnSync } from "node:child_process";
300983
+ import { mkdirSync, mkdtempSync, realpathSync as realpathSync2, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
300984
+ import { tmpdir } from "node:os";
300985
+ import { dirname as dirname4, join as join9, relative as relative3 } from "node:path";
301202
300986
 
301203
- // scripts/lib/workflow-script/profile-rules.mjs
300987
+ // scripts/lib/runtime-build/script-sdk.mjs
301204
300988
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301205
- var import_typescript5 = __toESM(require_typescript(), 1);
301206
- var PROFILES = {
301207
- workflow: {
301208
- label: "A workflow script",
301209
- imports: ["@diagonal/workflow", "@diagonal/workflow/workspace"],
301210
- specifier: null,
301211
- entry: null
301212
- },
301213
- test: {
301214
- label: "A test script",
301215
- imports: ["@diagonal/workflow", "@diagonal-hq/workflows/test", "@diagonal/workflow/workspace"],
301216
- specifier: "@diagonal-hq/workflows/test",
301217
- entry: "/sdk/profiles/test.ts"
301218
- },
301219
- migration: {
301220
- label: "A migration script",
301221
- imports: ["@diagonal-hq/workflows/migration", "@diagonal/workflow/workspace"],
301222
- specifier: "@diagonal-hq/workflows/migration",
301223
- entry: "/sdk/profiles/migration.ts"
301224
- }
301225
- };
301226
- var PROFILE_SPECIFIERS = new Set(
301227
- Object.values(PROFILES).flatMap(({ specifier }) => specifier === null ? [] : [specifier])
300989
+ import { readFileSync as readFileSync6, readdirSync as readdirSync2, statSync as statSync3 } from "node:fs";
300990
+ import { createRequire } from "node:module";
300991
+ import { dirname as dirname3, join as join8, relative as relative2, resolve as resolve4 } from "node:path";
300992
+ import { fileURLToPath } from "node:url";
300993
+ var SCRIPT_SDK_ROOT = resolve4(
300994
+ dirname3(fileURLToPath(import.meta.url)),
300995
+ "../../../packages/workflows/src"
301228
300996
  );
301229
- var SDK_SPECIFIERS = /* @__PURE__ */ new Set(["@diagonal/workflow", ...PROFILE_SPECIFIERS]);
301230
- function resolveProfile(name) {
301231
- if (name === void 0 || name === null) {
301232
- return "workflow";
301233
- }
301234
- if (typeof name !== "string" || !Object.hasOwn(PROFILES, name)) {
301235
- throw new Error(`Unknown workflow script profile: ${String(name)}`);
301236
- }
301237
- return name;
300997
+ var SDK_RUNTIME_ENTRY_POINTS = {
300998
+ workflow: join8(SCRIPT_SDK_ROOT, "index.ts"),
300999
+ testing: join8(SCRIPT_SDK_ROOT, "testing/index.ts")
301000
+ };
301001
+ function walk(directory) {
301002
+ return readdirSync2(directory).flatMap(
301003
+ (name) => statSync3(join8(directory, name)).isDirectory() ? walk(join8(directory, name)) : [join8(directory, name)]
301004
+ );
301238
301005
  }
301239
- function profileFindings(file2, checker, program3, profile) {
301240
- const { entry, label, specifier } = PROFILES[profile];
301241
- if (entry === null) {
301242
- return [];
301243
- }
301244
- const entryFile = program3.getSourceFile(entry);
301245
- const entrySymbol = entryFile && checker.getSymbolAtLocation(entryFile);
301246
- if (!entrySymbol) {
301247
- throw new Error(`The SDK has no ${entry} module.`);
301248
- }
301249
- const exports = new Map(
301250
- checker.getExportsOfModule(entrySymbol).map((symbol) => [symbol.getName(), symbol])
301006
+ function readSandboxSdkFiles() {
301007
+ return Object.fromEntries(
301008
+ walk(SCRIPT_SDK_ROOT).filter(
301009
+ (file2) => file2.endsWith(".ts") && !file2.includes("/testing/") && !file2.endsWith("/http-transport.ts") && !file2.endsWith("/workspace.generated.ts")
301010
+ ).map((file2) => [`/sdk/${relative2(SCRIPT_SDK_ROOT, file2)}`, readFileSync6(file2, "utf8")])
301251
301011
  );
301252
- const findings = [];
301253
- const forbidden = (node, path) => findings.push({
301254
- node,
301255
- code: "profile-capability",
301256
- message: `${label} cannot use ${path}. Use only the exports of ${specifier}.`
301012
+ }
301013
+ function bundleSdkRuntime(buildSync) {
301014
+ const result = buildSync({
301015
+ entryPoints: SDK_RUNTIME_ENTRY_POINTS,
301016
+ outdir: "/sdk",
301017
+ bundle: true,
301018
+ splitting: true,
301019
+ platform: "node",
301020
+ target: "node24",
301021
+ format: "esm",
301022
+ write: false,
301023
+ logLevel: "silent"
301257
301024
  });
301258
- const exportType = (name) => {
301259
- const symbol = exports.get(name);
301260
- const target = symbol && symbol.flags & import_typescript5.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
301261
- return target && target.flags & import_typescript5.default.SymbolFlags.Value ? checker.getTypeOfSymbolAtLocation(target, entryFile) : null;
301262
- };
301263
- const checkMembers = (identifier4, type, path) => {
301264
- let node = identifier4;
301265
- let current = type;
301266
- let currentPath = path;
301267
- while (current !== null) {
301268
- const parent = node.parent;
301269
- const isMemberAccess = import_typescript5.default.isPropertyAccessExpression(parent) && parent.expression === node || import_typescript5.default.isElementAccessExpression(parent) && parent.expression === node && import_typescript5.default.isStringLiteralLike(parent.argumentExpression);
301270
- if (!isMemberAccess) {
301271
- if (current.getCallSignatures().length === 0 && hasRestrictedMembers(current, currentPath)) {
301272
- forbidden(node, `${currentPath} as a value`);
301273
- }
301274
- return;
301275
- }
301276
- const member = import_typescript5.default.isPropertyAccessExpression(parent) ? parent.name.text : parent.argumentExpression.text;
301277
- const property = current.getProperty(member);
301278
- currentPath = `${currentPath}.${member}`;
301279
- if (!property) {
301280
- forbidden(parent, currentPath);
301281
- return;
301282
- }
301283
- current = checker.getTypeOfSymbolAtLocation(property, entryFile);
301284
- node = parent;
301285
- }
301286
- };
301287
- const hasRestrictedMembers = (profileType, path) => {
301288
- const rootType = rootNamespaceTypes.get(path);
301289
- return rootType !== void 0 && rootType.getProperties().some((property) => !profileType.getProperty(property.getName()));
301290
- };
301291
- const rootNamespaceTypes = /* @__PURE__ */ new Map();
301292
- const rootFile = program3.getSourceFile("/sdk/index.ts");
301293
- const rootSymbol = rootFile && checker.getSymbolAtLocation(rootFile);
301294
- for (const symbol of rootSymbol ? checker.getExportsOfModule(rootSymbol) : []) {
301295
- const target = symbol.flags & import_typescript5.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
301296
- if (target.flags & import_typescript5.default.SymbolFlags.Value) {
301297
- collectNamespaceTypes(
301298
- checker,
301299
- symbol.getName(),
301300
- checker.getTypeOfSymbolAtLocation(target, rootFile),
301301
- rootFile,
301302
- rootNamespaceTypes
301303
- );
301304
- }
301025
+ return Object.fromEntries(
301026
+ result.outputFiles.map((file2) => [relative2("/sdk", file2.path), file2.text])
301027
+ );
301028
+ }
301029
+ var sdkFiles;
301030
+ try {
301031
+ ({ SDK_FILES: sdkFiles } = await Promise.resolve().then(() => (init_sdk_files_generated(), sdk_files_generated_exports)));
301032
+ } catch (error) {
301033
+ if (error?.code !== "ERR_MODULE_NOT_FOUND") {
301034
+ throw error;
301305
301035
  }
301306
- const valueSymbol = (node) => import_typescript5.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
301307
- const references = (binding) => {
301308
- const symbol = checker.getSymbolAtLocation(binding);
301309
- const found2 = [];
301310
- const visit = (node) => {
301311
- if (import_typescript5.default.isIdentifier(node) && node !== binding && valueSymbol(node) === symbol && !import_typescript5.default.isImportSpecifier(node.parent)) {
301312
- found2.push(node);
301313
- }
301314
- import_typescript5.default.forEachChild(node, visit);
301315
- };
301316
- visit(file2);
301317
- return found2;
301318
- };
301319
- const checkNamespace = (binding) => {
301320
- for (const reference of references(binding)) {
301321
- const parent = reference.parent;
301322
- if (!import_typescript5.default.isPropertyAccessExpression(parent) || parent.expression !== reference) {
301323
- forbidden(reference, "the SDK namespace as a value");
301324
- continue;
301325
- }
301326
- const name = parent.name.text;
301327
- if (!exports.has(name)) {
301328
- forbidden(parent, name);
301329
- continue;
301330
- }
301331
- const type = exportType(name);
301332
- if (type !== null) {
301333
- checkMembers(parent, type, name);
301334
- }
301335
- }
301336
- };
301337
- for (const statement2 of file2.statements) {
301338
- if (import_typescript5.default.isImportEqualsDeclaration(statement2) && import_typescript5.default.isExternalModuleReference(statement2.moduleReference) && import_typescript5.default.isStringLiteral(statement2.moduleReference.expression) && SDK_SPECIFIERS.has(statement2.moduleReference.expression.text)) {
301339
- checkNamespace(statement2.name);
301036
+ sdkFiles = readSandboxSdkFiles();
301037
+ }
301038
+ var SCRIPT_SDK_FILES = sdkFiles;
301039
+ var sdkRuntimeFiles = null;
301040
+ function scriptSdkRuntimeFiles() {
301041
+ sdkRuntimeFiles ??= define_globalThis_DIAGONAL_SDK_RUNTIME_default ?? bundleSdkRuntime(createRequire(import.meta.url)("esbuild").buildSync);
301042
+ return sdkRuntimeFiles;
301043
+ }
301044
+
301045
+ // scripts/lib/runtime-build/workflow-tests.mjs
301046
+ var WORKFLOW_TEST_STAGE = "workflow test";
301047
+ var WORKFLOW_TEST_SUFFIX = ".test.ts";
301048
+ var TEST_TIMEOUT_MS = 1e4;
301049
+ var RUN_TIMEOUT_MS = 6e4;
301050
+ var RESULT_PREFIX = "\0diagonal-test ";
301051
+ var SDK_MODULES = {
301052
+ "@diagonal/workflow": "sdk/workflow.js",
301053
+ "@diagonal/workflow/testing": "sdk/testing.js",
301054
+ "@diagonal/workflow/workspace": "sdk/workspace.js",
301055
+ [AUTHORING_MODULE]: "sdk/runtime.js"
301056
+ };
301057
+ var NODE_TEST_MODULES = /* @__PURE__ */ new Set(["node:test", "node:assert", "node:assert/strict"]);
301058
+ var TEST_MODULE_EXTERNALS = /* @__PURE__ */ new Set([...Object.keys(SDK_MODULES), ...NODE_TEST_MODULES]);
301059
+ var RELATIVE_WORKFLOW = /^\.\/([^/]+?)(?:\.ts|\.js)?$/;
301060
+ var REPORTER_SOURCE = `const PREFIX = ${JSON.stringify(RESULT_PREFIX)};
301061
+ export default async function* reporter(source) {
301062
+ const names = [];
301063
+ for await (const event of source) {
301064
+ const data = event.data;
301065
+ if (event.type === 'test:start') {
301066
+ names.length = data.nesting;
301067
+ names.push(data.name);
301340
301068
  continue;
301341
301069
  }
301342
- if (!import_typescript5.default.isImportDeclaration(statement2) || !import_typescript5.default.isStringLiteral(statement2.moduleSpecifier) || !SDK_SPECIFIERS.has(statement2.moduleSpecifier.text) || !statement2.importClause) {
301070
+ if (event.type !== 'test:pass' && event.type !== 'test:fail') {
301343
301071
  continue;
301344
301072
  }
301345
- const clause = statement2.importClause;
301346
- if (clause.name) {
301347
- forbidden(clause.name, "a default import of the SDK");
301348
- }
301349
- const bindings = clause.namedBindings;
301350
- if (bindings && import_typescript5.default.isNamespaceImport(bindings)) {
301351
- checkNamespace(bindings.name);
301073
+ const error = data.details?.error;
301074
+ if (data.details?.type === 'suite' && (event.type === 'test:pass' || error?.failureType === 'subtestsFailed')) {
301352
301075
  continue;
301353
301076
  }
301354
- for (const element of bindings && import_typescript5.default.isNamedImports(bindings) ? bindings.elements : []) {
301355
- const name = (element.propertyName ?? element.name).text;
301356
- if (!exports.has(name)) {
301357
- forbidden(element, name);
301358
- continue;
301359
- }
301360
- const type = exportType(name);
301361
- if (type === null || element.isTypeOnly || clause.isTypeOnly) {
301362
- continue;
301363
- }
301364
- for (const reference of references(element.name)) {
301365
- checkMembers(reference, type, name);
301366
- }
301367
- }
301077
+ const path = [...names.slice(0, data.nesting), data.name].join(' > ');
301078
+ const cause = error?.cause ?? error;
301079
+ yield PREFIX + JSON.stringify({
301080
+ file: data.file ?? null,
301081
+ name: path,
301082
+ leaf: data.name,
301083
+ ok: event.type === 'test:pass',
301084
+ message: event.type === 'test:pass' ? null : String(cause?.message ?? cause ?? 'The test failed').trim()
301085
+ }) + '\\n';
301368
301086
  }
301369
- return findings;
301370
301087
  }
301371
- function collectNamespaceTypes(checker, path, type, location, into) {
301372
- if (type.getCallSignatures().length > 0 || !(type.flags & import_typescript5.default.TypeFlags.Object)) {
301373
- return;
301088
+ `;
301089
+ function moduleSpecifierNodes(ast) {
301090
+ return ast.program.body.filter(
301091
+ (statement2) => (statement2.type === "ImportDeclaration" || statement2.type === "ExportNamedDeclaration" || statement2.type === "ExportAllDeclaration") && statement2.source
301092
+ ).map((statement2) => statement2.source);
301093
+ }
301094
+ function transpile(path, source, ast, resolveSpecifier) {
301095
+ let rewritten = source;
301096
+ for (const node of moduleSpecifierNodes(ast).toSorted(
301097
+ (left, right) => right.start - left.start
301098
+ )) {
301099
+ const target = resolveSpecifier(node.value);
301100
+ if (target !== null) {
301101
+ rewritten = `${rewritten.slice(0, node.start)}${JSON.stringify(target)}${rewritten.slice(node.end)}`;
301102
+ }
301374
301103
  }
301375
- into.set(path, type);
301376
- for (const property of type.getProperties()) {
301377
- collectNamespaceTypes(
301378
- checker,
301379
- `${path}.${property.getName()}`,
301380
- checker.getTypeOfSymbolAtLocation(property, location),
301381
- location,
301382
- into
301383
- );
301104
+ return import_typescript2.default.transpileModule(rewritten, {
301105
+ fileName: path,
301106
+ compilerOptions: {
301107
+ target: import_typescript2.default.ScriptTarget.ES2023,
301108
+ module: import_typescript2.default.ModuleKind.ESNext,
301109
+ sourceMap: false
301110
+ }
301111
+ }).outputText;
301112
+ }
301113
+ function sdkSpecifier(fromDirectory) {
301114
+ return (specifier) => Object.hasOwn(SDK_MODULES, specifier) ? `${fromDirectory}${SDK_MODULES[specifier]}` : null;
301115
+ }
301116
+ function testCallNode(ast, name) {
301117
+ const pending = [ast.program];
301118
+ while (pending.length > 0) {
301119
+ const node = pending.pop();
301120
+ const [first] = node.type === "CallExpression" ? node.arguments : [];
301121
+ if (first !== void 0 && (first.type === "StringLiteral" || first.type === "TemplateLiteral" && first.expressions.length === 0) && (first.type === "StringLiteral" ? first.value : first.quasis[0].value.cooked) === name) {
301122
+ return node;
301123
+ }
301124
+ pending.push(...childNodes(node));
301384
301125
  }
301126
+ return null;
301385
301127
  }
301386
-
301387
- // scripts/lib/workflow-script/lint-rules.mjs
301388
- var UNSUPPORTED_GLOBALS = {
301389
- Intl: "The sandbox has no Intl. Use date.format, time.format, money.format, or number.format.",
301390
- crypto: "The sandbox has no crypto. Use text.hash, text.randomUuid, or security.randomPassword.",
301391
- setTimeout: "The sandbox has no timers.",
301392
- setInterval: "The sandbox has no timers.",
301393
- fetch: "The sandbox has no network. Use http.request.",
301394
- process: "The sandbox has no process.",
301395
- require: "Use an import from @diagonal/workflow."
301396
- };
301397
- var FLOATING_MESSAGE = "Await this call, return it, or assign it. A call that is not awaited can fail without stopping the workflow.";
301398
- var MAIL_TEMPLATE_CAPABILITIES = {
301399
- MailSendInput: "mail.send",
301400
- NotificationSendInput: "notification.send"
301401
- };
301402
- var MAIL_REFERENCES_KEY = "$references";
301403
- var composedMailTextMessage = (capability, field2) => `Do not write values into the ${capability} ${field2}. The email evaluates this text as Liquid, so a value such as "{{ workspace.name }}" renders. Put each value in layoutData.${MAIL_REFERENCES_KEY} and write {{ ref.<key> }} in the text.`;
301404
- function staticPropertyName(property) {
301405
- if (!import_typescript6.default.isPropertyAssignment(property) && !import_typescript6.default.isShorthandPropertyAssignment(property)) {
301406
- return null;
301128
+ function importDiagnostics(test, workflowNames, workspaceRoot) {
301129
+ const diagnostics = [];
301130
+ for (const node of moduleSpecifierNodes(test.ast)) {
301131
+ const specifier = node.value;
301132
+ const relative5 = RELATIVE_WORKFLOW.exec(specifier);
301133
+ if (NODE_TEST_MODULES.has(specifier) || Object.hasOwn(SDK_MODULES, specifier) || relative5 !== null && workflowNames.has(relative5[1]) || isAppSpecifier(specifier) && workspaceRoot !== null && resolveAppSpecifier(workspaceRoot, specifier) !== null) {
301134
+ continue;
301135
+ }
301136
+ diagnostics.push(
301137
+ diagnosticAt(
301138
+ test.path,
301139
+ node,
301140
+ `A workflow test can import only node:test, node:assert, @diagonal/workflow, @diagonal/workflow/testing, @diagonal/workflow/workspace, the workflows in workflows/, and workspace files by @app/. "${specifier}" is not one of them`,
301141
+ { stage: WORKFLOW_TEST_STAGE }
301142
+ )
301143
+ );
301407
301144
  }
301408
- return propertyNameText(property.name);
301145
+ return diagnostics;
301409
301146
  }
301410
- function floatingPromiseCalls(expression2, holdsPromise) {
301411
- const node = import_typescript6.default.skipParentheses(expression2);
301412
- if (import_typescript6.default.isConditionalExpression(node)) {
301413
- return [
301414
- ...floatingPromiseCalls(node.whenTrue, holdsPromise),
301415
- ...floatingPromiseCalls(node.whenFalse, holdsPromise)
301416
- ];
301417
- }
301418
- if (import_typescript6.default.isBinaryExpression(node) && [
301419
- import_typescript6.default.SyntaxKind.AmpersandAmpersandToken,
301420
- import_typescript6.default.SyntaxKind.BarBarToken,
301421
- import_typescript6.default.SyntaxKind.QuestionQuestionToken,
301422
- import_typescript6.default.SyntaxKind.CommaToken
301423
- ].includes(node.operatorToken.kind)) {
301424
- return [
301425
- ...floatingPromiseCalls(node.left, holdsPromise),
301426
- ...floatingPromiseCalls(node.right, holdsPromise)
301427
- ];
301428
- }
301429
- return (import_typescript6.default.isCallExpression(node) || import_typescript6.default.isArrayLiteralExpression(node)) && holdsPromise(node) ? [node] : [];
301147
+ function sandboxPath(path) {
301148
+ return path.replace(/\.(ts|tsx|js|jsx)$/, ".js");
301430
301149
  }
301431
- function returnsPromise(fn, checker) {
301432
- const signature = checker.getSignatureFromDeclaration(fn);
301433
- return signature !== void 0 && checker.getReturnTypeOfSignature(signature).getSymbol()?.getName() === "Promise";
301150
+ function sandboxPrefix(path) {
301151
+ return "../".repeat(path.split("/").length - 1) || "./";
301434
301152
  }
301435
- function contextuallyReturnsVoid(fn, checker) {
301436
- const signatures = checker.getContextualType(fn)?.getCallSignatures() ?? [];
301437
- return signatures.length > 0 && signatures.every(
301438
- (signature) => (checker.getReturnTypeOfSignature(signature).flags & import_typescript6.default.TypeFlags.Void) !== 0
301439
- );
301153
+ function relativeSandboxPath(from, target) {
301154
+ const path = relative3(dirname4(from), sandboxPath(target));
301155
+ return path.startsWith(".") ? path : `./${path}`;
301440
301156
  }
301441
- function isMemberName(node) {
301442
- const parent = node.parent;
301443
- if (import_typescript6.default.isPropertyAccessExpression(parent) || import_typescript6.default.isQualifiedName(parent)) {
301444
- return parent.name === node || parent.right === node;
301445
- }
301446
- if (import_typescript6.default.isBindingElement(parent) || import_typescript6.default.isImportSpecifier(parent) || import_typescript6.default.isExportSpecifier(parent)) {
301447
- return parent.propertyName === node;
301448
- }
301449
- return (import_typescript6.default.isPropertyAssignment(parent) || import_typescript6.default.isPropertyDeclaration(parent) || import_typescript6.default.isPropertySignature(parent) || import_typescript6.default.isMethodDeclaration(parent) || import_typescript6.default.isMethodSignature(parent) || import_typescript6.default.isGetAccessorDeclaration(parent) || import_typescript6.default.isSetAccessorDeclaration(parent) || import_typescript6.default.isEnumMember(parent)) && parent.name === node;
301157
+ function writeFile(root, path, content) {
301158
+ mkdirSync(dirname4(join9(root, path)), { recursive: true });
301159
+ writeFileSync3(join9(root, path), content);
301450
301160
  }
301451
- function lint2(file2, checker, { allowAppImports = false, profile = "workflow" } = {}) {
301452
- const findings = [];
301453
- const { imports: allowedImports, label } = PROFILES[profile];
301454
- const allowedImportList = new Intl.ListFormat("en", { type: "disjunction" }).format(
301455
- allowedImports
301161
+ function parseResults(stdout) {
301162
+ return stdout.split("\n").filter((line) => line.startsWith(RESULT_PREFIX)).map((line) => JSON.parse(line.slice(RESULT_PREFIX.length)));
301163
+ }
301164
+ function runWorkflowTests({
301165
+ tests,
301166
+ workflows,
301167
+ root: workspaceRoot = null,
301168
+ appModules = /* @__PURE__ */ new Map()
301169
+ }) {
301170
+ const diagnostics = [];
301171
+ const workflowNames = new Map(
301172
+ workflows.map((workflow) => [workflow.path.slice("workflows/".length, -".ts".length), workflow])
301456
301173
  );
301457
- let defaultExport = null;
301458
- const isPromiseType = (type) => type.getSymbol()?.getName() === "Promise";
301459
- const holdsPromise = (node) => {
301460
- const type = checker.getTypeAtLocation(node);
301461
- if (checker.isArrayType(type) || checker.isTupleType(type)) {
301462
- return checker.getTypeArguments(type).some(isPromiseType);
301463
- }
301464
- return isPromiseType(type);
301465
- };
301466
- const isDeclaredInScript = (symbol) => symbol?.declarations?.some((declaration) => declaration.getSourceFile() === file2) ?? false;
301467
- const mailTemplateCapability = (call) => {
301468
- const [parameter] = checker.getResolvedSignature(call)?.getParameters() ?? [];
301469
- const inputType = parameter && checker.getTypeOfSymbolAtLocation(parameter, call).getSymbol();
301470
- const fromSdk = inputType?.declarations?.some(
301471
- (declaration) => declaration.getSourceFile().fileName.startsWith("/sdk/")
301472
- ) ?? false;
301473
- return fromSdk && Object.hasOwn(MAIL_TEMPLATE_CAPABILITIES, inputType.getName()) ? MAIL_TEMPLATE_CAPABILITIES[inputType.getName()] : null;
301474
- };
301475
- const constValue = (expression2) => {
301476
- const node = unwrap(expression2);
301477
- if (!import_typescript6.default.isIdentifier(node)) {
301478
- return node;
301174
+ const runnable = [];
301175
+ for (const test of tests) {
301176
+ const workflowPath = `${test.path.slice(0, -WORKFLOW_TEST_SUFFIX.length)}.ts`;
301177
+ if (!workflowNames.has(workflowPath.slice("workflows/".length, -".ts".length))) {
301178
+ diagnostics.push(
301179
+ diagnosticAt(
301180
+ test.path,
301181
+ null,
301182
+ `The test file has no workflow. Add ${workflowPath} or remove the test file`,
301183
+ { stage: WORKFLOW_TEST_STAGE }
301184
+ )
301185
+ );
301186
+ continue;
301479
301187
  }
301480
- const symbol = import_typescript6.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
301481
- const declaration = symbol?.valueDeclaration;
301482
- return declaration !== void 0 && import_typescript6.default.isVariableDeclaration(declaration) && declaration.initializer !== void 0 && declaration.getSourceFile() === file2 && (import_typescript6.default.getCombinedNodeFlags(declaration) & import_typescript6.default.NodeFlags.Const) !== 0 ? unwrap(declaration.initializer) : node;
301483
- };
301484
- const hasLiteralType = (node) => {
301485
- const type = checker.getTypeAtLocation(node);
301486
- return (type.isUnion() ? type.types : [type]).every(
301487
- (member) => member.isLiteral() || (member.flags & import_typescript6.default.TypeFlags.BooleanLiteral) !== 0
301488
- );
301489
- };
301490
- const isConstantText = (expression2, followed = /* @__PURE__ */ new Set()) => {
301491
- const node = unwrap(expression2);
301492
- if (import_typescript6.default.isTemplateExpression(node)) {
301493
- return node.templateSpans.every((span) => isConstantText(span.expression, followed));
301188
+ const imports = importDiagnostics(test, workflowNames, workspaceRoot);
301189
+ diagnostics.push(...imports);
301190
+ if (imports.length === 0) {
301191
+ runnable.push({ ...test, workflow: workflowPath });
301494
301192
  }
301495
- if (import_typescript6.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript6.default.SyntaxKind.PlusToken) {
301496
- return isConstantText(node.left, followed) && isConstantText(node.right, followed);
301193
+ }
301194
+ if (runnable.length === 0) {
301195
+ return { workflowTests: [], diagnostics };
301196
+ }
301197
+ const modules = new Map(appModules);
301198
+ for (const test of runnable) {
301199
+ for (const [path, module] of appModuleClosure(
301200
+ workspaceRoot,
301201
+ workspaceRoot === null ? [] : appImportsOf(workspaceRoot, test.path, test.ast),
301202
+ TEST_MODULE_EXTERNALS
301203
+ )) {
301204
+ modules.set(path, module);
301497
301205
  }
301498
- if (hasLiteralType(node)) {
301499
- return true;
301206
+ }
301207
+ const root = realpathSync2(mkdtempSync(join9(tmpdir(), "diagonal-workflow-tests-")));
301208
+ try {
301209
+ writeFile(root, "package.json", '{"type":"module"}\n');
301210
+ writeFile(root, "reporter.mjs", REPORTER_SOURCE);
301211
+ for (const [path, content] of Object.entries(scriptSdkRuntimeFiles())) {
301212
+ writeFile(root, `sdk/${path}`, content);
301500
301213
  }
301501
- const initializer = import_typescript6.default.isIdentifier(node) ? constValue(node) : node;
301502
- if (initializer === node || followed.has(initializer)) {
301503
- return false;
301214
+ writeFile(root, "sdk/workspace.js", "export {};\n");
301215
+ writeFile(root, "sdk/runtime.js", AUTHORING_HELPERS_MODULE);
301216
+ for (const [path, module] of modules) {
301217
+ const resolveSdk = sdkSpecifier(sandboxPrefix(path));
301218
+ writeFile(
301219
+ root,
301220
+ sandboxPath(path),
301221
+ transpile(
301222
+ path,
301223
+ module.source,
301224
+ parseSource(module.source, { jsx: path.endsWith("x") }),
301225
+ (specifier) => module.requires[specifier] === void 0 ? resolveSdk(specifier) : relativeSandboxPath(path, module.requires[specifier])
301226
+ )
301227
+ );
301504
301228
  }
301505
- return isConstantText(initializer, /* @__PURE__ */ new Set([...followed, initializer]));
301506
- };
301507
- const composedMailText = (expression2) => {
301508
- const node = unwrap(expression2);
301509
- if (import_typescript6.default.isConditionalExpression(node)) {
301510
- return composedMailText(node.whenTrue) ?? composedMailText(node.whenFalse);
301229
+ for (const workflow of workflows) {
301230
+ writeFile(
301231
+ root,
301232
+ workflow.path.replace(/\.ts$/, ".js"),
301233
+ transpile(workflow.path, workflow.source, workflow.ast, (specifier) => {
301234
+ const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
301235
+ return target === null ? sdkSpecifier("../")(specifier) : relativeSandboxPath(workflow.path, target);
301236
+ })
301237
+ );
301511
301238
  }
301512
- if (import_typescript6.default.isBinaryExpression(node) && [import_typescript6.default.SyntaxKind.BarBarToken, import_typescript6.default.SyntaxKind.QuestionQuestionToken].includes(
301513
- node.operatorToken.kind
301514
- )) {
301515
- return composedMailText(node.left) ?? composedMailText(node.right);
301239
+ for (const test of runnable) {
301240
+ const resolveSdk = sdkSpecifier("../");
301241
+ writeFile(
301242
+ root,
301243
+ test.path.replace(/\.ts$/, ".js"),
301244
+ transpile(test.path, test.source, test.ast, (specifier) => {
301245
+ const relative5 = RELATIVE_WORKFLOW.exec(specifier);
301246
+ const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
301247
+ if (target !== null) {
301248
+ return relativeSandboxPath(test.path, target);
301249
+ }
301250
+ return relative5 !== null ? `./${relative5[1]}.js` : resolveSdk(specifier);
301251
+ })
301252
+ );
301516
301253
  }
301517
- const isConcatenation = import_typescript6.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript6.default.SyntaxKind.PlusToken && (checker.getTypeAtLocation(node).flags & import_typescript6.default.TypeFlags.StringLike) !== 0;
301518
- return (import_typescript6.default.isTemplateExpression(node) || isConcatenation) && !isConstantText(node) ? node : null;
301519
- };
301520
- const checkMailTemplateCall = (call) => {
301521
- const capability = call.arguments.length > 0 ? mailTemplateCapability(call) : null;
301522
- const input = capability === null ? null : constValue(call.arguments[0]);
301523
- if (input === null || !import_typescript6.default.isObjectLiteralExpression(input)) {
301524
- return;
301254
+ const run = spawnSync(
301255
+ process.execPath,
301256
+ [
301257
+ "--permission",
301258
+ `--allow-fs-read=${root}`,
301259
+ "--test",
301260
+ "--test-isolation=none",
301261
+ `--test-timeout=${TEST_TIMEOUT_MS}`,
301262
+ "--test-reporter=./reporter.mjs",
301263
+ ...runnable.map((test) => test.path.replace(/\.ts$/, ".js"))
301264
+ ],
301265
+ {
301266
+ cwd: root,
301267
+ env: { TZ: "UTC" },
301268
+ encoding: "utf8",
301269
+ timeout: RUN_TIMEOUT_MS,
301270
+ maxBuffer: 16 * 1024 * 1024
301271
+ }
301272
+ );
301273
+ if (run.error !== void 0 && run.error.code !== "ETIMEDOUT") {
301274
+ throw run.error;
301525
301275
  }
301526
- const valueOf = (property) => import_typescript6.default.isShorthandPropertyAssignment(property) ? property.name : property.initializer;
301527
- const check2 = (value, field2) => {
301528
- const composed = composedMailText(constValue(value));
301529
- if (composed !== null) {
301530
- findings.push({
301531
- node: composed,
301532
- code: "no-composed-mail-text",
301533
- message: composedMailTextMessage(capability, field2)
301534
- });
301535
- }
301536
- };
301537
- for (const property of input.properties) {
301538
- const name = staticPropertyName(property);
301539
- if (name === "subject") {
301540
- check2(valueOf(property), "subject");
301541
- }
301542
- const layoutData = name === "layoutData" ? constValue(valueOf(property)) : null;
301543
- if (layoutData === null || !import_typescript6.default.isObjectLiteralExpression(layoutData)) {
301544
- continue;
301545
- }
301546
- for (const slot of layoutData.properties) {
301547
- const slotName = staticPropertyName(slot);
301548
- if (slotName !== null && slotName !== MAIL_REFERENCES_KEY) {
301549
- check2(valueOf(slot), `layoutData.${slotName}`);
301276
+ const results = parseResults(run.stdout ?? "");
301277
+ const timedOut = run.error?.code === "ETIMEDOUT" || run.signal !== null;
301278
+ const workflowTests = runnable.map((test) => {
301279
+ const file2 = join9(root, test.path.replace(/\.ts$/, ".js"));
301280
+ const own = results.filter((result) => result.file === file2);
301281
+ for (const result of own) {
301282
+ if (!result.ok) {
301283
+ const node = testCallNode(test.ast, result.leaf);
301284
+ diagnostics.push(
301285
+ diagnosticAt(test.path, node, `Test "${result.name}" failed: ${result.message}`, {
301286
+ stage: WORKFLOW_TEST_STAGE
301287
+ })
301288
+ );
301550
301289
  }
301551
301290
  }
301552
- }
301553
- };
301554
- const checkModuleSpecifier = (node, specifier) => {
301555
- if (specifier && import_typescript6.default.isStringLiteral(specifier) && !allowedImports.includes(specifier.text) && !(allowAppImports && specifier.text.startsWith("@app/"))) {
301556
- findings.push({
301557
- node,
301558
- code: "allowed-imports",
301559
- message: profile === "workflow" ? `Import only @diagonal/workflow or @diagonal/workflow/workspace, not ${specifier.text}.` : `${label} imports only ${allowedImportList}, not ${specifier.text}.`
301560
- });
301561
- }
301562
- };
301563
- const visit = (node) => {
301564
- if (import_typescript6.default.isImportDeclaration(node) || import_typescript6.default.isExportDeclaration(node)) {
301565
- checkModuleSpecifier(node, node.moduleSpecifier);
301566
- }
301567
- if (import_typescript6.default.isImportEqualsDeclaration(node) && import_typescript6.default.isExternalModuleReference(node.moduleReference)) {
301568
- checkModuleSpecifier(node, node.moduleReference.expression);
301569
- }
301570
- if (import_typescript6.default.isCallExpression(node) && node.expression.kind === import_typescript6.default.SyntaxKind.ImportKeyword) {
301571
- findings.push({ node, code: "allowed-imports", message: "Dynamic import is not supported." });
301572
- }
301573
- if (import_typescript6.default.isCallExpression(node) && node.expression.kind !== import_typescript6.default.SyntaxKind.ImportKeyword) {
301574
- checkMailTemplateCall(node);
301575
- }
301576
- if (import_typescript6.default.isExpressionStatement(node)) {
301577
- for (const call of floatingPromiseCalls(node.expression, holdsPromise)) {
301578
- findings.push({ node: call, code: "no-floating-capability", message: FLOATING_MESSAGE });
301579
- }
301580
- }
301581
- if ((import_typescript6.default.isArrowFunction(node) || import_typescript6.default.isFunctionExpression(node)) && import_typescript6.default.isCallExpression(node.parent) && node.parent.arguments.includes(node) && returnsPromise(node, checker) && contextuallyReturnsVoid(node, checker)) {
301582
- findings.push({ node, code: "no-floating-capability", message: FLOATING_MESSAGE });
301583
- }
301584
- if (import_typescript6.default.isIdentifier(node) && Object.hasOwn(UNSUPPORTED_GLOBALS, node.text)) {
301585
- const isGlobalThisMember = import_typescript6.default.isPropertyAccessExpression(node.parent) && node.parent.name === node && import_typescript6.default.isIdentifier(node.parent.expression) && node.parent.expression.text === "globalThis";
301586
- const symbol = import_typescript6.default.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
301587
- const isGlobalReference = !isMemberName(node) && !isDeclaredInScript(symbol);
301588
- if (isGlobalThisMember || isGlobalReference) {
301589
- findings.push({
301590
- node,
301591
- code: "no-unsupported-global",
301592
- message: UNSUPPORTED_GLOBALS[node.text]
301593
- });
301291
+ if (timedOut) {
301292
+ diagnostics.push(
301293
+ diagnostic(
301294
+ test.path,
301295
+ 1,
301296
+ 1,
301297
+ `The workflow tests did not finish in ${RUN_TIMEOUT_MS / 1e3} seconds`,
301298
+ { stage: WORKFLOW_TEST_STAGE }
301299
+ )
301300
+ );
301301
+ } else if (own.length === 0 && run.status !== 0) {
301302
+ diagnostics.push(
301303
+ diagnostic(
301304
+ test.path,
301305
+ 1,
301306
+ 1,
301307
+ `The workflow tests did not run: ${(run.stderr ?? "").trim().split("\n")[0] || `exit code ${run.status}`}`,
301308
+ { stage: WORKFLOW_TEST_STAGE }
301309
+ )
301310
+ );
301594
301311
  }
301595
- }
301596
- if (import_typescript6.default.isExportAssignment(node) && !node.isExportEquals) {
301597
- defaultExport = node.expression;
301598
- }
301599
- import_typescript6.default.forEachChild(node, visit);
301600
- };
301601
- for (const directive2 of file2.libReferenceDirectives) {
301602
- findings.push({
301603
- node: file2,
301604
- position: directive2.pos,
301605
- code: "no-lib-reference",
301606
- message: "Remove this lib reference. Workflow scripts run on ES2023 in the sandbox."
301607
- });
301608
- }
301609
- visit(file2);
301610
- if (!isSdkDefineWorkflowCall(defaultExport, checker)) {
301611
- findings.push({
301612
- node: defaultExport ?? file2,
301613
- code: "default-workflow-export",
301614
- message: "Export the workflow as `export default defineWorkflow(async (input, ctx) => { ... })`."
301312
+ return {
301313
+ path: test.path,
301314
+ workflow: test.workflow,
301315
+ passed: own.filter((result) => result.ok).length,
301316
+ failed: own.filter((result) => !result.ok).length,
301317
+ results: own.map((result) => ({
301318
+ name: result.name,
301319
+ ok: result.ok,
301320
+ message: result.message
301321
+ }))
301322
+ };
301615
301323
  });
301324
+ return { workflowTests, diagnostics };
301325
+ } finally {
301326
+ rmSync(root, { recursive: true, force: true });
301616
301327
  }
301617
- return findings;
301618
- }
301619
- function isSdkDefineWorkflowCall(expression2, checker) {
301620
- if (expression2 === null || !import_typescript6.default.isCallExpression(expression2) || !import_typescript6.default.isIdentifier(expression2.expression)) {
301621
- return false;
301622
- }
301623
- let symbol = checker.getSymbolAtLocation(expression2.expression);
301624
- if (symbol && symbol.flags & import_typescript6.default.SymbolFlags.Alias) {
301625
- symbol = checker.getAliasedSymbol(symbol);
301626
- }
301627
- return symbol?.getName() === "defineWorkflow" && (symbol.declarations?.some(
301628
- (declaration) => declaration.getSourceFile().fileName.startsWith("/sdk/")
301629
- ) ?? false);
301630
301328
  }
301631
301329
 
301330
+ // scripts/lib/runtime-build/workflows.mjs
301331
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301332
+
301632
301333
  // scripts/lib/workflow-script/compile.mjs
301633
- var SCRIPT = "/workflow.ts";
301634
- var INPUT_VALIDATOR_CHECK = "/input-validator.check.ts";
301635
- var INPUT_VALIDATOR_CHECK_SOURCE = `import type { InputValidator, WorkflowDefinition } from '@diagonal/workflow';
301636
- import * as script from './workflow';
301334
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301335
+ var import_typescript7 = __toESM(require_typescript(), 1);
301637
301336
 
301638
- type Input = typeof script.default extends WorkflowDefinition<infer I, unknown> ? I : never;
301639
- type Exported = typeof script extends { validateInput: infer V } ? V : undefined;
301337
+ // scripts/lib/workflow-script/ast.mjs
301338
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301339
+ var import_typescript3 = __toESM(require_typescript(), 1);
301340
+ function unwrap2(node) {
301341
+ let current = node;
301342
+ while (import_typescript3.default.isParenthesizedExpression(current) || import_typescript3.default.isAsExpression(current) || import_typescript3.default.isSatisfiesExpression(current)) {
301343
+ current = current.expression;
301344
+ }
301345
+ return current;
301346
+ }
301347
+ function propertyNameText(name) {
301348
+ return import_typescript3.default.isIdentifier(name) || import_typescript3.default.isStringLiteral(name) ? name.text : null;
301349
+ }
301640
301350
 
301641
- declare const validateInput: Exported;
301642
- export const check: InputValidator<Input> | undefined = validateInput;
301643
- `;
301644
- var WORKSPACE = "/sdk/workspace.generated.ts";
301645
- var APP_ROOT = "/app";
301646
- var LIB_DIR = "/lib";
301647
- var OPTIONS = {
301648
- target: import_typescript7.default.ScriptTarget.ES2023,
301649
- lib: [ROOT_LIB],
301650
- module: import_typescript7.default.ModuleKind.CommonJS,
301651
- moduleResolution: import_typescript7.default.ModuleResolutionKind.Bundler,
301652
- strict: true,
301653
- types: [],
301654
- paths: {
301655
- "@diagonal/workflow": ["/sdk/index.ts"],
301656
- "@diagonal/workflow/workspace": [WORKSPACE],
301657
- ...Object.fromEntries(
301658
- Object.values(PROFILES).filter(({ specifier }) => specifier !== null).map(({ specifier, entry }) => [specifier, [entry]])
301659
- )
301351
+ // scripts/lib/workflow-script/input-schema.mjs
301352
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301353
+ var import_typescript4 = __toESM(require_typescript(), 1);
301354
+ var SDK_MODULE = "@diagonal/workflow";
301355
+ var SCALAR_KINDS = /* @__PURE__ */ new Set([
301356
+ "text",
301357
+ "email",
301358
+ "url",
301359
+ "uuid",
301360
+ "phone",
301361
+ "date",
301362
+ "datetime",
301363
+ "time",
301364
+ "timezone",
301365
+ "color",
301366
+ "number",
301367
+ "integer",
301368
+ "money",
301369
+ "boolean"
301370
+ ]);
301371
+ var SchemaError = class extends Error {
301372
+ constructor(node, message) {
301373
+ super(message);
301374
+ this.node = node;
301660
301375
  }
301661
301376
  };
301662
- var libFiles2;
301663
- try {
301664
- const { LIB_FILES: LIB_FILES2 } = await Promise.resolve().then(() => (init_sdk_files_generated(), sdk_files_generated_exports));
301665
- libFiles2 = libClosure((name) => LIB_FILES2[name]);
301666
- } catch {
301667
- libFiles2 = readLibClosure();
301668
- }
301669
- var libSourceFiles = /* @__PURE__ */ new Map();
301670
- var readLibFile = (name) => Object.hasOwn(libFiles2, name) ? libFiles2[name] : void 0;
301671
- function libSourceFile(name, languageVersion) {
301672
- if (!libSourceFiles.has(name)) {
301673
- const text = readLibFile(name);
301674
- libSourceFiles.set(
301675
- name,
301676
- text === void 0 ? void 0 : import_typescript7.default.createSourceFile(`${LIB_DIR}/${name}`, text, languageVersion)
301677
- );
301377
+ function extractInputSchema(file2, checker) {
301378
+ const call = defineWorkflowCall(file2, checker);
301379
+ if (call === null || call.arguments.length < 2) {
301380
+ return { schema: null, findings: [] };
301678
301381
  }
301679
- return libSourceFiles.get(name);
301680
- }
301681
- var libName = (path) => path.startsWith(`${LIB_DIR}/`) ? path.slice(LIB_DIR.length + 1) : null;
301682
- function position(file2, start) {
301683
- if (file2 === void 0 || start === void 0) {
301684
- return { line: 1, column: 1 };
301382
+ try {
301383
+ const schema = evaluate2(call.arguments[0], checker, /* @__PURE__ */ new Set());
301384
+ if (schema.kind !== "object") {
301385
+ throw new SchemaError(call.arguments[0], "The input schema must be v.object({ ... }).");
301386
+ }
301387
+ return { schema, findings: [] };
301388
+ } catch (error) {
301389
+ if (error instanceof SchemaError) {
301390
+ return {
301391
+ schema: null,
301392
+ findings: [{ node: error.node, code: "static-input-schema", message: error.message }]
301393
+ };
301394
+ }
301395
+ throw error;
301685
301396
  }
301686
- const { line, character } = file2.getLineAndCharacterOfPosition(start);
301687
- return { line: line + 1, column: character + 1 };
301688
301397
  }
301689
- function inputValidatorPosition(file2) {
301398
+ function defineWorkflowCall(file2, checker) {
301690
301399
  for (const statement2 of file2.statements) {
301691
- if (import_typescript7.default.isFunctionDeclaration(statement2) && statement2.name?.text === "validateInput") {
301692
- return statement2.name.getStart(file2);
301693
- }
301694
- if (import_typescript7.default.isVariableStatement(statement2)) {
301695
- for (const declaration of statement2.declarationList.declarations) {
301696
- if (import_typescript7.default.isIdentifier(declaration.name) && declaration.name.text === "validateInput") {
301697
- return declaration.name.getStart(file2);
301698
- }
301699
- }
301400
+ if (import_typescript4.default.isExportAssignment(statement2) && import_typescript4.default.isCallExpression(statement2.expression) && import_typescript4.default.isIdentifier(statement2.expression.expression) && sdkImportName(checker, statement2.expression.expression) === "defineWorkflow") {
301401
+ return statement2.expression;
301700
301402
  }
301701
301403
  }
301702
- return void 0;
301404
+ return null;
301703
301405
  }
301704
- function workspaceResourceNames(file2, program3, workspaceDeclarations) {
301705
- const checker = program3.getTypeChecker();
301706
- const imports = /* @__PURE__ */ new Set();
301707
- const namespaces2 = /* @__PURE__ */ new Set();
301708
- const names2 = /* @__PURE__ */ new Set();
301709
- const ids = /* @__PURE__ */ new Map();
301710
- let needsAll = false;
301711
- const key = (node) => node && (import_typescript7.default.isIdentifier(node) || import_typescript7.default.isStringLiteral(node) || import_typescript7.default.isNoSubstitutionTemplateLiteral(node)) ? node.text : null;
301712
- const unparenthesized = (node) => {
301713
- while (node && import_typescript7.default.isParenthesizedExpression(node)) {
301714
- node = node.expression;
301715
- }
301716
- return node;
301717
- };
301718
- const symbol = (node) => {
301719
- if (import_typescript7.default.isShorthandPropertyAssignment(node.parent)) {
301720
- return checker.getShorthandAssignmentValueSymbol(node.parent);
301721
- }
301722
- if (import_typescript7.default.isExportSpecifier(node.parent) && !node.parent.parent.parent.moduleSpecifier) {
301723
- return checker.getExportSpecifierLocalTargetSymbol(node.parent);
301724
- }
301725
- return checker.getSymbolAtLocation(node);
301726
- };
301727
- const isNamespace = (node) => node && import_typescript7.default.isIdentifier(node) && namespaces2.has(symbol(node));
301728
- const member = (node) => {
301729
- if (import_typescript7.default.isPropertyAccessExpression(node)) {
301730
- return node.name.text;
301731
- }
301732
- if (import_typescript7.default.isElementAccessExpression(node)) {
301733
- const argument = unparenthesized(node.argumentExpression);
301734
- return argument && (import_typescript7.default.isStringLiteral(argument) || import_typescript7.default.isNoSubstitutionTemplateLiteral(argument)) ? argument.text : null;
301735
- }
301406
+ function sdkImportName(checker, identifier4) {
301407
+ const declaration = checker.getSymbolAtLocation(identifier4)?.declarations?.[0];
301408
+ if (declaration === void 0 || !import_typescript4.default.isImportSpecifier(declaration)) {
301736
301409
  return null;
301737
- };
301738
- const isMap3 = (node) => import_typescript7.default.isIdentifier(node) && imports.has(symbol(node)) || (import_typescript7.default.isPropertyAccessExpression(node) || import_typescript7.default.isElementAccessExpression(node)) && isNamespace(unparenthesized(node.expression)) && member(node) === "resources";
301739
- for (const statement2 of file2.statements) {
301740
- if (import_typescript7.default.isExportDeclaration(statement2) && !statement2.isTypeOnly && statement2.moduleSpecifier && import_typescript7.default.isStringLiteral(statement2.moduleSpecifier) && statement2.moduleSpecifier.text === "@diagonal/workflow/workspace" && (!statement2.exportClause || import_typescript7.default.isNamespaceExport(statement2.exportClause) || statement2.exportClause.elements.some(
301741
- (element) => !element.isTypeOnly && (element.propertyName ?? element.name).text === "resources"
301742
- ))) {
301743
- return null;
301744
- }
301745
- if (import_typescript7.default.isImportEqualsDeclaration(statement2)) {
301746
- const reference = statement2.moduleReference;
301747
- if (!statement2.isTypeOnly && import_typescript7.default.isExternalModuleReference(reference) && reference.expression && import_typescript7.default.isStringLiteral(reference.expression) && reference.expression.text === "@diagonal/workflow/workspace") {
301748
- namespaces2.add(checker.getSymbolAtLocation(statement2.name));
301749
- }
301750
- continue;
301751
- }
301752
- if (!import_typescript7.default.isImportDeclaration(statement2) || statement2.moduleSpecifier.text !== "@diagonal/workflow/workspace" || statement2.importClause?.isTypeOnly) {
301753
- continue;
301754
- }
301755
- const bindings = statement2.importClause?.namedBindings;
301756
- if (bindings && import_typescript7.default.isNamespaceImport(bindings)) {
301757
- namespaces2.add(checker.getSymbolAtLocation(bindings.name));
301410
+ }
301411
+ const specifier = declaration.parent.parent.parent.moduleSpecifier;
301412
+ return import_typescript4.default.isStringLiteral(specifier) && specifier.text === SDK_MODULE ? (declaration.propertyName ?? declaration.name).text : null;
301413
+ }
301414
+ var STATIC_HINT = "Build the input schema from v.* calls with literal arguments, so the platform can validate input before the script runs.";
301415
+ function evaluate2(node, checker, visiting) {
301416
+ const expression2 = unwrap2(node);
301417
+ if (import_typescript4.default.isIdentifier(expression2)) {
301418
+ const declaration = checker.getSymbolAtLocation(expression2)?.valueDeclaration;
301419
+ if (declaration === void 0 || !import_typescript4.default.isVariableDeclaration(declaration) || declaration.initializer === void 0 || !(import_typescript4.default.getCombinedNodeFlags(declaration) & import_typescript4.default.NodeFlags.Const) || !import_typescript4.default.isSourceFile(declaration.parent.parent.parent)) {
301420
+ throw new SchemaError(
301421
+ expression2,
301422
+ `${expression2.text} is not a top-level const. ${STATIC_HINT}`
301423
+ );
301758
301424
  }
301759
- if (bindings && import_typescript7.default.isNamedImports(bindings)) {
301760
- for (const binding of bindings.elements) {
301761
- if (!binding.isTypeOnly && (binding.propertyName ?? binding.name).text === "resources") {
301762
- imports.add(checker.getSymbolAtLocation(binding.name));
301763
- }
301764
- }
301425
+ if (visiting.has(declaration)) {
301426
+ throw new SchemaError(expression2, `${expression2.text} refers to itself.`);
301765
301427
  }
301428
+ visiting.add(declaration);
301429
+ const spec = evaluate2(declaration.initializer, checker, visiting);
301430
+ visiting.delete(declaration);
301431
+ return spec;
301766
301432
  }
301767
- const workspace = program3.getSourceFile(WORKSPACE) ?? import_typescript7.default.createSourceFile(WORKSPACE, workspaceDeclarations, import_typescript7.default.ScriptTarget.ES2023, true);
301768
- for (const statement2 of workspace.statements) {
301769
- if (!import_typescript7.default.isVariableStatement(statement2)) {
301770
- continue;
301433
+ if (!import_typescript4.default.isCallExpression(expression2) || !import_typescript4.default.isPropertyAccessExpression(expression2.expression)) {
301434
+ throw new SchemaError(expression2, STATIC_HINT);
301435
+ }
301436
+ const method = expression2.expression.name.text;
301437
+ const receiver = unwrap2(expression2.expression.expression);
301438
+ if (import_typescript4.default.isIdentifier(receiver) && sdkImportName(checker, receiver) === "v") {
301439
+ return builder(method, expression2, checker, visiting);
301440
+ }
301441
+ return modifier(method, evaluate2(receiver, checker, visiting), expression2);
301442
+ }
301443
+ var base = (kind, extra = {}) => ({
301444
+ kind,
301445
+ optional: false,
301446
+ nullable: false,
301447
+ rules: [],
301448
+ ...extra
301449
+ });
301450
+ function builder(method, call, checker, visiting) {
301451
+ const args = call.arguments;
301452
+ if (SCALAR_KINDS.has(method)) {
301453
+ return base(method);
301454
+ }
301455
+ switch (method) {
301456
+ case "select": {
301457
+ const options2 = args[0] && unwrap2(args[0]);
301458
+ if (!options2 || !import_typescript4.default.isArrayLiteralExpression(options2) || options2.elements.length === 0) {
301459
+ throw new SchemaError(call, "v.select() needs a literal array of its options.");
301460
+ }
301461
+ return base("select", { options: options2.elements.map((element) => literal(element)) });
301771
301462
  }
301772
- for (const declaration of statement2.declarationList.declarations) {
301773
- if (!import_typescript7.default.isIdentifier(declaration.name) || declaration.name.text !== "resources") {
301774
- continue;
301463
+ case "list":
301464
+ if (args.length !== 1) {
301465
+ throw new SchemaError(call, "v.list() needs the item field.");
301775
301466
  }
301776
- const value = declaration.initializer && unwrap(declaration.initializer);
301777
- if (!value || !import_typescript7.default.isObjectLiteralExpression(value)) {
301778
- continue;
301467
+ return base("list", { items: evaluate2(args[0], checker, visiting) });
301468
+ case "object": {
301469
+ const shape = args[0] && unwrap2(args[0]);
301470
+ if (!shape || !import_typescript4.default.isObjectLiteralExpression(shape)) {
301471
+ throw new SchemaError(call, "v.object() needs an object literal of fields.");
301779
301472
  }
301780
- for (const property of value.properties) {
301781
- if (import_typescript7.default.isPropertyAssignment(property) && import_typescript7.default.isStringLiteral(property.initializer) && key(property.name) !== null) {
301782
- ids.set(property.initializer.text, key(property.name));
301473
+ const fields = {};
301474
+ for (const property of shape.properties) {
301475
+ if (import_typescript4.default.isPropertyAssignment(property) && (import_typescript4.default.isIdentifier(property.name) || import_typescript4.default.isStringLiteral(property.name))) {
301476
+ fields[property.name.text] = evaluate2(property.initializer, checker, visiting);
301477
+ } else if (import_typescript4.default.isShorthandPropertyAssignment(property)) {
301478
+ fields[property.name.text] = evaluate2(property.name, checker, visiting);
301479
+ } else {
301480
+ throw new SchemaError(
301481
+ property,
301482
+ `Each field of v.object() must be a named field. ${STATIC_HINT}`
301483
+ );
301783
301484
  }
301784
301485
  }
301486
+ return base("object", { fields });
301785
301487
  }
301786
- }
301787
- const visit = (node) => {
301788
- if (needsAll || import_typescript7.default.isImportDeclaration(node) || import_typescript7.default.isImportEqualsDeclaration(node) && import_typescript7.default.isExternalModuleReference(node.moduleReference) || import_typescript7.default.isTypeNode(node)) {
301789
- return;
301790
- }
301791
- if ((import_typescript7.default.isStringLiteral(node) || import_typescript7.default.isNoSubstitutionTemplateLiteral(node)) && ids.has(node.text)) {
301792
- names2.add(ids.get(node.text));
301793
- }
301794
- let use = node;
301795
- while (import_typescript7.default.isParenthesizedExpression(use.parent)) {
301796
- use = use.parent;
301488
+ case "record": {
301489
+ const type = args[0] ? checker.getTypeAtLocation(args[0]) : void 0;
301490
+ if (!type?.isStringLiteral()) {
301491
+ throw new SchemaError(
301492
+ call,
301493
+ "v.record() needs a resource, such as resources.Products from @diagonal/workflow/workspace or Resources.Products.slug from @app/generated/resources in a file-based workspace."
301494
+ );
301495
+ }
301496
+ return base("record", { resource: type.value });
301797
301497
  }
301798
- if (isMap3(node)) {
301799
- const parent = use.parent;
301800
- const name = (import_typescript7.default.isPropertyAccessExpression(parent) || import_typescript7.default.isElementAccessExpression(parent)) && parent.expression === use ? member(parent) : null;
301801
- if (name === null) {
301802
- needsAll = true;
301803
- } else {
301804
- names2.add(name);
301498
+ case "recordReference": {
301499
+ const type = args[0] ? checker.getTypeAtLocation(args[0]) : void 0;
301500
+ if (!type?.isStringLiteral()) {
301501
+ throw new SchemaError(
301502
+ call,
301503
+ "v.recordReference() needs a resource, such as resources.Products from @diagonal/workflow/workspace or Resources.Products.slug from @app/generated/resources in a file-based workspace."
301504
+ );
301805
301505
  }
301806
- } else if (isNamespace(node) && !isMap3(use.parent)) {
301807
- needsAll = true;
301506
+ return base("recordReference", {
301507
+ resource: type.value,
301508
+ ...options(call, args[1], ["scope"])
301509
+ });
301808
301510
  }
301809
- if (!needsAll) {
301810
- import_typescript7.default.forEachChild(node, visit);
301511
+ case "roleReference":
301512
+ return base("roleReference");
301513
+ case "file":
301514
+ return base("file", options(call, args[0], ["accept", "visibility"]));
301515
+ case "content": {
301516
+ const content = options(call, args[0], ["multiLine", "extensions", "allowedNodes"]);
301517
+ return base("content", Object.keys(content).length === 0 ? {} : { content });
301811
301518
  }
301812
- };
301813
- import_typescript7.default.forEachChild(file2, visit);
301814
- return needsAll ? null : [...names2].toSorted((left, right) => left.localeCompare(right));
301519
+ default:
301520
+ throw new SchemaError(call.expression, `v.${method}() is not an input field.`);
301521
+ }
301815
301522
  }
301816
- function scriptResourceNames(file2, program3, workspaceDeclarations, appModules = {}) {
301817
- const names2 = /* @__PURE__ */ new Set();
301818
- for (const source of [
301819
- file2,
301820
- ...Object.keys(appModules).map((path) => program3.getSourceFile(`${APP_ROOT}/${path}`))
301821
- ]) {
301822
- if (source === void 0) {
301823
- return null;
301523
+ function modifier(method, spec, call) {
301524
+ const args = call.arguments;
301525
+ const number = (index3) => {
301526
+ const value = args[index3] === void 0 ? void 0 : literal(args[index3]);
301527
+ if (typeof value !== "number") {
301528
+ throw new SchemaError(call, `.${method}() needs number literals.`);
301824
301529
  }
301825
- const used = workspaceResourceNames(source, program3, workspaceDeclarations);
301826
- if (used === null) {
301827
- return null;
301530
+ return value;
301531
+ };
301532
+ const string = () => {
301533
+ const value = args[0] === void 0 ? void 0 : literal(args[0]);
301534
+ if (typeof value !== "string") {
301535
+ throw new SchemaError(call, `.${method}() needs a string literal.`);
301828
301536
  }
301829
- for (const name of used) {
301830
- names2.add(name);
301537
+ return value;
301538
+ };
301539
+ const withRule = (rule) => ({ ...spec, rules: [...spec.rules, rule] });
301540
+ switch (method) {
301541
+ case "optional":
301542
+ return { ...spec, optional: true };
301543
+ case "nullable":
301544
+ return { ...spec, nullable: true };
301545
+ case "min":
301546
+ case "max":
301547
+ case "size":
301548
+ return withRule(`${method}:${number(0)}`);
301549
+ case "between":
301550
+ return withRule(`between:${number(0)},${number(1)}`);
301551
+ case "regex": {
301552
+ const pattern = args[0] && unwrap2(args[0]);
301553
+ if (!pattern || pattern.kind !== import_typescript4.default.SyntaxKind.RegularExpressionLiteral) {
301554
+ throw new SchemaError(call, ".regex() needs a regular expression literal.");
301555
+ }
301556
+ return withRule(`regex:${pattern.text}`);
301831
301557
  }
301832
- }
301833
- return [...names2].toSorted((left, right) => left.localeCompare(right));
301834
- }
301835
- function createScriptProgram({
301836
- source,
301837
- sdkFiles: sdkFiles2,
301838
- workspaceDeclarations,
301839
- appModules = {},
301840
- profile
301841
- }) {
301842
- const entry = PROFILES[resolveProfile(profile)].entry;
301843
- const files = new Map(
301844
- Object.entries({
301845
- ...sdkFiles2,
301846
- [WORKSPACE]: workspaceDeclarations,
301847
- [SCRIPT]: source,
301848
- [INPUT_VALIDATOR_CHECK]: INPUT_VALIDATOR_CHECK_SOURCE,
301849
- ...Object.fromEntries(
301850
- Object.entries(appModules).map(([path, moduleSource]) => [
301851
- `${APP_ROOT}/${path}`,
301852
- moduleSource
301853
- ])
301854
- )
301855
- })
301856
- );
301857
- const host = {
301858
- getSourceFile: (name, languageVersion) => {
301859
- const lib = libName(name);
301860
- if (lib !== null) {
301861
- return libSourceFile(lib, languageVersion);
301862
- }
301863
- return files.has(name) ? import_typescript7.default.createSourceFile(name, files.get(name), languageVersion, true) : void 0;
301864
- },
301865
- getDefaultLibFileName: () => `${LIB_DIR}/${ROOT_LIB}`,
301866
- getDefaultLibLocation: () => LIB_DIR,
301867
- writeFile: () => {
301868
- },
301869
- getCurrentDirectory: () => "/",
301870
- getCanonicalFileName: (name) => name,
301871
- useCaseSensitiveFileNames: () => true,
301872
- getNewLine: () => "\n",
301873
- fileExists: (name) => files.has(name) || libName(name) !== null && readLibFile(libName(name)) !== void 0,
301874
- readFile: (name) => files.get(name) ?? (libName(name) !== null ? readLibFile(libName(name)) : void 0),
301875
- directoryExists: (name) => {
301876
- const prefix2 = name.endsWith("/") ? name : `${name}/`;
301877
- return prefix2 === `${LIB_DIR}/` || [...files.keys()].some((path) => path.startsWith(prefix2));
301878
- },
301879
- getDirectories: () => []
301880
- };
301881
- const program3 = import_typescript7.default.createProgram({
301882
- rootNames: [SCRIPT, INPUT_VALIDATOR_CHECK, WORKSPACE, ...entry === null ? [] : [entry]],
301883
- options: Object.keys(appModules).length === 0 ? OPTIONS : { ...OPTIONS, paths: { ...OPTIONS.paths, "@app/*": [`${APP_ROOT}/*`] } },
301884
- host
301885
- });
301886
- return { program: program3, file: program3.getSourceFile(SCRIPT) };
301558
+ case "rule":
301559
+ return withRule(string());
301560
+ case "label":
301561
+ return { ...spec, label: string() };
301562
+ case "description":
301563
+ return { ...spec, description: string() };
301564
+ default:
301565
+ throw new SchemaError(call.expression, `.${method}() is not an input field modifier.`);
301566
+ }
301887
301567
  }
301888
- function servedProfileImports(context) {
301889
- const { factory } = context;
301890
- const served = (specifier) => import_typescript7.default.isStringLiteral(specifier) && PROFILE_SPECIFIERS.has(specifier.text) ? factory.createStringLiteral("@diagonal/workflow") : specifier;
301891
- return (sourceFile) => factory.updateSourceFile(
301892
- sourceFile,
301893
- sourceFile.statements.map((statement2) => {
301894
- if (import_typescript7.default.isImportDeclaration(statement2)) {
301895
- return factory.updateImportDeclaration(
301896
- statement2,
301897
- statement2.modifiers,
301898
- statement2.importClause,
301899
- served(statement2.moduleSpecifier),
301900
- statement2.attributes
301901
- );
301902
- }
301903
- if (import_typescript7.default.isImportEqualsDeclaration(statement2) && import_typescript7.default.isExternalModuleReference(statement2.moduleReference)) {
301904
- return factory.updateImportEqualsDeclaration(
301905
- statement2,
301906
- statement2.modifiers,
301907
- statement2.isTypeOnly,
301908
- statement2.name,
301909
- factory.updateExternalModuleReference(
301910
- statement2.moduleReference,
301911
- served(statement2.moduleReference.expression)
301912
- )
301913
- );
301914
- }
301915
- if (import_typescript7.default.isExportDeclaration(statement2) && statement2.moduleSpecifier) {
301916
- return factory.updateExportDeclaration(
301917
- statement2,
301918
- statement2.modifiers,
301919
- statement2.isTypeOnly,
301920
- statement2.exportClause,
301921
- served(statement2.moduleSpecifier),
301922
- statement2.attributes
301568
+ function options(call, node, keys2) {
301569
+ if (node === void 0) {
301570
+ return {};
301571
+ }
301572
+ const value = literalData(node);
301573
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
301574
+ throw new SchemaError(
301575
+ node,
301576
+ `v.${call.expression.name.text}() needs an object literal of options.`
301577
+ );
301578
+ }
301579
+ const unknown = Object.keys(value).find((key) => !keys2.includes(key));
301580
+ if (unknown !== void 0) {
301581
+ throw new SchemaError(node, `v.${call.expression.name.text}() has no option "${unknown}".`);
301582
+ }
301583
+ return value;
301584
+ }
301585
+ function literalData(node) {
301586
+ const expression2 = unwrap2(node);
301587
+ if (expression2.kind === import_typescript4.default.SyntaxKind.TrueKeyword) {
301588
+ return true;
301589
+ }
301590
+ if (expression2.kind === import_typescript4.default.SyntaxKind.FalseKeyword) {
301591
+ return false;
301592
+ }
301593
+ if (import_typescript4.default.isArrayLiteralExpression(expression2)) {
301594
+ return expression2.elements.map((element) => literalData(element));
301595
+ }
301596
+ if (import_typescript4.default.isObjectLiteralExpression(expression2)) {
301597
+ const result = {};
301598
+ for (const property of expression2.properties) {
301599
+ if (!import_typescript4.default.isPropertyAssignment(property) || !(import_typescript4.default.isIdentifier(property.name) || import_typescript4.default.isStringLiteral(property.name))) {
301600
+ throw new SchemaError(
301601
+ property,
301602
+ `Use a named property with a literal value. ${STATIC_HINT}`
301923
301603
  );
301924
301604
  }
301925
- return statement2;
301926
- })
301927
- );
301605
+ result[property.name.text] = literalData(property.initializer);
301606
+ }
301607
+ return result;
301608
+ }
301609
+ return literal(expression2);
301928
301610
  }
301929
- function compileWorkflowScript(request2, scriptProgram = createScriptProgram(request2)) {
301930
- let code2 = null;
301931
- const { program: program3, file: file2 } = scriptProgram;
301932
- const diagnostics = [];
301933
- for (const diagnostic2 of import_typescript7.default.getPreEmitDiagnostics(program3, file2)) {
301934
- diagnostics.push({
301935
- severity: "error",
301936
- code: `TS${diagnostic2.code}`,
301937
- message: import_typescript7.default.flattenDiagnosticMessageText(diagnostic2.messageText, "\n"),
301938
- ...position(diagnostic2.file, diagnostic2.start)
301939
- });
301611
+ function literal(node) {
301612
+ const expression2 = unwrap2(node);
301613
+ if (import_typescript4.default.isStringLiteral(expression2) || import_typescript4.default.isNoSubstitutionTemplateLiteral(expression2)) {
301614
+ return expression2.text;
301940
301615
  }
301941
- for (const diagnostic2 of program3.getSemanticDiagnostics(
301942
- program3.getSourceFile(INPUT_VALIDATOR_CHECK)
301943
- )) {
301944
- diagnostics.push({
301945
- severity: "error",
301946
- code: `TS${diagnostic2.code}`,
301947
- message: `validateInput must be (input, ctx) => InputErrors<Input> | void for this workflow's input. ${import_typescript7.default.flattenDiagnosticMessageText(diagnostic2.messageText, "\n")}`,
301948
- ...position(file2, inputValidatorPosition(file2))
301949
- });
301616
+ if (import_typescript4.default.isNumericLiteral(expression2)) {
301617
+ return Number(expression2.text);
301950
301618
  }
301951
- const inputSchema = extractInputSchema(file2, program3.getTypeChecker());
301952
- const allowAppImports = Object.keys(request2.appModules ?? {}).length > 0;
301953
- const profile = resolveProfile(request2.profile);
301954
- for (const finding of [
301955
- ...lint2(file2, program3.getTypeChecker(), { allowAppImports, profile }),
301956
- ...profileFindings(file2, program3.getTypeChecker(), program3, profile),
301957
- ...inputSchema.findings
301958
- ]) {
301959
- diagnostics.push({
301960
- severity: "error",
301961
- code: finding.code,
301962
- message: finding.message,
301963
- ...position(file2, finding.position ?? finding.node.getStart(file2))
301964
- });
301619
+ if (import_typescript4.default.isPrefixUnaryExpression(expression2) && expression2.operator === import_typescript4.default.SyntaxKind.MinusToken && import_typescript4.default.isNumericLiteral(expression2.operand)) {
301620
+ return -Number(expression2.operand.text);
301965
301621
  }
301966
- if (diagnostics.length === 0) {
301967
- program3.emit(
301968
- file2,
301969
- (name, text) => {
301970
- if (name === "/workflow.js") {
301971
- code2 = text;
301972
- }
301973
- },
301974
- void 0,
301975
- false,
301976
- { before: [servedProfileImports] }
301977
- );
301622
+ throw new SchemaError(expression2, `Use a literal value here. ${STATIC_HINT}`);
301623
+ }
301624
+
301625
+ // scripts/lib/workflow-script/lib-files.mjs
301626
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301627
+ import { readFileSync as readFileSync7 } from "node:fs";
301628
+ import { createRequire as createRequire2 } from "node:module";
301629
+ import { dirname as dirname5, join as join10 } from "node:path";
301630
+ var ROOT_LIB = "lib.es2023.d.ts";
301631
+ function libClosure(read, root = ROOT_LIB) {
301632
+ const files = {};
301633
+ const pending = [root];
301634
+ while (pending.length > 0) {
301635
+ const name = pending.pop();
301636
+ if (Object.hasOwn(files, name)) {
301637
+ continue;
301638
+ }
301639
+ files[name] = read(name);
301640
+ for (const match of files[name].matchAll(/<reference lib="([^"]+)"/g)) {
301641
+ pending.push(`lib.${match[1].toLowerCase()}.d.ts`);
301642
+ }
301978
301643
  }
301979
- return {
301980
- ok: diagnostics.length === 0 && code2 !== null,
301981
- code: diagnostics.length === 0 ? code2 : null,
301982
- input: diagnostics.length === 0 ? inputSchema.schema : null,
301983
- resources: diagnostics.length === 0 ? scriptResourceNames(file2, program3, request2.workspaceDeclarations, request2.appModules) : null,
301984
- diagnostics: diagnostics.toSorted((a, b2) => a.line - b2.line || a.column - b2.column)
301985
- };
301644
+ return files;
301645
+ }
301646
+ function readLibClosure(root = ROOT_LIB) {
301647
+ const libDir = dirname5(createRequire2(import.meta.url).resolve("typescript/lib/lib.d.ts"));
301648
+ return libClosure((name) => readFileSync7(join10(libDir, name), "utf8"), root);
301986
301649
  }
301987
301650
 
301988
- // scripts/lib/runtime-build/workflow-config.mjs
301651
+ // scripts/lib/workflow-script/lint-rules.mjs
301989
301652
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301990
- var WORKFLOW_STAGE = "workflow";
301991
- var UUID_PATTERN2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
301992
- var ROUTE_PATTERN = /^\/[a-z0-9\-_/{}]*$/;
301993
- var ROUTE_PARAM_PATTERN = /\{([^}]+)\}/g;
301994
- var CRON_FIELD_PATTERN = /^[0-9A-Za-z*/,\-?#]+$/;
301995
- var OFFSET_PATTERN = /^[+-]P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/i;
301996
- var WORKFLOW_PATH_PATTERN = /^workflows\/[^/]+\.ts$/;
301997
- var CONFIG_KEYS = /* @__PURE__ */ new Set(["title", "description", "trigger", "runAs", "authorizer"]);
301998
- var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
301999
- var RECORD_EVENTS = ["created", "updated", "deleted", "restored", "saved"];
302000
- var LIFECYCLE_HOOKS = ["creating", "updating", "saving", "deleting", "restoring"];
302001
- var WORKFLOW_EVENTS = ["execution.success", "execution.error", "execution.exception"];
302002
- var SCHEDULE_FIELD_TYPES = /* @__PURE__ */ new Set(["date", "datetime"]);
302003
- var TRIGGERS = {
302004
- request: {
302005
- type: "request",
302006
- keys: ["type", "path", "method"],
302007
- background: false,
302008
- sync: true
301653
+ var import_typescript6 = __toESM(require_typescript(), 1);
301654
+
301655
+ // scripts/lib/workflow-script/profile-rules.mjs
301656
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301657
+ var import_typescript5 = __toESM(require_typescript(), 1);
301658
+ var PROFILES = {
301659
+ workflow: {
301660
+ label: "A workflow script",
301661
+ imports: ["@diagonal/workflow", "@diagonal/workflow/workspace"],
301662
+ specifier: null,
301663
+ entry: null
302009
301664
  },
302010
- recordEvent: {
302011
- type: "event.record",
302012
- keys: ["type", "resource", "event", "filters"],
302013
- background: true,
302014
- sync: false
302015
- },
302016
- recordLifecycle: {
302017
- type: "lifecycle.record",
302018
- keys: ["type", "resource", "hook"],
302019
- background: false,
302020
- sync: true
302021
- },
302022
- recordSchedule: {
302023
- type: "schedule.record",
302024
- keys: ["type", "resource", "dateField", "offsets"],
302025
- background: true,
302026
- sync: false
302027
- },
302028
- scheduled: {
302029
- type: "scheduled",
302030
- keys: ["type", "expression"],
302031
- background: true,
302032
- sync: false
302033
- },
302034
- workflowEvent: {
302035
- type: "event.workflow",
302036
- keys: ["type", "workflow", "event"],
302037
- background: true,
302038
- sync: false
301665
+ test: {
301666
+ label: "A test script",
301667
+ imports: ["@diagonal/workflow", "@diagonal-hq/workflows/test", "@diagonal/workflow/workspace"],
301668
+ specifier: "@diagonal-hq/workflows/test",
301669
+ entry: "/sdk/profiles/test.ts"
302039
301670
  },
302040
- manual: {
302041
- type: "manual",
302042
- keys: ["type"],
302043
- background: false,
302044
- sync: true
301671
+ migration: {
301672
+ label: "A migration script",
301673
+ imports: ["@diagonal-hq/workflows/migration", "@diagonal/workflow/workspace"],
301674
+ specifier: "@diagonal-hq/workflows/migration",
301675
+ entry: "/sdk/profiles/migration.ts"
302045
301676
  }
302046
301677
  };
302047
- function unwrap2(node) {
302048
- let current = node;
302049
- while (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSNonNullExpression" || current.type === "ParenthesizedExpression") {
302050
- current = current.expression;
301678
+ var PROFILE_SPECIFIERS = new Set(
301679
+ Object.values(PROFILES).flatMap(({ specifier }) => specifier === null ? [] : [specifier])
301680
+ );
301681
+ var SDK_SPECIFIERS = /* @__PURE__ */ new Set(["@diagonal/workflow", ...PROFILE_SPECIFIERS]);
301682
+ function resolveProfile(name) {
301683
+ if (name === void 0 || name === null) {
301684
+ return "workflow";
302051
301685
  }
302052
- return current;
301686
+ if (typeof name !== "string" || !Object.hasOwn(PROFILES, name)) {
301687
+ throw new Error(`Unknown workflow script profile: ${String(name)}`);
301688
+ }
301689
+ return name;
302053
301690
  }
302054
- function propertyNodes(node) {
302055
- const unwrapped = node === void 0 ? null : unwrap2(node);
302056
- const nodes = /* @__PURE__ */ new Map();
302057
- if (unwrapped?.type !== "ObjectExpression") {
302058
- return nodes;
301691
+ function profileFindings(file2, checker, program3, profile) {
301692
+ const { entry, label, specifier } = PROFILES[profile];
301693
+ if (entry === null) {
301694
+ return [];
302059
301695
  }
302060
- for (const property of unwrapped.properties) {
302061
- if (property.type === "ObjectProperty") {
302062
- nodes.set(propertyKey(property), property);
301696
+ const entryFile = program3.getSourceFile(entry);
301697
+ const entrySymbol = entryFile && checker.getSymbolAtLocation(entryFile);
301698
+ if (!entrySymbol) {
301699
+ throw new Error(`The SDK has no ${entry} module.`);
301700
+ }
301701
+ const exports = new Map(
301702
+ checker.getExportsOfModule(entrySymbol).map((symbol) => [symbol.getName(), symbol])
301703
+ );
301704
+ const findings = [];
301705
+ const forbidden = (node, path) => findings.push({
301706
+ node,
301707
+ code: "profile-capability",
301708
+ message: `${label} cannot use ${path}. Use only the exports of ${specifier}.`
301709
+ });
301710
+ const exportType = (name) => {
301711
+ const symbol = exports.get(name);
301712
+ const target = symbol && symbol.flags & import_typescript5.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
301713
+ return target && target.flags & import_typescript5.default.SymbolFlags.Value ? checker.getTypeOfSymbolAtLocation(target, entryFile) : null;
301714
+ };
301715
+ const checkMembers = (identifier4, type, path) => {
301716
+ let node = identifier4;
301717
+ let current = type;
301718
+ let currentPath = path;
301719
+ while (current !== null) {
301720
+ const parent = node.parent;
301721
+ const isMemberAccess = import_typescript5.default.isPropertyAccessExpression(parent) && parent.expression === node || import_typescript5.default.isElementAccessExpression(parent) && parent.expression === node && import_typescript5.default.isStringLiteralLike(parent.argumentExpression);
301722
+ if (!isMemberAccess) {
301723
+ if (current.getCallSignatures().length === 0 && hasRestrictedMembers(current, currentPath)) {
301724
+ forbidden(node, `${currentPath} as a value`);
301725
+ }
301726
+ return;
301727
+ }
301728
+ const member = import_typescript5.default.isPropertyAccessExpression(parent) ? parent.name.text : parent.argumentExpression.text;
301729
+ const property = current.getProperty(member);
301730
+ currentPath = `${currentPath}.${member}`;
301731
+ if (!property) {
301732
+ forbidden(parent, currentPath);
301733
+ return;
301734
+ }
301735
+ current = checker.getTypeOfSymbolAtLocation(property, entryFile);
301736
+ node = parent;
301737
+ }
301738
+ };
301739
+ const hasRestrictedMembers = (profileType, path) => {
301740
+ const rootType = rootNamespaceTypes.get(path);
301741
+ return rootType !== void 0 && rootType.getProperties().some((property) => !profileType.getProperty(property.getName()));
301742
+ };
301743
+ const rootNamespaceTypes = /* @__PURE__ */ new Map();
301744
+ const rootFile = program3.getSourceFile("/sdk/index.ts");
301745
+ const rootSymbol = rootFile && checker.getSymbolAtLocation(rootFile);
301746
+ for (const symbol of rootSymbol ? checker.getExportsOfModule(rootSymbol) : []) {
301747
+ const target = symbol.flags & import_typescript5.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
301748
+ if (target.flags & import_typescript5.default.SymbolFlags.Value) {
301749
+ collectNamespaceTypes(
301750
+ checker,
301751
+ symbol.getName(),
301752
+ checker.getTypeOfSymbolAtLocation(target, rootFile),
301753
+ rootFile,
301754
+ rootNamespaceTypes
301755
+ );
301756
+ }
301757
+ }
301758
+ const valueSymbol = (node) => import_typescript5.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
301759
+ const references = (binding) => {
301760
+ const symbol = checker.getSymbolAtLocation(binding);
301761
+ const found2 = [];
301762
+ const visit = (node) => {
301763
+ if (import_typescript5.default.isIdentifier(node) && node !== binding && valueSymbol(node) === symbol && !import_typescript5.default.isImportSpecifier(node.parent)) {
301764
+ found2.push(node);
301765
+ }
301766
+ import_typescript5.default.forEachChild(node, visit);
301767
+ };
301768
+ visit(file2);
301769
+ return found2;
301770
+ };
301771
+ const checkNamespace = (binding) => {
301772
+ for (const reference of references(binding)) {
301773
+ const parent = reference.parent;
301774
+ if (!import_typescript5.default.isPropertyAccessExpression(parent) || parent.expression !== reference) {
301775
+ forbidden(reference, "the SDK namespace as a value");
301776
+ continue;
301777
+ }
301778
+ const name = parent.name.text;
301779
+ if (!exports.has(name)) {
301780
+ forbidden(parent, name);
301781
+ continue;
301782
+ }
301783
+ const type = exportType(name);
301784
+ if (type !== null) {
301785
+ checkMembers(parent, type, name);
301786
+ }
301787
+ }
301788
+ };
301789
+ for (const statement2 of file2.statements) {
301790
+ if (import_typescript5.default.isImportEqualsDeclaration(statement2) && import_typescript5.default.isExternalModuleReference(statement2.moduleReference) && import_typescript5.default.isStringLiteral(statement2.moduleReference.expression) && SDK_SPECIFIERS.has(statement2.moduleReference.expression.text)) {
301791
+ checkNamespace(statement2.name);
301792
+ continue;
301793
+ }
301794
+ if (!import_typescript5.default.isImportDeclaration(statement2) || !import_typescript5.default.isStringLiteral(statement2.moduleSpecifier) || !SDK_SPECIFIERS.has(statement2.moduleSpecifier.text) || !statement2.importClause) {
301795
+ continue;
301796
+ }
301797
+ const clause = statement2.importClause;
301798
+ if (clause.name) {
301799
+ forbidden(clause.name, "a default import of the SDK");
301800
+ }
301801
+ const bindings = clause.namedBindings;
301802
+ if (bindings && import_typescript5.default.isNamespaceImport(bindings)) {
301803
+ checkNamespace(bindings.name);
301804
+ continue;
301805
+ }
301806
+ for (const element of bindings && import_typescript5.default.isNamedImports(bindings) ? bindings.elements : []) {
301807
+ const name = (element.propertyName ?? element.name).text;
301808
+ if (!exports.has(name)) {
301809
+ forbidden(element, name);
301810
+ continue;
301811
+ }
301812
+ const type = exportType(name);
301813
+ if (type === null || element.isTypeOnly || clause.isTypeOnly) {
301814
+ continue;
301815
+ }
301816
+ for (const reference of references(element.name)) {
301817
+ checkMembers(reference, type, name);
301818
+ }
301819
+ }
301820
+ }
301821
+ return findings;
301822
+ }
301823
+ function collectNamespaceTypes(checker, path, type, location, into) {
301824
+ if (type.getCallSignatures().length > 0 || !(type.flags & import_typescript5.default.TypeFlags.Object)) {
301825
+ return;
301826
+ }
301827
+ into.set(path, type);
301828
+ for (const property of type.getProperties()) {
301829
+ collectNamespaceTypes(
301830
+ checker,
301831
+ `${path}.${property.getName()}`,
301832
+ checker.getTypeOfSymbolAtLocation(property, location),
301833
+ location,
301834
+ into
301835
+ );
301836
+ }
301837
+ }
301838
+
301839
+ // scripts/lib/workflow-script/lint-rules.mjs
301840
+ var UNSUPPORTED_GLOBALS = {
301841
+ Intl: "The sandbox has no Intl. Use date.format, time.format, money.format, or number.format.",
301842
+ crypto: "The sandbox has no crypto. Use text.hash, text.randomUuid, or security.randomPassword.",
301843
+ setTimeout: "The sandbox has no timers.",
301844
+ setInterval: "The sandbox has no timers.",
301845
+ fetch: "The sandbox has no network. Use http.request.",
301846
+ process: "The sandbox has no process.",
301847
+ require: "Use an import from @diagonal/workflow."
301848
+ };
301849
+ var FLOATING_MESSAGE = "Await this call, return it, or assign it. A call that is not awaited can fail without stopping the workflow.";
301850
+ var MAIL_TEMPLATE_CAPABILITIES = {
301851
+ MailSendInput: "mail.send",
301852
+ NotificationSendInput: "notification.send"
301853
+ };
301854
+ var MAIL_REFERENCES_KEY = "$references";
301855
+ var composedMailTextMessage = (capability, field2) => `Do not write values into the ${capability} ${field2}. The email evaluates this text as Liquid, so a value such as "{{ workspace.name }}" renders. Put each value in layoutData.${MAIL_REFERENCES_KEY} and write {{ ref.<key> }} in the text.`;
301856
+ function staticPropertyName(property) {
301857
+ if (!import_typescript6.default.isPropertyAssignment(property) && !import_typescript6.default.isShorthandPropertyAssignment(property)) {
301858
+ return null;
301859
+ }
301860
+ return propertyNameText(property.name);
301861
+ }
301862
+ function floatingPromiseCalls(expression2, holdsPromise) {
301863
+ const node = import_typescript6.default.skipParentheses(expression2);
301864
+ if (import_typescript6.default.isConditionalExpression(node)) {
301865
+ return [
301866
+ ...floatingPromiseCalls(node.whenTrue, holdsPromise),
301867
+ ...floatingPromiseCalls(node.whenFalse, holdsPromise)
301868
+ ];
301869
+ }
301870
+ if (import_typescript6.default.isBinaryExpression(node) && [
301871
+ import_typescript6.default.SyntaxKind.AmpersandAmpersandToken,
301872
+ import_typescript6.default.SyntaxKind.BarBarToken,
301873
+ import_typescript6.default.SyntaxKind.QuestionQuestionToken,
301874
+ import_typescript6.default.SyntaxKind.CommaToken
301875
+ ].includes(node.operatorToken.kind)) {
301876
+ return [
301877
+ ...floatingPromiseCalls(node.left, holdsPromise),
301878
+ ...floatingPromiseCalls(node.right, holdsPromise)
301879
+ ];
301880
+ }
301881
+ return (import_typescript6.default.isCallExpression(node) || import_typescript6.default.isArrayLiteralExpression(node)) && holdsPromise(node) ? [node] : [];
301882
+ }
301883
+ function returnsPromise(fn, checker) {
301884
+ const signature = checker.getSignatureFromDeclaration(fn);
301885
+ return signature !== void 0 && checker.getReturnTypeOfSignature(signature).getSymbol()?.getName() === "Promise";
301886
+ }
301887
+ function contextuallyReturnsVoid(fn, checker) {
301888
+ const signatures = checker.getContextualType(fn)?.getCallSignatures() ?? [];
301889
+ return signatures.length > 0 && signatures.every(
301890
+ (signature) => (checker.getReturnTypeOfSignature(signature).flags & import_typescript6.default.TypeFlags.Void) !== 0
301891
+ );
301892
+ }
301893
+ function isMemberName(node) {
301894
+ const parent = node.parent;
301895
+ if (import_typescript6.default.isPropertyAccessExpression(parent) || import_typescript6.default.isQualifiedName(parent)) {
301896
+ return parent.name === node || parent.right === node;
301897
+ }
301898
+ if (import_typescript6.default.isBindingElement(parent) || import_typescript6.default.isImportSpecifier(parent) || import_typescript6.default.isExportSpecifier(parent)) {
301899
+ return parent.propertyName === node;
301900
+ }
301901
+ return (import_typescript6.default.isPropertyAssignment(parent) || import_typescript6.default.isPropertyDeclaration(parent) || import_typescript6.default.isPropertySignature(parent) || import_typescript6.default.isMethodDeclaration(parent) || import_typescript6.default.isMethodSignature(parent) || import_typescript6.default.isGetAccessorDeclaration(parent) || import_typescript6.default.isSetAccessorDeclaration(parent) || import_typescript6.default.isEnumMember(parent)) && parent.name === node;
301902
+ }
301903
+ function lint2(file2, checker, { allowAppImports = false, profile = "workflow" } = {}) {
301904
+ const findings = [];
301905
+ const { imports: allowedImports, label } = PROFILES[profile];
301906
+ const allowedImportList = new Intl.ListFormat("en", { type: "disjunction" }).format(
301907
+ allowedImports
301908
+ );
301909
+ let defaultExport = null;
301910
+ const isPromiseType = (type) => type.getSymbol()?.getName() === "Promise";
301911
+ const holdsPromise = (node) => {
301912
+ const type = checker.getTypeAtLocation(node);
301913
+ if (checker.isArrayType(type) || checker.isTupleType(type)) {
301914
+ return checker.getTypeArguments(type).some(isPromiseType);
301915
+ }
301916
+ return isPromiseType(type);
301917
+ };
301918
+ const isDeclaredInScript = (symbol) => symbol?.declarations?.some((declaration) => declaration.getSourceFile() === file2) ?? false;
301919
+ const mailTemplateCapability = (call) => {
301920
+ const [parameter] = checker.getResolvedSignature(call)?.getParameters() ?? [];
301921
+ const inputType = parameter && checker.getTypeOfSymbolAtLocation(parameter, call).getSymbol();
301922
+ const fromSdk = inputType?.declarations?.some(
301923
+ (declaration) => declaration.getSourceFile().fileName.startsWith("/sdk/")
301924
+ ) ?? false;
301925
+ return fromSdk && Object.hasOwn(MAIL_TEMPLATE_CAPABILITIES, inputType.getName()) ? MAIL_TEMPLATE_CAPABILITIES[inputType.getName()] : null;
301926
+ };
301927
+ const constValue = (expression2) => {
301928
+ const node = unwrap2(expression2);
301929
+ if (!import_typescript6.default.isIdentifier(node)) {
301930
+ return node;
301931
+ }
301932
+ const symbol = import_typescript6.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
301933
+ const declaration = symbol?.valueDeclaration;
301934
+ return declaration !== void 0 && import_typescript6.default.isVariableDeclaration(declaration) && declaration.initializer !== void 0 && declaration.getSourceFile() === file2 && (import_typescript6.default.getCombinedNodeFlags(declaration) & import_typescript6.default.NodeFlags.Const) !== 0 ? unwrap2(declaration.initializer) : node;
301935
+ };
301936
+ const hasLiteralType = (node) => {
301937
+ const type = checker.getTypeAtLocation(node);
301938
+ return (type.isUnion() ? type.types : [type]).every(
301939
+ (member) => member.isLiteral() || (member.flags & import_typescript6.default.TypeFlags.BooleanLiteral) !== 0
301940
+ );
301941
+ };
301942
+ const isConstantText = (expression2, followed = /* @__PURE__ */ new Set()) => {
301943
+ const node = unwrap2(expression2);
301944
+ if (import_typescript6.default.isTemplateExpression(node)) {
301945
+ return node.templateSpans.every((span) => isConstantText(span.expression, followed));
301946
+ }
301947
+ if (import_typescript6.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript6.default.SyntaxKind.PlusToken) {
301948
+ return isConstantText(node.left, followed) && isConstantText(node.right, followed);
301949
+ }
301950
+ if (hasLiteralType(node)) {
301951
+ return true;
302063
301952
  }
302064
- }
302065
- return nodes;
302066
- }
302067
- function listOf(values) {
302068
- return values.map((value) => `'${value}'`).join(", ");
302069
- }
302070
- function blank(text) {
302071
- return text.replaceAll(/[^\n]/g, " ");
302072
- }
302073
- function isConfigExport(statement2) {
302074
- return statement2.type === "ExportNamedDeclaration" && statement2.declaration?.type === "VariableDeclaration" && statement2.declaration.declarations.some(
302075
- (declarator) => declarator.id.type === "Identifier" && declarator.id.name === "config"
302076
- );
302077
- }
302078
- function splitWorkflowModule(path, source, ast) {
302079
- const diagnostics = [];
302080
- const ranges = [];
302081
- let configNode = null;
302082
- let configCount = 0;
302083
- let hasDefault = false;
302084
- for (const statement2 of ast.program.body) {
302085
- if (statement2.type === "ImportDeclaration" && isAuthoringModule(statement2.source.value)) {
302086
- ranges.push(statement2);
302087
- continue;
301953
+ const initializer = import_typescript6.default.isIdentifier(node) ? constValue(node) : node;
301954
+ if (initializer === node || followed.has(initializer)) {
301955
+ return false;
302088
301956
  }
302089
- if (statement2.type === "ExportDefaultDeclaration") {
302090
- hasDefault = true;
302091
- continue;
301957
+ return isConstantText(initializer, /* @__PURE__ */ new Set([...followed, initializer]));
301958
+ };
301959
+ const composedMailText = (expression2) => {
301960
+ const node = unwrap2(expression2);
301961
+ if (import_typescript6.default.isConditionalExpression(node)) {
301962
+ return composedMailText(node.whenTrue) ?? composedMailText(node.whenFalse);
302092
301963
  }
302093
- if (!isConfigExport(statement2)) {
302094
- continue;
301964
+ if (import_typescript6.default.isBinaryExpression(node) && [import_typescript6.default.SyntaxKind.BarBarToken, import_typescript6.default.SyntaxKind.QuestionQuestionToken].includes(
301965
+ node.operatorToken.kind
301966
+ )) {
301967
+ return composedMailText(node.left) ?? composedMailText(node.right);
302095
301968
  }
302096
- configCount++;
302097
- ranges.push(statement2);
302098
- const declaration = statement2.declaration;
302099
- if (configCount > 1) {
302100
- diagnostics.push(
302101
- diagnosticAt(path, statement2, "A workflow can export only one config", {
302102
- stage: WORKFLOW_STAGE
302103
- })
302104
- );
302105
- continue;
301969
+ const isConcatenation = import_typescript6.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript6.default.SyntaxKind.PlusToken && (checker.getTypeAtLocation(node).flags & import_typescript6.default.TypeFlags.StringLike) !== 0;
301970
+ return (import_typescript6.default.isTemplateExpression(node) || isConcatenation) && !isConstantText(node) ? node : null;
301971
+ };
301972
+ const checkMailTemplateCall = (call) => {
301973
+ const capability = call.arguments.length > 0 ? mailTemplateCapability(call) : null;
301974
+ const input = capability === null ? null : constValue(call.arguments[0]);
301975
+ if (input === null || !import_typescript6.default.isObjectLiteralExpression(input)) {
301976
+ return;
302106
301977
  }
302107
- if (declaration.kind !== "const" || declaration.declarations.length !== 1) {
302108
- diagnostics.push(
302109
- diagnosticAt(
302110
- path,
302111
- statement2,
302112
- "Declare the config alone as `export const config = { ... }`",
302113
- { stage: WORKFLOW_STAGE }
302114
- )
302115
- );
302116
- continue;
301978
+ const valueOf = (property) => import_typescript6.default.isShorthandPropertyAssignment(property) ? property.name : property.initializer;
301979
+ const check2 = (value, field2) => {
301980
+ const composed = composedMailText(constValue(value));
301981
+ if (composed !== null) {
301982
+ findings.push({
301983
+ node: composed,
301984
+ code: "no-composed-mail-text",
301985
+ message: composedMailTextMessage(capability, field2)
301986
+ });
301987
+ }
301988
+ };
301989
+ for (const property of input.properties) {
301990
+ const name = staticPropertyName(property);
301991
+ if (name === "subject") {
301992
+ check2(valueOf(property), "subject");
301993
+ }
301994
+ const layoutData = name === "layoutData" ? constValue(valueOf(property)) : null;
301995
+ if (layoutData === null || !import_typescript6.default.isObjectLiteralExpression(layoutData)) {
301996
+ continue;
301997
+ }
301998
+ for (const slot of layoutData.properties) {
301999
+ const slotName = staticPropertyName(slot);
302000
+ if (slotName !== null && slotName !== MAIL_REFERENCES_KEY) {
302001
+ check2(valueOf(slot), `layoutData.${slotName}`);
302002
+ }
302003
+ }
302117
302004
  }
302118
- const init = declaration.declarations[0].init;
302119
- if (init === null || init === void 0) {
302120
- diagnostics.push(
302121
- diagnosticAt(path, statement2, "The config needs a value", { stage: WORKFLOW_STAGE })
302122
- );
302123
- continue;
302005
+ };
302006
+ const checkModuleSpecifier = (node, specifier) => {
302007
+ if (specifier && import_typescript6.default.isStringLiteral(specifier) && !allowedImports.includes(specifier.text) && !(allowAppImports && specifier.text.startsWith("@app/"))) {
302008
+ findings.push({
302009
+ node,
302010
+ code: "allowed-imports",
302011
+ message: profile === "workflow" ? `Import only @diagonal/workflow or @diagonal/workflow/workspace, not ${specifier.text}.` : `${label} imports only ${allowedImportList}, not ${specifier.text}.`
302012
+ });
302124
302013
  }
302125
- configNode = init;
302126
- }
302127
- if (configCount === 0) {
302128
- diagnostics.push(
302129
- diagnosticAt(
302130
- path,
302131
- null,
302132
- "The workflow has no config. Add `export const config = { title, trigger }`",
302133
- { stage: WORKFLOW_STAGE }
302134
- )
302135
- );
302136
- }
302137
- if (!hasDefault) {
302138
- diagnostics.push(
302139
- diagnosticAt(
302140
- path,
302141
- null,
302142
- "The workflow has no default export. Add `export default defineWorkflow(...)`",
302143
- { stage: WORKFLOW_STAGE }
302144
- )
302145
- );
302146
- }
302147
- let scriptSource = source;
302148
- for (const node of ranges.toSorted((left, right) => right.start - left.start)) {
302149
- scriptSource = scriptSource.slice(0, node.start) + blank(scriptSource.slice(node.start, node.end)) + scriptSource.slice(node.end);
302150
- }
302151
- return { configNode, scriptSource, diagnostics };
302152
- }
302153
- function readWorkflowConfig(path, configNode, context) {
302154
- const diagnostics = [];
302155
- const report = (node, message) => diagnostics.push(diagnosticAt(path, node, message, { stage: WORKFLOW_STAGE }));
302156
- let value;
302157
- try {
302158
- value = staticValue(configNode, { resources: context.resourcesBinding });
302159
- } catch (error) {
302160
- if (!(error instanceof SourceError)) {
302161
- throw error;
302014
+ };
302015
+ const visit = (node) => {
302016
+ if (import_typescript6.default.isImportDeclaration(node) || import_typescript6.default.isExportDeclaration(node)) {
302017
+ checkModuleSpecifier(node, node.moduleSpecifier);
302162
302018
  }
302163
- report(error.node, error.message);
302164
- return { config: null, diagnostics };
302165
- }
302166
- if (!isPlainObject(value)) {
302167
- report(configNode, "The config must be an object literal");
302168
- return { config: null, diagnostics };
302169
- }
302170
- const nodes = propertyNodes(configNode);
302171
- const at = (key) => nodes.get(key) ?? configNode;
302172
- for (const key of Object.keys(value)) {
302173
- if (!CONFIG_KEYS.has(key)) {
302174
- report(at(key), `Unknown workflow config option "${key}"`);
302019
+ if (import_typescript6.default.isImportEqualsDeclaration(node) && import_typescript6.default.isExternalModuleReference(node.moduleReference)) {
302020
+ checkModuleSpecifier(node, node.moduleReference.expression);
302021
+ }
302022
+ if (import_typescript6.default.isCallExpression(node) && node.expression.kind === import_typescript6.default.SyntaxKind.ImportKeyword) {
302023
+ findings.push({ node, code: "allowed-imports", message: "Dynamic import is not supported." });
302024
+ }
302025
+ if (import_typescript6.default.isCallExpression(node) && node.expression.kind !== import_typescript6.default.SyntaxKind.ImportKeyword) {
302026
+ checkMailTemplateCall(node);
302027
+ }
302028
+ if (import_typescript6.default.isExpressionStatement(node)) {
302029
+ for (const call of floatingPromiseCalls(node.expression, holdsPromise)) {
302030
+ findings.push({ node: call, code: "no-floating-capability", message: FLOATING_MESSAGE });
302031
+ }
302032
+ }
302033
+ if ((import_typescript6.default.isArrowFunction(node) || import_typescript6.default.isFunctionExpression(node)) && import_typescript6.default.isCallExpression(node.parent) && node.parent.arguments.includes(node) && returnsPromise(node, checker) && contextuallyReturnsVoid(node, checker)) {
302034
+ findings.push({ node, code: "no-floating-capability", message: FLOATING_MESSAGE });
302035
+ }
302036
+ if (import_typescript6.default.isIdentifier(node) && Object.hasOwn(UNSUPPORTED_GLOBALS, node.text)) {
302037
+ const isGlobalThisMember = import_typescript6.default.isPropertyAccessExpression(node.parent) && node.parent.name === node && import_typescript6.default.isIdentifier(node.parent.expression) && node.parent.expression.text === "globalThis";
302038
+ const symbol = import_typescript6.default.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
302039
+ const isGlobalReference = !isMemberName(node) && !isDeclaredInScript(symbol);
302040
+ if (isGlobalThisMember || isGlobalReference) {
302041
+ findings.push({
302042
+ node,
302043
+ code: "no-unsupported-global",
302044
+ message: UNSUPPORTED_GLOBALS[node.text]
302045
+ });
302046
+ }
302047
+ }
302048
+ if (import_typescript6.default.isExportAssignment(node) && !node.isExportEquals) {
302049
+ defaultExport = node.expression;
302175
302050
  }
302051
+ import_typescript6.default.forEachChild(node, visit);
302052
+ };
302053
+ for (const directive2 of file2.libReferenceDirectives) {
302054
+ findings.push({
302055
+ node: file2,
302056
+ position: directive2.pos,
302057
+ code: "no-lib-reference",
302058
+ message: "Remove this lib reference. Workflow scripts run on ES2023 in the sandbox."
302059
+ });
302176
302060
  }
302177
- const title = value.title;
302178
- if (typeof title !== "string" || title.trim() === "") {
302179
- report(at("title"), '"title" is required and must be a non-empty string');
302061
+ visit(file2);
302062
+ if (!isSdkDefineWorkflowCall(defaultExport, checker)) {
302063
+ findings.push({
302064
+ node: defaultExport ?? file2,
302065
+ code: "default-workflow-export",
302066
+ message: "Export the workflow as `export default defineWorkflow(async (input, ctx) => { ... })`."
302067
+ });
302180
302068
  }
302181
- const description = value.description ?? null;
302182
- if (description !== null && typeof description !== "string") {
302183
- report(at("description"), '"description" must be a string');
302069
+ return findings;
302070
+ }
302071
+ function isSdkDefineWorkflowCall(expression2, checker) {
302072
+ if (expression2 === null || !import_typescript6.default.isCallExpression(expression2) || !import_typescript6.default.isIdentifier(expression2.expression)) {
302073
+ return false;
302184
302074
  }
302185
- const scoped = { ...context, path };
302186
- const trigger = readTrigger(value.trigger, at("trigger"), scoped, report);
302187
- const runAs = trigger === null ? null : readRunAs(value.runAs, at("runAs"), trigger, scoped, report);
302188
- const authorizer = readAuthorizer(value.authorizer, at("authorizer"), trigger, report);
302189
- if (diagnostics.length > 0 || trigger === null) {
302190
- return { config: null, diagnostics };
302075
+ let symbol = checker.getSymbolAtLocation(expression2.expression);
302076
+ if (symbol && symbol.flags & import_typescript6.default.SymbolFlags.Alias) {
302077
+ symbol = checker.getAliasedSymbol(symbol);
302078
+ }
302079
+ return symbol?.getName() === "defineWorkflow" && (symbol.declarations?.some(
302080
+ (declaration) => declaration.getSourceFile().fileName.startsWith("/sdk/")
302081
+ ) ?? false);
302082
+ }
302083
+
302084
+ // scripts/lib/workflow-script/compile.mjs
302085
+ var SCRIPT = "/workflow.ts";
302086
+ var INPUT_VALIDATOR_CHECK = "/input-validator.check.ts";
302087
+ var INPUT_VALIDATOR_CHECK_SOURCE = `import type { InputValidator, WorkflowDefinition } from '@diagonal/workflow';
302088
+ import * as script from './workflow';
302089
+
302090
+ type Input = typeof script.default extends WorkflowDefinition<infer I, unknown> ? I : never;
302091
+ type Exported = typeof script extends { validateInput: infer V } ? V : undefined;
302092
+
302093
+ declare const validateInput: Exported;
302094
+ export const check: InputValidator<Input> | undefined = validateInput;
302095
+ `;
302096
+ var WORKSPACE = "/sdk/workspace.generated.ts";
302097
+ var APP_ROOT = "/app";
302098
+ var LIB_DIR = "/lib";
302099
+ var OPTIONS = {
302100
+ target: import_typescript7.default.ScriptTarget.ES2023,
302101
+ lib: [ROOT_LIB],
302102
+ module: import_typescript7.default.ModuleKind.CommonJS,
302103
+ moduleResolution: import_typescript7.default.ModuleResolutionKind.Bundler,
302104
+ strict: true,
302105
+ types: [],
302106
+ paths: {
302107
+ "@diagonal/workflow": ["/sdk/index.ts"],
302108
+ "@diagonal/workflow/workspace": [WORKSPACE],
302109
+ ...Object.fromEntries(
302110
+ Object.values(PROFILES).filter(({ specifier }) => specifier !== null).map(({ specifier, entry }) => [specifier, [entry]])
302111
+ )
302191
302112
  }
302192
- return {
302193
- config: {
302194
- title,
302195
- description,
302196
- type: trigger.definition.type,
302197
- settings: trigger.settings,
302198
- run_as: runAs,
302199
- authorizer,
302200
- execution_mode: trigger.definition.sync ? "sync" : "async"
302201
- },
302202
- diagnostics
302203
- };
302113
+ };
302114
+ var libFiles2;
302115
+ try {
302116
+ const { LIB_FILES: LIB_FILES2 } = await Promise.resolve().then(() => (init_sdk_files_generated(), sdk_files_generated_exports));
302117
+ libFiles2 = libClosure((name) => LIB_FILES2[name]);
302118
+ } catch {
302119
+ libFiles2 = readLibClosure();
302204
302120
  }
302205
- function resolveResource(reference, node, context, report) {
302206
- if (typeof reference !== "string" || reference === "") {
302207
- report(node, '"resource" must be Resources.<Name>.slug');
302208
- return null;
302209
- }
302210
- const resource = context.findResource(reference);
302211
- if (resource === void 0) {
302212
- if (context.reportUnknownResources) {
302213
- report(node, referenceProblem(reference, context.resources, context.names).message);
302214
- }
302215
- return null;
302121
+ var libSourceFiles = /* @__PURE__ */ new Map();
302122
+ var readLibFile = (name) => Object.hasOwn(libFiles2, name) ? libFiles2[name] : void 0;
302123
+ function libSourceFile(name, languageVersion) {
302124
+ if (!libSourceFiles.has(name)) {
302125
+ const text = readLibFile(name);
302126
+ libSourceFiles.set(
302127
+ name,
302128
+ text === void 0 ? void 0 : import_typescript7.default.createSourceFile(`${LIB_DIR}/${name}`, text, languageVersion)
302129
+ );
302216
302130
  }
302217
- return resource;
302131
+ return libSourceFiles.get(name);
302218
302132
  }
302219
- function oneOf(trigger, key, allowed, at, report) {
302220
- const item = trigger[key];
302221
- if (!allowed.includes(item)) {
302222
- report(at(key), `"${key}" must be one of: ${listOf(allowed)}`);
302223
- return null;
302133
+ var libName = (path) => path.startsWith(`${LIB_DIR}/`) ? path.slice(LIB_DIR.length + 1) : null;
302134
+ function position(file2, start) {
302135
+ if (file2 === void 0 || start === void 0) {
302136
+ return { line: 1, column: 1 };
302224
302137
  }
302225
- return item;
302138
+ const { line, character } = file2.getLineAndCharacterOfPosition(start);
302139
+ return { line: line + 1, column: character + 1 };
302226
302140
  }
302227
- function readTrigger(trigger, triggerNode, context, report) {
302228
- if (!isPlainObject(trigger)) {
302229
- report(triggerNode, `"trigger" is required: { type: ${listOf(Object.keys(TRIGGERS))}, ... }`);
302230
- return null;
302141
+ function inputValidatorPosition(file2) {
302142
+ for (const statement2 of file2.statements) {
302143
+ if (import_typescript7.default.isFunctionDeclaration(statement2) && statement2.name?.text === "validateInput") {
302144
+ return statement2.name.getStart(file2);
302145
+ }
302146
+ if (import_typescript7.default.isVariableStatement(statement2)) {
302147
+ for (const declaration of statement2.declarationList.declarations) {
302148
+ if (import_typescript7.default.isIdentifier(declaration.name) && declaration.name.text === "validateInput") {
302149
+ return declaration.name.getStart(file2);
302150
+ }
302151
+ }
302152
+ }
302231
302153
  }
302232
- const nodes = propertyNodes(triggerNode.value ?? triggerNode);
302233
- const at = (key) => nodes.get(key) ?? triggerNode;
302234
- const definition = Object.hasOwn(TRIGGERS, trigger.type) ? TRIGGERS[trigger.type] : void 0;
302235
- if (definition === void 0) {
302236
- report(at("type"), `"trigger.type" must be one of: ${listOf(Object.keys(TRIGGERS))}`);
302154
+ return void 0;
302155
+ }
302156
+ function workspaceResourceNames(file2, program3, workspaceDeclarations) {
302157
+ const checker = program3.getTypeChecker();
302158
+ const imports = /* @__PURE__ */ new Set();
302159
+ const namespaces2 = /* @__PURE__ */ new Set();
302160
+ const names2 = /* @__PURE__ */ new Set();
302161
+ const ids = /* @__PURE__ */ new Map();
302162
+ let needsAll = false;
302163
+ const key = (node) => node && (import_typescript7.default.isIdentifier(node) || import_typescript7.default.isStringLiteral(node) || import_typescript7.default.isNoSubstitutionTemplateLiteral(node)) ? node.text : null;
302164
+ const unparenthesized = (node) => {
302165
+ while (node && import_typescript7.default.isParenthesizedExpression(node)) {
302166
+ node = node.expression;
302167
+ }
302168
+ return node;
302169
+ };
302170
+ const symbol = (node) => {
302171
+ if (import_typescript7.default.isShorthandPropertyAssignment(node.parent)) {
302172
+ return checker.getShorthandAssignmentValueSymbol(node.parent);
302173
+ }
302174
+ if (import_typescript7.default.isExportSpecifier(node.parent) && !node.parent.parent.parent.moduleSpecifier) {
302175
+ return checker.getExportSpecifierLocalTargetSymbol(node.parent);
302176
+ }
302177
+ return checker.getSymbolAtLocation(node);
302178
+ };
302179
+ const isNamespace = (node) => node && import_typescript7.default.isIdentifier(node) && namespaces2.has(symbol(node));
302180
+ const member = (node) => {
302181
+ if (import_typescript7.default.isPropertyAccessExpression(node)) {
302182
+ return node.name.text;
302183
+ }
302184
+ if (import_typescript7.default.isElementAccessExpression(node)) {
302185
+ const argument = unparenthesized(node.argumentExpression);
302186
+ return argument && (import_typescript7.default.isStringLiteral(argument) || import_typescript7.default.isNoSubstitutionTemplateLiteral(argument)) ? argument.text : null;
302187
+ }
302237
302188
  return null;
302238
- }
302239
- let failed = false;
302240
- const fail = (node, message) => {
302241
- failed = true;
302242
- report(node, message);
302243
302189
  };
302244
- for (const key of Object.keys(trigger)) {
302245
- if (!definition.keys.includes(key)) {
302246
- fail(at(key), `A ${trigger.type} trigger has no option "${key}"`);
302190
+ const isMap3 = (node) => import_typescript7.default.isIdentifier(node) && imports.has(symbol(node)) || (import_typescript7.default.isPropertyAccessExpression(node) || import_typescript7.default.isElementAccessExpression(node)) && isNamespace(unparenthesized(node.expression)) && member(node) === "resources";
302191
+ for (const statement2 of file2.statements) {
302192
+ if (import_typescript7.default.isExportDeclaration(statement2) && !statement2.isTypeOnly && statement2.moduleSpecifier && import_typescript7.default.isStringLiteral(statement2.moduleSpecifier) && statement2.moduleSpecifier.text === "@diagonal/workflow/workspace" && (!statement2.exportClause || import_typescript7.default.isNamespaceExport(statement2.exportClause) || statement2.exportClause.elements.some(
302193
+ (element) => !element.isTypeOnly && (element.propertyName ?? element.name).text === "resources"
302194
+ ))) {
302195
+ return null;
302247
302196
  }
302248
- }
302249
- const settings = triggerSettings(trigger, at, context, fail);
302250
- return failed || settings === null ? null : { definition, name: trigger.type, settings };
302251
- }
302252
- function triggerSettings(trigger, at, context, fail) {
302253
- switch (trigger.type) {
302254
- case "request": {
302255
- const path = trigger.path;
302256
- if (typeof path !== "string" || !ROUTE_PATTERN.test(path) || path.length > 255) {
302257
- fail(
302258
- at("path"),
302259
- '"path" must start with "/" and contain only a-z, 0-9, -, _, /, and {param}'
302260
- );
302261
- return null;
302262
- }
302263
- const method = trigger.method === void 0 ? "GET" : oneOf(trigger, "method", HTTP_METHODS, at, fail);
302264
- if (method === null) {
302265
- return null;
302197
+ if (import_typescript7.default.isImportEqualsDeclaration(statement2)) {
302198
+ const reference = statement2.moduleReference;
302199
+ if (!statement2.isTypeOnly && import_typescript7.default.isExternalModuleReference(reference) && reference.expression && import_typescript7.default.isStringLiteral(reference.expression) && reference.expression.text === "@diagonal/workflow/workspace") {
302200
+ namespaces2.add(checker.getSymbolAtLocation(statement2.name));
302266
302201
  }
302267
- const params = [...path.matchAll(ROUTE_PARAM_PATTERN)].map((match) => ({
302268
- key: match[1],
302269
- scope: null,
302270
- relations: [],
302271
- resource_id: null,
302272
- lookup_field: null
302273
- }));
302274
- return { route: path, method, params };
302202
+ continue;
302275
302203
  }
302276
- case "recordEvent": {
302277
- const resource = resolveResource(trigger.resource, at("resource"), context, fail);
302278
- const event = oneOf(trigger, "event", RECORD_EVENTS, at, fail);
302279
- if (trigger.filters !== void 0 && trigger.filters !== null && typeof trigger.filters !== "object") {
302280
- fail(at("filters"), '"filters" must be a filter object');
302281
- }
302282
- if (resource === null || event === null) {
302283
- return null;
302284
- }
302285
- return trigger.filters === void 0 ? { event, resource: resource.slug } : { event, resource: resource.slug, filters: trigger.filters };
302204
+ if (!import_typescript7.default.isImportDeclaration(statement2) || statement2.moduleSpecifier.text !== "@diagonal/workflow/workspace" || statement2.importClause?.isTypeOnly) {
302205
+ continue;
302286
302206
  }
302287
- case "recordLifecycle": {
302288
- const resource = resolveResource(trigger.resource, at("resource"), context, fail);
302289
- const hook = oneOf(trigger, "hook", LIFECYCLE_HOOKS, at, fail);
302290
- return resource === null || hook === null ? null : { hook, resource: resource.slug };
302207
+ const bindings = statement2.importClause?.namedBindings;
302208
+ if (bindings && import_typescript7.default.isNamespaceImport(bindings)) {
302209
+ namespaces2.add(checker.getSymbolAtLocation(bindings.name));
302291
302210
  }
302292
- case "recordSchedule": {
302293
- const resource = resolveResource(trigger.resource, at("resource"), context, fail);
302294
- const offsets = readOffsets(trigger.offsets, at("offsets"), fail);
302295
- const dateField = trigger.dateField;
302296
- if (typeof dateField !== "string" || dateField === "") {
302297
- fail(at("dateField"), '"dateField" must be the key of a date or datetime field');
302298
- return null;
302299
- }
302300
- if (resource !== null && resource.platform !== true) {
302301
- const field2 = resource.fields.find((item) => item.key === dateField);
302302
- if (field2 === void 0 || !SCHEDULE_FIELD_TYPES.has(field2.type)) {
302303
- fail(
302304
- at("dateField"),
302305
- `"${dateField}" is not a date or datetime field of resource "${resource.slug}"`
302306
- );
302307
- return null;
302211
+ if (bindings && import_typescript7.default.isNamedImports(bindings)) {
302212
+ for (const binding of bindings.elements) {
302213
+ if (!binding.isTypeOnly && (binding.propertyName ?? binding.name).text === "resources") {
302214
+ imports.add(checker.getSymbolAtLocation(binding.name));
302308
302215
  }
302309
302216
  }
302310
- return resource === null || offsets === null ? null : { schedule: { offsets }, date_field: dateField, resource: resource.slug };
302311
302217
  }
302312
- case "scheduled": {
302313
- const expression2 = trigger.expression;
302314
- const fields = typeof expression2 === "string" ? expression2.trim().split(/\s+/) : [];
302315
- if (fields.length !== 5 || !fields.every((field2) => CRON_FIELD_PATTERN.test(field2))) {
302316
- fail(
302317
- at("expression"),
302318
- '"expression" must be a cron expression with 5 fields, for example "0 2 * * *"'
302319
- );
302320
- return null;
302321
- }
302322
- return { expression: expression2 };
302218
+ }
302219
+ const workspace = program3.getSourceFile(WORKSPACE) ?? import_typescript7.default.createSourceFile(WORKSPACE, workspaceDeclarations, import_typescript7.default.ScriptTarget.ES2023, true);
302220
+ for (const statement2 of workspace.statements) {
302221
+ if (!import_typescript7.default.isVariableStatement(statement2)) {
302222
+ continue;
302323
302223
  }
302324
- case "workflowEvent": {
302325
- const workflow = trigger.workflow;
302326
- const event = oneOf(trigger, "event", WORKFLOW_EVENTS, at, fail);
302327
- if (typeof workflow !== "string" || !WORKFLOW_PATH_PATTERN.test(workflow)) {
302328
- fail(
302329
- at("workflow"),
302330
- '"workflow" must be the path of a workflow, for example "workflows/welcome.ts"'
302331
- );
302332
- return null;
302333
- }
302334
- if (!context.workflowPaths.has(workflow)) {
302335
- fail(at("workflow"), `Unknown workflow "${workflow}". Add the file or change the path`);
302336
- return null;
302337
- }
302338
- if (workflow === context.path) {
302339
- fail(at("workflow"), "A workflow cannot trigger on its own runs");
302340
- return null;
302224
+ for (const declaration of statement2.declarationList.declarations) {
302225
+ if (!import_typescript7.default.isIdentifier(declaration.name) || declaration.name.text !== "resources") {
302226
+ continue;
302227
+ }
302228
+ const value = declaration.initializer && unwrap2(declaration.initializer);
302229
+ if (!value || !import_typescript7.default.isObjectLiteralExpression(value)) {
302230
+ continue;
302231
+ }
302232
+ for (const property of value.properties) {
302233
+ if (import_typescript7.default.isPropertyAssignment(property) && import_typescript7.default.isStringLiteral(property.initializer) && key(property.name) !== null) {
302234
+ ids.set(property.initializer.text, key(property.name));
302235
+ }
302341
302236
  }
302342
- return event === null ? null : { event, workflow: { path: workflow } };
302343
- }
302344
- case "manual":
302345
- return {};
302346
- default:
302347
- return null;
302348
- }
302349
- }
302350
- function readOffsets(offsets, node, fail) {
302351
- if (!Array.isArray(offsets) || offsets.length === 0) {
302352
- fail(node, `"offsets" must be a list of signed ISO 8601 durations, for example ['-P1D']`);
302353
- return null;
302354
- }
302355
- for (const offset of offsets) {
302356
- if (typeof offset !== "string" || !OFFSET_PATTERN.test(offset) || !/\d+[DHM]/i.test(offset)) {
302357
- fail(
302358
- node,
302359
- `Offset ${JSON.stringify(offset)} must be a signed ISO 8601 duration in days, hours, or minutes, for example '-P1D' or '+PT2H'`
302360
- );
302361
- return null;
302362
302237
  }
302363
302238
  }
302364
- if (new Set(offsets).size !== offsets.length) {
302365
- fail(node, "The offsets must be distinct");
302366
- return null;
302367
- }
302368
- return offsets;
302369
- }
302370
- function readRunAs(runAs, node, trigger, context, report) {
302371
- const name = trigger.name;
302372
- if (runAs === void 0 || runAs === null) {
302373
- if (name === "request") {
302374
- return { mode: "session" };
302239
+ const visit = (node) => {
302240
+ if (needsAll || import_typescript7.default.isImportDeclaration(node) || import_typescript7.default.isImportEqualsDeclaration(node) && import_typescript7.default.isExternalModuleReference(node.moduleReference) || import_typescript7.default.isTypeNode(node)) {
302241
+ return;
302375
302242
  }
302376
- if (trigger.definition.background) {
302377
- report(
302378
- node,
302379
- `A ${name} workflow runs in the background and needs an identity. Set runAs to 'system' or { resource, record }`
302380
- );
302243
+ if ((import_typescript7.default.isStringLiteral(node) || import_typescript7.default.isNoSubstitutionTemplateLiteral(node)) && ids.has(node.text)) {
302244
+ names2.add(ids.get(node.text));
302381
302245
  }
302382
- return null;
302383
- }
302384
- if (name === "recordLifecycle") {
302385
- report(node, "A recordLifecycle workflow runs inside the record write. Remove runAs");
302386
- return null;
302387
- }
302388
- if (runAs === "system") {
302389
- return { mode: "system" };
302390
- }
302391
- if (runAs === "session") {
302392
- if (name !== "request") {
302393
- report(
302394
- node,
302395
- "runAs 'session' is only for request workflows. Use 'system' or { resource, record }"
302396
- );
302246
+ let use = node;
302247
+ while (import_typescript7.default.isParenthesizedExpression(use.parent)) {
302248
+ use = use.parent;
302249
+ }
302250
+ if (isMap3(node)) {
302251
+ const parent = use.parent;
302252
+ const name = (import_typescript7.default.isPropertyAccessExpression(parent) || import_typescript7.default.isElementAccessExpression(parent)) && parent.expression === use ? member(parent) : null;
302253
+ if (name === null) {
302254
+ needsAll = true;
302255
+ } else {
302256
+ names2.add(name);
302257
+ }
302258
+ } else if (isNamespace(node) && !isMap3(use.parent)) {
302259
+ needsAll = true;
302260
+ }
302261
+ if (!needsAll) {
302262
+ import_typescript7.default.forEachChild(node, visit);
302263
+ }
302264
+ };
302265
+ import_typescript7.default.forEachChild(file2, visit);
302266
+ return needsAll ? null : [...names2].toSorted((left, right) => left.localeCompare(right));
302267
+ }
302268
+ function scriptResourceNames(file2, program3, workspaceDeclarations, appModules = {}) {
302269
+ const names2 = /* @__PURE__ */ new Set();
302270
+ for (const source of [
302271
+ file2,
302272
+ ...Object.keys(appModules).map((path) => program3.getSourceFile(`${APP_ROOT}/${path}`))
302273
+ ]) {
302274
+ if (source === void 0) {
302397
302275
  return null;
302398
302276
  }
302399
- return { mode: "session" };
302400
- }
302401
- if (!isPlainObject(runAs)) {
302402
- report(node, "runAs must be 'system', 'session', or { resource, record }");
302403
- return null;
302404
- }
302405
- for (const key of Object.keys(runAs)) {
302406
- if (key !== "resource" && key !== "record") {
302407
- report(node, `runAs has no option "${key}". Use { resource, record }`);
302277
+ const used = workspaceResourceNames(source, program3, workspaceDeclarations);
302278
+ if (used === null) {
302408
302279
  return null;
302409
302280
  }
302281
+ for (const name of used) {
302282
+ names2.add(name);
302283
+ }
302410
302284
  }
302411
- const resource = resolveResource(runAs.resource, node, context, report);
302412
- if (typeof runAs.record !== "string" || !UUID_PATTERN2.test(runAs.record)) {
302413
- report(node, '"runAs.record" must be the lowercase UUID of a record');
302414
- return null;
302415
- }
302416
- return resource === null ? null : { mode: "fixed", resource: resource.slug, record_id: runAs.record };
302285
+ return [...names2].toSorted((left, right) => left.localeCompare(right));
302417
302286
  }
302418
- function readAuthorizer(authorizer, node, trigger, report) {
302419
- if (authorizer === void 0 || authorizer === null) {
302420
- return null;
302287
+ function createScriptProgram({
302288
+ source,
302289
+ sdkFiles: sdkFiles2,
302290
+ workspaceDeclarations,
302291
+ appModules = {},
302292
+ profile
302293
+ }) {
302294
+ const entry = PROFILES[resolveProfile(profile)].entry;
302295
+ const files = new Map(
302296
+ Object.entries({
302297
+ ...sdkFiles2,
302298
+ [WORKSPACE]: workspaceDeclarations,
302299
+ [SCRIPT]: source,
302300
+ [INPUT_VALIDATOR_CHECK]: INPUT_VALIDATOR_CHECK_SOURCE,
302301
+ ...Object.fromEntries(
302302
+ Object.entries(appModules).map(([path, moduleSource]) => [
302303
+ `${APP_ROOT}/${path}`,
302304
+ moduleSource
302305
+ ])
302306
+ )
302307
+ })
302308
+ );
302309
+ const host = {
302310
+ getSourceFile: (name, languageVersion) => {
302311
+ const lib = libName(name);
302312
+ if (lib !== null) {
302313
+ return libSourceFile(lib, languageVersion);
302314
+ }
302315
+ return files.has(name) ? import_typescript7.default.createSourceFile(name, files.get(name), languageVersion, true) : void 0;
302316
+ },
302317
+ getDefaultLibFileName: () => `${LIB_DIR}/${ROOT_LIB}`,
302318
+ getDefaultLibLocation: () => LIB_DIR,
302319
+ writeFile: () => {
302320
+ },
302321
+ getCurrentDirectory: () => "/",
302322
+ getCanonicalFileName: (name) => name,
302323
+ useCaseSensitiveFileNames: () => true,
302324
+ getNewLine: () => "\n",
302325
+ fileExists: (name) => files.has(name) || libName(name) !== null && readLibFile(libName(name)) !== void 0,
302326
+ readFile: (name) => files.get(name) ?? (libName(name) !== null ? readLibFile(libName(name)) : void 0),
302327
+ directoryExists: (name) => {
302328
+ const prefix2 = name.endsWith("/") ? name : `${name}/`;
302329
+ return prefix2 === `${LIB_DIR}/` || [...files.keys()].some((path) => path.startsWith(prefix2));
302330
+ },
302331
+ getDirectories: () => []
302332
+ };
302333
+ const program3 = import_typescript7.default.createProgram({
302334
+ rootNames: [SCRIPT, INPUT_VALIDATOR_CHECK, WORKSPACE, ...entry === null ? [] : [entry]],
302335
+ options: Object.keys(appModules).length === 0 ? OPTIONS : { ...OPTIONS, paths: { ...OPTIONS.paths, "@app/*": [`${APP_ROOT}/*`] } },
302336
+ host
302337
+ });
302338
+ return { program: program3, file: program3.getSourceFile(SCRIPT) };
302339
+ }
302340
+ function servedProfileImports(context) {
302341
+ const { factory } = context;
302342
+ const served = (specifier) => import_typescript7.default.isStringLiteral(specifier) && PROFILE_SPECIFIERS.has(specifier.text) ? factory.createStringLiteral("@diagonal/workflow") : specifier;
302343
+ return (sourceFile) => factory.updateSourceFile(
302344
+ sourceFile,
302345
+ sourceFile.statements.map((statement2) => {
302346
+ if (import_typescript7.default.isImportDeclaration(statement2)) {
302347
+ return factory.updateImportDeclaration(
302348
+ statement2,
302349
+ statement2.modifiers,
302350
+ statement2.importClause,
302351
+ served(statement2.moduleSpecifier),
302352
+ statement2.attributes
302353
+ );
302354
+ }
302355
+ if (import_typescript7.default.isImportEqualsDeclaration(statement2) && import_typescript7.default.isExternalModuleReference(statement2.moduleReference)) {
302356
+ return factory.updateImportEqualsDeclaration(
302357
+ statement2,
302358
+ statement2.modifiers,
302359
+ statement2.isTypeOnly,
302360
+ statement2.name,
302361
+ factory.updateExternalModuleReference(
302362
+ statement2.moduleReference,
302363
+ served(statement2.moduleReference.expression)
302364
+ )
302365
+ );
302366
+ }
302367
+ if (import_typescript7.default.isExportDeclaration(statement2) && statement2.moduleSpecifier) {
302368
+ return factory.updateExportDeclaration(
302369
+ statement2,
302370
+ statement2.modifiers,
302371
+ statement2.isTypeOnly,
302372
+ statement2.exportClause,
302373
+ served(statement2.moduleSpecifier),
302374
+ statement2.attributes
302375
+ );
302376
+ }
302377
+ return statement2;
302378
+ })
302379
+ );
302380
+ }
302381
+ function compileWorkflowScript(request2, scriptProgram = createScriptProgram(request2)) {
302382
+ let code2 = null;
302383
+ const { program: program3, file: file2 } = scriptProgram;
302384
+ const diagnostics = [];
302385
+ for (const diagnostic2 of import_typescript7.default.getPreEmitDiagnostics(program3, file2)) {
302386
+ diagnostics.push({
302387
+ severity: "error",
302388
+ code: `TS${diagnostic2.code}`,
302389
+ message: import_typescript7.default.flattenDiagnosticMessageText(diagnostic2.messageText, "\n"),
302390
+ ...position(diagnostic2.file, diagnostic2.start)
302391
+ });
302421
302392
  }
302422
- if (authorizer !== "authenticated") {
302423
- report(node, "authorizer must be 'authenticated'");
302424
- return null;
302393
+ for (const diagnostic2 of program3.getSemanticDiagnostics(
302394
+ program3.getSourceFile(INPUT_VALIDATOR_CHECK)
302395
+ )) {
302396
+ diagnostics.push({
302397
+ severity: "error",
302398
+ code: `TS${diagnostic2.code}`,
302399
+ message: `validateInput must be (input, ctx) => InputErrors<Input> | void for this workflow's input. ${import_typescript7.default.flattenDiagnosticMessageText(diagnostic2.messageText, "\n")}`,
302400
+ ...position(file2, inputValidatorPosition(file2))
302401
+ });
302425
302402
  }
302426
- if (trigger !== null && trigger.name !== "request") {
302427
- report(node, "Only a request workflow can have an authorizer");
302428
- return null;
302403
+ const inputSchema = extractInputSchema(file2, program3.getTypeChecker());
302404
+ const allowAppImports = Object.keys(request2.appModules ?? {}).length > 0;
302405
+ const profile = resolveProfile(request2.profile);
302406
+ for (const finding of [
302407
+ ...lint2(file2, program3.getTypeChecker(), { allowAppImports, profile }),
302408
+ ...profileFindings(file2, program3.getTypeChecker(), program3, profile),
302409
+ ...inputSchema.findings
302410
+ ]) {
302411
+ diagnostics.push({
302412
+ severity: "error",
302413
+ code: finding.code,
302414
+ message: finding.message,
302415
+ ...position(file2, finding.position ?? finding.node.getStart(file2))
302416
+ });
302429
302417
  }
302430
- return { requires_authentication: true };
302418
+ if (diagnostics.length === 0) {
302419
+ program3.emit(
302420
+ file2,
302421
+ (name, text) => {
302422
+ if (name === "/workflow.js") {
302423
+ code2 = text;
302424
+ }
302425
+ },
302426
+ void 0,
302427
+ false,
302428
+ { before: [servedProfileImports] }
302429
+ );
302430
+ }
302431
+ return {
302432
+ ok: diagnostics.length === 0 && code2 !== null,
302433
+ code: diagnostics.length === 0 ? code2 : null,
302434
+ input: diagnostics.length === 0 ? inputSchema.schema : null,
302435
+ resources: diagnostics.length === 0 ? scriptResourceNames(file2, program3, request2.workspaceDeclarations, request2.appModules) : null,
302436
+ diagnostics: diagnostics.toSorted((a, b2) => a.line - b2.line || a.column - b2.column)
302437
+ };
302431
302438
  }
302432
302439
 
302433
302440
  // scripts/lib/runtime-build/workspace-script-types.mjs
@@ -302610,6 +302617,7 @@ function reportDuplicateTriggers(workflows, diagnostics) {
302610
302617
  }
302611
302618
  function buildWorkflows({
302612
302619
  workflows,
302620
+ uidsByPath = /* @__PURE__ */ new Map(),
302613
302621
  tests,
302614
302622
  resources,
302615
302623
  platformResources = [],
@@ -302670,6 +302678,7 @@ function buildWorkflows({
302670
302678
  const config = read.config;
302671
302679
  return {
302672
302680
  path,
302681
+ uid: uidsByPath.get(path) ?? null,
302673
302682
  title: config?.title ?? null,
302674
302683
  description: config?.description ?? null,
302675
302684
  type: config?.type ?? null,
@@ -302811,6 +302820,12 @@ function classify(path) {
302811
302820
  return "ignored";
302812
302821
  }
302813
302822
  }
302823
+ function rereadWorkflowFiles(root, workflowFiles) {
302824
+ return workflowFiles.map((file2) => {
302825
+ const source = readFileSync8(join11(root, file2.path), "utf8");
302826
+ return source === file2.source ? file2 : { path: file2.path, source, ast: parseSource(source, { jsx: false }) };
302827
+ });
302828
+ }
302814
302829
  function reportDuplicates(items, keyOf, label, diagnostics, nodeOf = () => null) {
302815
302830
  const seen = /* @__PURE__ */ new Map();
302816
302831
  for (const item of items) {
@@ -302946,6 +302961,10 @@ function uidDefinitionNodes(kind, ast) {
302946
302961
  const platform = node.type === "ObjectExpression" && node.properties.some((property) => property.type === "ObjectProperty" && propertyKey(property) === "platform");
302947
302962
  return platform ? [] : [{ type: "resource", node }];
302948
302963
  }
302964
+ case "workflow": {
302965
+ const node = workflowConfigObject(ast);
302966
+ return node === null ? [] : [{ type: "workflow", node }];
302967
+ }
302949
302968
  default:
302950
302969
  return [];
302951
302970
  }
@@ -303058,6 +303077,9 @@ function buildWorkspace(root, { assetCatalog = null, writeSource = false } = {})
303058
303077
  break;
303059
303078
  case "workflow":
303060
303079
  workflowFiles.push({ path, source, ast });
303080
+ for (const { type, node } of uidDefinitionNodes(kind, ast)) {
303081
+ uidPositions.set(path, uidDefinitions.push({ type, path, source, node }) - 1);
303082
+ }
303061
303083
  break;
303062
303084
  case "workflow_test":
303063
303085
  workflowTestFiles.push({ path, source, ast });
@@ -303138,7 +303160,8 @@ function buildWorkspace(root, { assetCatalog = null, writeSource = false } = {})
303138
303160
  entries
303139
303161
  );
303140
303162
  const workflowBuild = buildWorkflows({
303141
- workflows: workflowFiles,
303163
+ workflows: rereadWorkflowFiles(root, workflowFiles),
303164
+ uidsByPath: new Map(workflowFiles.map((file2) => [file2.path, uidCheck.uids[uidPositions.get(file2.path)] ?? null])),
303142
303165
  tests: workflowTestFiles,
303143
303166
  resources: output.resources,
303144
303167
  platformResources: output.platform_resources,