@diagonal-hq/cli 0.35.8 → 0.36.0

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.
Files changed (2) hide show
  1. package/dist/cli.mjs +1867 -2174
  2. package/package.json +4 -4
package/dist/cli.mjs CHANGED
@@ -77551,16 +77551,22 @@ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
77551
77551
  ".woff2"
77552
77552
  ]);
77553
77553
  var BINARY_FILE_MESSAGE = "Binary files cannot be in the repository. Add it as an Application Asset and use Assets.<Name>.url from @app/generated/assets in code or url(asset:<key>) in CSS. For an icon, use the Icon component from @diagonal-hq/pages or an SVG written as a TSX component";
77554
- function binaryCssUrlMessage(value) {
77555
- return `url("${value}") is not supported. A CSS url() can name an Application Asset as url(asset:<key>), a data: URL, an http: or https: URL, or a #fragment`;
77556
- }
77557
- function binaryCssImportMessage(value) {
77558
- const request2 = value.split(/[?#]/)[0];
77559
- return BINARY_EXTENSIONS.has(posix.extname(request2).toLowerCase()) ? `"${value}" is a binary file. Binary files cannot be in the repository. Add it as an Application Asset and use url(asset:<key>)` : null;
77560
- }
77561
77554
  var NODE_MODULES = new Set(builtinModules.flatMap((name) => [name, `node:${name}`]));
77562
77555
  var SERVER_PACKAGES = /* @__PURE__ */ new Set(["@diagonal/workflow", "@diagonal/workflow/workspace"]);
77563
77556
  var SERVER_PACKAGE_NAMES = /* @__PURE__ */ new Set(["@diagonal-hq/workflows"]);
77557
+ var IMPORT_RULES = {
77558
+ hostModules: [...HOST_MODULES],
77559
+ nodeModules: [...NODE_MODULES],
77560
+ renamedModules: Object.fromEntries(RENAMED_MODULES),
77561
+ serverModules: [...SERVER_PACKAGES],
77562
+ serverPackages: [...SERVER_PACKAGE_NAMES],
77563
+ binaryExtensions: [...BINARY_EXTENSIONS],
77564
+ sourceExtensions: SOURCE_EXTENSIONS,
77565
+ binaryFileMessage: BINARY_FILE_MESSAGE,
77566
+ pagesSdkModule: PAGES_SDK_MODULE,
77567
+ pagesSdkExports: Object.keys(PAGE_SDK_EXPORTS),
77568
+ pagesSdkTypes: Object.keys(PAGE_SDK_TYPES)
77569
+ };
77564
77570
  function importKind(specifier) {
77565
77571
  const bare = specifier.split("?")[0];
77566
77572
  if (specifier.includes("?") || bare.endsWith(".wasm") || /^[a-z][a-z0-9+.-]*:\/\//i.test(specifier)) {
@@ -77693,130 +77699,33 @@ function moduleSpecifiers(ast) {
77693
77699
  }
77694
77700
  return found2;
77695
77701
  }
77696
- function checkoutFile(root, path) {
77697
- if (path === ".." || path.startsWith("../") || posix.isAbsolute(path)) {
77698
- return null;
77702
+ function requestedNames(statement2) {
77703
+ if (statement2 === null || statement2.importKind === "type" || statement2.exportKind === "type") {
77704
+ return [];
77699
77705
  }
77700
- const file2 = join(root, path);
77701
- if (!existsSync(file2)) {
77702
- return null;
77706
+ if (statement2.type === "ExportAllDeclaration") {
77707
+ return ["*"];
77703
77708
  }
77704
- const realRoot = realpathSync(root);
77705
- const realFile = realpathSync(file2);
77706
- return realFile.startsWith(`${realRoot}/`) ? file2 : null;
77707
- }
77708
- function isExternalCssUrl(value) {
77709
- return /^(asset:|data:|https?:|#)/i.test(value);
77710
- }
77711
- function resolveCssReference(root, importerPath, value) {
77712
- const request2 = value.split(/[?#]/)[0];
77713
- if (posix.isAbsolute(request2)) {
77714
- return null;
77709
+ if (statement2.type === "ExportNamedDeclaration") {
77710
+ return (statement2.specifiers ?? []).filter((specifier) => specifier.exportKind !== "type").map(
77711
+ (specifier) => specifier.type === "ExportNamespaceSpecifier" ? "*" : specifier.local.name ?? specifier.local.value
77712
+ );
77715
77713
  }
77716
- const path = posix.normalize(posix.join(posix.dirname(importerPath), request2));
77717
- const file2 = checkoutFile(root, path);
77718
- return file2 !== null && isExactFile(file2) ? relative(realpathSync(root), realpathSync(file2)).split("\\").join("/") : null;
77719
- }
77720
- function assetUrlKey(value) {
77721
- return /^asset:/i.test(value) ? value.slice(6) : null;
77722
- }
77723
- function cssReferences(source) {
77724
- const urls = [];
77725
- const imports = [];
77726
- const functions = [];
77727
- let offset = 0;
77728
- let importing = false;
77729
- let composing = false;
77730
- let nextNewline = source.indexOf("\n");
77731
- let line = 1;
77732
- let lineStart = 0;
77733
- const skipSpace = () => {
77734
- while (offset < source.length) {
77735
- if (/\s/.test(source[offset])) {
77736
- offset++;
77737
- } else if (source.startsWith("/*", offset)) {
77738
- const end = source.indexOf("*/", offset + 2);
77739
- offset = end === -1 ? source.length : end + 2;
77740
- } else {
77741
- break;
77742
- }
77743
- }
77744
- };
77745
- const string = () => {
77746
- const quote = source[offset++];
77747
- const start = offset;
77748
- while (offset < source.length && source[offset] !== quote) {
77749
- offset += source[offset] === "\\" ? 2 : 1;
77750
- }
77751
- const value = source.slice(start, offset);
77752
- offset++;
77753
- return value;
77754
- };
77755
- const add = (value, start) => {
77756
- while (nextNewline !== -1 && nextNewline < start) {
77757
- line++;
77758
- lineStart = nextNewline + 1;
77759
- nextNewline = source.indexOf("\n", lineStart);
77760
- }
77761
- const column = start - lineStart + 1;
77762
- (importing ? imports : urls).push({ value, line, column });
77763
- importing = false;
77764
- };
77765
- while (offset < source.length) {
77766
- skipSpace();
77767
- const start = offset;
77768
- const char = source[offset];
77769
- if (char === '"' || char === "'") {
77770
- const value = string();
77771
- if (importing || ["image-set", "-webkit-image-set"].includes(functions.at(-1))) {
77772
- add(value, start);
77773
- }
77774
- continue;
77775
- }
77776
- if (source.slice(offset, offset + 7).toLowerCase() === "@import" && !/[\w-]/.test(source[offset + 7] ?? "")) {
77777
- offset += 7;
77778
- importing = true;
77779
- continue;
77714
+ if (statement2.type !== "ImportDeclaration") {
77715
+ return [];
77716
+ }
77717
+ return statement2.specifiers.flatMap((specifier) => {
77718
+ if (specifier.type === "ImportDefaultSpecifier") {
77719
+ return ["default"];
77780
77720
  }
77781
- const identifier4 = /^[a-z_-][a-z0-9_-]*/i.exec(source.slice(offset));
77782
- if (identifier4 !== null) {
77783
- offset += identifier4[0].length;
77784
- const name = identifier4[0].toLowerCase();
77785
- if (name === "composes" || name === "composes-with") {
77786
- skipSpace();
77787
- composing = source[offset] === ":";
77788
- } else if (composing && name === "from") {
77789
- importing = true;
77790
- composing = false;
77791
- } else if (importing && name !== "url") {
77792
- importing = false;
77793
- }
77794
- if (source[offset] === "(") {
77795
- offset++;
77796
- if (name === "url") {
77797
- skipSpace();
77798
- const value = source[offset] === '"' || source[offset] === "'" ? string() : source.slice(
77799
- offset,
77800
- source.indexOf(")", offset) === -1 ? source.length : source.indexOf(")", offset)
77801
- ).trim();
77802
- const end = source.indexOf(")", offset);
77803
- offset = end === -1 ? source.length : end + 1;
77804
- add(value, start);
77805
- } else {
77806
- functions.push(name);
77807
- }
77808
- }
77809
- continue;
77721
+ if (specifier.type === "ImportNamespaceSpecifier") {
77722
+ return ["*"];
77810
77723
  }
77811
- if (char === ")") {
77812
- functions.pop();
77813
- } else if (char === ";" || char === "{" || char === "}") {
77814
- importing = false;
77815
- composing = false;
77724
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type") {
77725
+ return [specifier.imported.name ?? specifier.imported.value];
77816
77726
  }
77817
- offset++;
77818
- }
77819
- return { urls, imports };
77727
+ return [];
77728
+ });
77820
77729
  }
77821
77730
 
77822
77731
  // scripts/lib/runtime-build/source-module.mjs
@@ -100373,7 +100282,7 @@ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
100373
100282
  import { spawnSync as spawnSync2 } from "node:child_process";
100374
100283
  import { mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, realpathSync as realpathSync2, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "node:fs";
100375
100284
  import { tmpdir as tmpdir2 } from "node:os";
100376
- import { basename as basename9, dirname as dirname4, join as join12, relative as relative5 } from "node:path";
100285
+ import { basename as basename5, dirname as dirname4, join as join10, relative as relative5 } from "node:path";
100377
100286
 
100378
100287
  // scripts/lib/workflow-script/compile.mjs
100379
100288
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
@@ -100385,7 +100294,9 @@ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
100385
100294
  function nativePlatformSuffix({
100386
100295
  platform = process.platform,
100387
100296
  arch = process.arch,
100388
- glibcVersionRuntime = process.report.getReport().header.glibcVersionRuntime
100297
+ glibcVersionRuntime = (globalThis[/* @__PURE__ */ Symbol.for("diagonal.nativePlatformSuffix.glibcVersionRuntime")] ??= {
100298
+ value: process.report.getReport().header.glibcVersionRuntime
100299
+ }).value
100389
100300
  } = {}) {
100390
100301
  const parts = [platform, arch];
100391
100302
  if (platform === "linux") {
@@ -100489,10 +100400,15 @@ function compilerBinary() {
100489
100400
  ensureExecutable(binary);
100490
100401
  return binary;
100491
100402
  }
100403
+ var packagedBun = null;
100492
100404
  function bunBinary() {
100493
100405
  if (process.env.RUNTIME_BUN_BINARY) {
100494
100406
  return process.env.RUNTIME_BUN_BINARY;
100495
100407
  }
100408
+ packagedBun ??= packagedBunBinary();
100409
+ return packagedBun;
100410
+ }
100411
+ function packagedBunBinary() {
100496
100412
  const require2 = createRequire2(import.meta.url);
100497
100413
  try {
100498
100414
  return require2.resolve(`${bunPackage(nativePlatformSuffix())}/bin/bun`);
@@ -100538,14 +100454,17 @@ function stripTypes(files) {
100538
100454
  }
100539
100455
  return runCompiler({ strips: files }).stripResults;
100540
100456
  }
100541
- function runCompiler(input, args = [], { timeout } = {}) {
100457
+ function checkWorkspace(check2) {
100458
+ return runCompiler({ workspaceCheck: check2 }, [], { bun: false }).workspaceCheck;
100459
+ }
100460
+ function runCompiler(input, args = [], { timeout, bun = true } = {}) {
100542
100461
  const run = spawnSync(compilerBinary(), args, {
100543
100462
  input: JSON.stringify(input),
100544
100463
  encoding: "utf8",
100545
100464
  maxBuffer: 256 * 1024 * 1024,
100546
100465
  timeout,
100547
100466
  killSignal: "SIGKILL",
100548
- env: { ...process.env, RUNTIME_BUN_BINARY: bunBinary() }
100467
+ env: bun ? { ...process.env, RUNTIME_BUN_BINARY: bunBinary() } : process.env
100549
100468
  });
100550
100469
  if (run.error !== void 0) {
100551
100470
  throw run.error;
@@ -100559,8 +100478,8 @@ function runCompiler(input, args = [], { timeout } = {}) {
100559
100478
  // scripts/lib/runtime-build/app-modules.mjs
100560
100479
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
100561
100480
  var import_sucrase = __toESM(require_dist3(), 1);
100562
- import { readFileSync as readFileSync8 } from "node:fs";
100563
- import { join as join10 } from "node:path";
100481
+ import { readFileSync as readFileSync6 } from "node:fs";
100482
+ import { join as join8 } from "node:path";
100564
100483
 
100565
100484
  // packages/cli/index.js
100566
100485
  var cli_exports = {};
@@ -100703,610 +100622,856 @@ function styleModuleExpression(path) {
100703
100622
  return path === null ? "{}" : `__appStyleModule(${JSON.stringify(path)})`;
100704
100623
  }
100705
100624
 
100706
- // scripts/lib/runtime-build/module-graph.mjs
100707
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
100708
- import { readFileSync as readFileSync7 } from "node:fs";
100709
- import { posix as posix2, join as join9 } from "node:path";
100710
-
100711
- // scripts/lib/runtime-build/page-build-protocol.mjs
100712
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
100713
- import { createHash } from "node:crypto";
100714
- var PROFILE = Object.freeze({ target: "runtime-esm", version: 1 });
100715
- var MAX_SOURCE_BYTES = 50 * 1024 * 1024;
100716
- function sha256(value) {
100717
- return createHash("sha256").update(value).digest("hex");
100625
+ // scripts/lib/runtime-build/app-modules.mjs
100626
+ var APP_IMPORT = "__appImport";
100627
+ var PRELUDE_SKIPPED_KINDS = /* @__PURE__ */ new Set(["host", "package", "style", "style_module", "binary"]);
100628
+ var AUTHORING_HELPERS_SOURCE = objectLiteral(cli_exports);
100629
+ var AUTHORING_HELPERS_MODULE = Object.entries(cli_exports).map(([name, value]) => `export const ${name} = ${helperSource(value)};
100630
+ `).join("");
100631
+ function helperSource(value) {
100632
+ if (typeof value === "function") {
100633
+ return String(value);
100634
+ }
100635
+ return value !== null && typeof value === "object" ? objectLiteral(value) : JSON.stringify(value);
100718
100636
  }
100719
-
100720
- // scripts/lib/runtime-build/permission-references.mjs
100721
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
100722
- import { basename as basename5, extname } from "node:path";
100723
- var PERMISSIONS_DIRECTORY = "permissions";
100724
- var LEGACY_PERMISSIONS_PATH = "permissions.ts";
100725
- var GENERATED_PERMISSIONS_PATH = "generated/permissions.ts";
100726
- var GENERATED_PERMISSIONS_MODULE = "@app/generated/permissions";
100727
- var PERMISSIONS_EXPORT = "Permissions";
100728
- var SYSTEM_PERMISSIONS_EXPORT = "SystemPermissions";
100729
- var SLUG_PATTERN2 = /^[a-z][a-z0-9_]*$/;
100730
- var OPTIONS = /* @__PURE__ */ new Set(["uid", "slug", "name", "description"]);
100731
- var MAX_LENGTH = 255;
100732
- var systemPermissions = Object.entries(SystemPermissions).map(([constName, permission]) => ({
100733
- constName,
100734
- ...permission
100735
- }));
100736
- var systemBySlug = new Map(systemPermissions.map((permission) => [permission.slug, permission]));
100737
- var systemByName = new Map(systemPermissions.map((permission) => [permission.name, permission]));
100738
- var systemByUid = new Map(systemPermissions.map((permission) => [permission.uid, permission]));
100739
- var SLUG_RULE2 = `start with a lowercase letter, contain only a-z, 0-9, and _, and have at most ${MAX_LENGTH} characters`;
100740
- function isDefinitionSlug(slug) {
100741
- return SLUG_PATTERN2.test(slug) && slug.length <= MAX_LENGTH;
100637
+ function objectLiteral(entries) {
100638
+ const members = Object.entries(entries).map(([name, value]) => `${name}: ${helperSource(value)}`);
100639
+ return `{ ${members.join(", ")} }`;
100742
100640
  }
100743
- function definitionFileSlug(path, definition, { noun, exportName }) {
100744
- const fileName = basename5(path, extname(path));
100745
- const declared = declaredSlug(definition);
100746
- if (declared.problem !== null) {
100747
- throw new SourceError(declared.problem, declared.node);
100748
- }
100749
- if (!isDefinitionSlug(fileName)) {
100750
- const role = declared.slug === null ? `is the slug of the ${noun}` : `gives the ${exportName} name of the ${noun}`;
100751
- throw new SourceError(`The file name "${fileName}" ${role}, so it must ${SLUG_RULE2}`, null);
100752
- }
100753
- if (declared.slug !== null && !isDefinitionSlug(declared.slug)) {
100754
- throw new SourceError(`The "slug" of the ${noun} is "${declared.slug}". A slug must ${SLUG_RULE2}`, declared.node);
100755
- }
100756
- return { slug: declared.slug ?? fileName, name: studlyName(fileName) };
100641
+ function isAppSpecifier(specifier) {
100642
+ return specifier.startsWith(APP_PREFIX);
100757
100643
  }
100758
- function refuseUnknownOptions2(value, definition, options, noun, slug) {
100759
- for (const option of Object.keys(value)) {
100760
- if (options.has(option)) {
100644
+ function resolveAppSpecifier(root, specifier) {
100645
+ return isAppSpecifier(specifier) ? resolveLocalSpecifier(root, "", specifier) : null;
100646
+ }
100647
+ function namesWorkspaceFile(specifier, ui) {
100648
+ return isAppSpecifier(specifier) || ui && importKind(specifier) === "app";
100649
+ }
100650
+ function appImportsOf(root, path, ast, { ui = false } = {}) {
100651
+ const imports = [];
100652
+ for (const statement2 of ast.program.body) {
100653
+ if (statement2.type !== "ImportDeclaration" || !namesWorkspaceFile(statement2.source.value, ui)) {
100761
100654
  continue;
100762
100655
  }
100763
- throw new SourceError(`Unknown option "${option}" of ${noun} "${slug}"`, propertyNode(definition, option) ?? definition);
100656
+ const target = resolveLocalSpecifier(root, path, statement2.source.value);
100657
+ if (target === null) {
100658
+ const suggestion = suggestedRelativeSpecifier(root, path, statement2.source.value);
100659
+ const message = isAppSpecifier(statement2.source.value) ? `Cannot find "${statement2.source.value}". An @app/ import names a file from the workspace root, such as @app/lib/format` : `Cannot find "${statement2.source.value}" from ${path}`;
100660
+ throw new SourceError(
100661
+ suggestion === null || suggestion === statement2.source.value ? message : `${message}. Use "${suggestion}"`,
100662
+ statement2.source
100663
+ );
100664
+ }
100665
+ const testSource = testSourceImportMessage(path, target);
100666
+ if (testSource !== null) {
100667
+ throw new SourceError(testSource, statement2.source);
100668
+ }
100669
+ imports.push({ statement: statement2, specifier: statement2.source.value, path: target, from: path });
100764
100670
  }
100671
+ return imports;
100765
100672
  }
100766
- function definePermissionArgument(ast) {
100767
- const { declaration } = defaultExportOf(ast);
100768
- return expectDefineCall(declaration, "definePermission", 1)[0];
100673
+ function appBindings(source, imports) {
100674
+ return imports.map(({ statement: statement2, path }) => ({
100675
+ start: statement2.start,
100676
+ end: statement2.end,
100677
+ text: bindingFor(statement2, path),
100678
+ original: sliceOf(source, statement2)
100679
+ }));
100769
100680
  }
100770
- function buildPermission(path, definition) {
100771
- const { slug, name } = definitionFileSlug(path, definition, { noun: "permission", exportName: PERMISSIONS_EXPORT });
100772
- if (definition.type !== "ObjectExpression") {
100773
- throw new SourceError("definePermission(...) takes an object literal", definition);
100774
- }
100775
- const value = staticValue(definition);
100776
- if (!isPlainObject2(value)) {
100777
- throw new SourceError("definePermission(...) takes an object literal", definition);
100778
- }
100779
- refuseUnknownOptions2(value, definition, OPTIONS, "permission", slug);
100780
- if (typeof value.name !== "string" || value.name.trim() === "" || value.name.length > MAX_LENGTH) {
100781
- throw new SourceError(
100782
- `Permission "${slug}" needs a "name" of 1 to ${MAX_LENGTH} characters`,
100783
- definition
100784
- );
100785
- }
100786
- const description = value.description ?? null;
100787
- if (description !== null && typeof description !== "string") {
100788
- throw new SourceError(
100789
- `The "description" of permission "${slug}" must be a string`,
100790
- propertyNode(definition, "description")
100791
- );
100681
+ function bindingFor(statement2, path) {
100682
+ if (statement2.importKind === "type") {
100683
+ return "";
100792
100684
  }
100793
- return {
100794
- key: slug,
100795
- name,
100796
- uid: null,
100797
- slug,
100798
- label: value.name,
100799
- description,
100800
- path,
100801
- node: definition
100802
- };
100803
- }
100804
- function checkPermissions(permissions, diagnostics) {
100805
- for (const permission of permissions) {
100806
- const system = systemBySlug.get(permission.slug);
100807
- if (system !== void 0) {
100808
- diagnostics.push(
100809
- diagnosticAt(
100810
- permission.path,
100811
- null,
100812
- `Permission "${permission.slug}": "${permission.slug}" is the slug of the system permission ${SYSTEM_PERMISSIONS_EXPORT}.${system.constName}. Name it with ${SYSTEM_PERMISSIONS_EXPORT}.${system.constName}.uid from ${AUTHORING_MODULE}, or give this permission another slug`
100813
- )
100814
- );
100815
- }
100816
- const systemName = systemByName.get(permission.label);
100817
- if (systemName !== void 0) {
100818
- diagnostics.push(
100819
- diagnosticAt(
100820
- permission.path,
100821
- permission.node,
100822
- `Permission "${permission.slug}": "${permission.label}" is the name of the system permission ${SYSTEM_PERMISSIONS_EXPORT}.${systemName.constName}. Give this permission another name`
100823
- )
100685
+ const load = `${APP_IMPORT}(${JSON.stringify(path)})`;
100686
+ const named = [];
100687
+ const statements2 = [];
100688
+ for (const specifier of statement2.specifiers) {
100689
+ if (specifier.type === "ImportDefaultSpecifier") {
100690
+ statements2.push(`const ${specifier.local.name} = ${load}.default;`);
100691
+ } else if (specifier.type === "ImportNamespaceSpecifier") {
100692
+ statements2.push(`const ${specifier.local.name} = ${load};`);
100693
+ } else if (specifier.importKind !== "type") {
100694
+ const imported = specifier.imported.type === "StringLiteral" ? JSON.stringify(specifier.imported.value) : specifier.imported.name;
100695
+ named.push(
100696
+ imported === specifier.local.name ? imported : `${imported}: ${specifier.local.name}`
100824
100697
  );
100825
100698
  }
100826
100699
  }
100827
- checkDuplicateDefinitions(permissions, "permissions", PERMISSIONS_EXPORT, diagnostics);
100700
+ if (named.length > 0) {
100701
+ statements2.push(`const { ${named.join(", ")} } = ${load};`);
100702
+ }
100703
+ if (statements2.length === 0) {
100704
+ statements2.push(`${load};`);
100705
+ }
100706
+ return statements2.join(" ");
100828
100707
  }
100829
- function checkDuplicateDefinitions(definitions, plural2, exportName, diagnostics) {
100830
- const firstBySlug = /* @__PURE__ */ new Map();
100831
- const firstByName = /* @__PURE__ */ new Map();
100832
- const firstByLabel = /* @__PURE__ */ new Map();
100833
- for (const definition of definitions) {
100834
- const sameSlug = firstBySlug.get(definition.slug);
100835
- if (sameSlug !== void 0) {
100836
- diagnostics.push(
100837
- diagnosticAt(
100838
- definition.path,
100839
- definition.node,
100840
- `The ${plural2} ${sameSlug.path} and ${definition.path} have the same slug "${definition.slug}". Change one of them`,
100841
- { relatedPath: sameSlug.path }
100842
- )
100843
- );
100708
+ function appModuleClosure(root, imports, external = /* @__PURE__ */ new Set(), { ui = false, transform: transform3 = null } = {}) {
100709
+ const modules = /* @__PURE__ */ new Map();
100710
+ const pending = imports.map((item) => item.path);
100711
+ while (pending.length > 0) {
100712
+ const path = pending.shift();
100713
+ if (modules.has(path)) {
100844
100714
  continue;
100845
100715
  }
100846
- firstBySlug.set(definition.slug, definition);
100847
- for (const [first, value, label] of [
100848
- [firstByName, definition.name, `name ${exportName}.${definition.name}`],
100849
- [firstByLabel, definition.label, `name "${definition.label}"`]
100850
- ]) {
100851
- const other = first.get(value);
100852
- if (other === void 0) {
100853
- first.set(value, definition);
100716
+ const read2 = readFileSync6(join8(root, path), "utf8");
100717
+ const source = transform3 === null ? read2 : transform3(path, read2);
100718
+ const ast = parseModule(path, source);
100719
+ const requires = {};
100720
+ const foreign = {};
100721
+ const references = ui ? moduleSpecifiers(ast).filter((item) => item.specifier !== null && !item.typeOnly).map((item) => ({ specifier: item.specifier, source: item.node })) : ast.program.body.filter(
100722
+ (statement2) => statement2.type === "ImportDeclaration" || statement2.type === "ExportAllDeclaration" || statement2.type === "ExportNamedDeclaration"
100723
+ ).map((statement2) => ({ specifier: statement2.source?.value, source: statement2.source }));
100724
+ for (const statement2 of references) {
100725
+ const specifier = statement2.specifier;
100726
+ if (specifier === void 0 || isAuthoringModule(specifier) || external.has(specifier)) {
100854
100727
  continue;
100855
100728
  }
100856
- diagnostics.push(
100857
- diagnosticAt(
100858
- definition.path,
100859
- definition.node,
100860
- `The ${plural2} "${other.slug}" and "${definition.slug}" have the same ${label}. Change one of them`,
100861
- { relatedPath: other.path }
100862
- )
100863
- );
100864
- }
100865
- }
100866
- }
100867
- function checkPermissionUids(permissions, diagnostics) {
100868
- for (const permission of permissions) {
100869
- const system = permission.uid === null ? void 0 : systemByUid.get(permission.uid);
100870
- if (system !== void 0) {
100871
- diagnostics.push(
100872
- diagnosticAt(
100873
- permission.path,
100874
- permission.node,
100875
- `Permission "${permission.slug}" has the uid of the system permission ${SYSTEM_PERMISSIONS_EXPORT}.${system.constName}. Give it a new uid`
100876
- )
100877
- );
100729
+ const kind = importKind(specifier);
100730
+ if (ui && PRELUDE_SKIPPED_KINDS.has(kind)) {
100731
+ const value = foreignValue(root, path, specifier, kind);
100732
+ if (value !== null) {
100733
+ foreign[specifier] = value;
100734
+ }
100735
+ continue;
100736
+ }
100737
+ if (ui && unsupportedImportMessage(specifier, kind) !== null) {
100738
+ continue;
100739
+ }
100740
+ if (!namesWorkspaceFile(specifier, ui)) {
100741
+ throw new SourceError(
100742
+ `${path} imports "${specifier}". A workspace module can import only ${[AUTHORING_MODULE, ...external].map((name) => `"${name}"`).join(", ")}, and @app/ files`,
100743
+ statement2.source
100744
+ );
100745
+ }
100746
+ const target = resolveLocalSpecifier(root, path, specifier);
100747
+ if (target === null) {
100748
+ if (ui) {
100749
+ continue;
100750
+ }
100751
+ throw new SourceError(
100752
+ `${path} imports "${specifier}", which does not exist`,
100753
+ statement2.source
100754
+ );
100755
+ }
100756
+ const testSource = testSourceImportMessage(path, target);
100757
+ if (testSource !== null) {
100758
+ throw new SourceError(testSource, statement2.source);
100759
+ }
100760
+ requires[specifier] = target;
100761
+ pending.push(target);
100878
100762
  }
100763
+ modules.set(path, {
100764
+ source,
100765
+ requires,
100766
+ foreign,
100767
+ pagesNames: ui ? pagesSdkNames(ast) : []
100768
+ });
100879
100769
  }
100770
+ return modules;
100880
100771
  }
100881
- function definitionEntries(definitions) {
100882
- const entries = /* @__PURE__ */ Object.create(null);
100883
- for (const definition of definitions.toSorted(
100884
- (left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0
100885
- )) {
100886
- entries[definition.name] = {
100887
- uid: definition.uid,
100888
- slug: definition.slug,
100889
- name: definition.label
100890
- };
100772
+ function foreignValue(root, path, specifier, kind) {
100773
+ switch (kind) {
100774
+ case "package":
100775
+ return `{ __esModule: true, ...${packageExpression(specifier)} }`;
100776
+ case "style_module":
100777
+ return styleModuleExpression(resolveLocalSpecifier(root, path, specifier));
100778
+ case "style":
100779
+ return "{}";
100780
+ default:
100781
+ return null;
100891
100782
  }
100892
- return entries;
100893
- }
100894
- function generatedPermissionsSource(entries) {
100895
- return generatedModuleSource(PERMISSIONS_EXPORT, entries);
100896
- }
100897
- function permissionValues(entries) {
100898
- return { entries, exportName: PERMISSIONS_EXPORT, noun: "permission", directory: "permissions/", exampleMember: "uid" };
100899
- }
100900
- function knownPermissionUids(permissions) {
100901
- return /* @__PURE__ */ new Set([
100902
- ...systemByUid.keys(),
100903
- ...permissions.map((permission) => permission.uid).filter((uid2) => uid2 !== null)
100904
- ]);
100905
100783
  }
100906
- function permissionReferenceProblem(reference, permissions) {
100907
- const system = systemBySlug.get(reference);
100908
- if (system !== void 0) {
100909
- return `"${reference}" is the slug of a system permission. Use ${SYSTEM_PERMISSIONS_EXPORT}.${system.constName}.uid from ${AUTHORING_MODULE}`;
100910
- }
100911
- const declared = permissions.find((permission) => permission.slug === reference);
100912
- if (declared !== void 0) {
100913
- return `"${reference}" is the slug of a permission. Use ${PERMISSIONS_EXPORT}.${declared.name}.uid from ${GENERATED_PERMISSIONS_MODULE}`;
100914
- }
100915
- return `Unknown permission "${reference}". Use ${PERMISSIONS_EXPORT}.<Name>.uid from ${GENERATED_PERMISSIONS_MODULE}, or ${SYSTEM_PERMISSIONS_EXPORT}.<Name>.uid from ${AUTHORING_MODULE}`;
100784
+ function pagesSdkNames(ast) {
100785
+ return moduleSpecifiers(ast).filter((item) => item.specifier === PAGES_SDK_MODULE && !item.typeOnly).flatMap((item) => item.dynamic ? ["*"] : requestedNames(item.statement));
100916
100786
  }
100917
- function permissionsBinding(ast, entries) {
100918
- const bindings = [];
100919
- const declared = generatedBindingLocal(ast, GENERATED_PERMISSIONS_MODULE, PERMISSIONS_EXPORT);
100920
- const system = generatedBindingLocal(ast, AUTHORING_MODULE, SYSTEM_PERMISSIONS_EXPORT);
100921
- if (declared !== null) {
100922
- bindings.push({
100923
- local: declared,
100924
- entries: entries ?? /* @__PURE__ */ Object.create(null),
100925
- source: `${PERMISSIONS_DIRECTORY}/`
100926
- });
100927
- }
100928
- if (system !== null) {
100929
- bindings.push({ local: system, entries: SystemPermissions, source: AUTHORING_MODULE });
100787
+ function parseModule(path, source) {
100788
+ try {
100789
+ return parseSource(source, { jsx: path.endsWith("x") });
100790
+ } catch (error) {
100791
+ throw new SourceError(`${path} does not parse: ${error.message}`, null);
100930
100792
  }
100931
- return bindings.length === 0 ? null : bindings;
100932
100793
  }
100933
- function menuPermissionSlugWarnings(path, ast, entries) {
100934
- const declaration = ast.program.body.find((statement2) => statement2.type === "ExportDefaultDeclaration")?.declaration;
100935
- const menu = declaration?.type === "CallExpression" ? declaration.arguments[0] : null;
100936
- const context = menu?.params?.[0];
100937
- if (context?.type !== "Identifier") {
100938
- return [];
100794
+ function appPrelude(modules) {
100795
+ if (modules.size === 0) {
100796
+ return "";
100939
100797
  }
100940
- const references = new Map([
100941
- ...systemPermissions.map((permission) => [
100942
- permission.slug,
100943
- { reference: `${SYSTEM_PERMISSIONS_EXPORT}.${permission.constName}.uid`, module: AUTHORING_MODULE }
100944
- ]),
100945
- ...Object.entries(entries).map(([name, entry]) => [
100946
- entry.slug,
100947
- { reference: `${PERMISSIONS_EXPORT}.${name}.uid`, module: GENERATED_PERMISSIONS_MODULE }
100948
- ])
100949
- ]);
100950
- const slugMembers = new Map(
100951
- (permissionsBinding(ast, entries) ?? []).map((binding) => [binding.local, binding.entries])
100952
- );
100953
- const slugOf = (argument) => {
100954
- if (argument?.type === "StringLiteral") {
100955
- return argument.value;
100798
+ const hasForeign = [...modules.values()].some((module) => Object.keys(module.foreign ?? {}).length > 0);
100799
+ const entries = [...modules].map(([path, module]) => {
100800
+ const code2 = compileModule(path, module.source);
100801
+ const foreign = Object.entries(module.foreign ?? {}).map(([specifier, value]) => `${JSON.stringify(specifier)}: () => (${value})`);
100802
+ const foreignEntry = hasForeign ? `, { ${foreign.join(", ")} }` : "";
100803
+ return `${JSON.stringify(path)}: [function (exports, require, module) {
100804
+ ${code2}
100805
+ }, ${JSON.stringify(module.requires)}${foreignEntry}]`;
100806
+ });
100807
+ const foreignRequire = hasForeign ? `
100808
+ if (foreign[specifier] !== undefined) {
100809
+ return foreign[specifier]();
100810
+ }
100811
+ ` : "";
100812
+ const pagesNames = new Set([...modules.values()].flatMap((module) => module.pagesNames));
100813
+ const pagesSdk = pagesNames.has("*") ? pagesSdkObjectText() : pagesSdkObjectText([...pagesNames].toSorted());
100814
+ return `const ${APP_IMPORT} = ((modules, outer) => {
100815
+ const cache = {};
100816
+ const runtime = ${AUTHORING_HELPERS_SOURCE};
100817
+ const pagesSdk = typeof Sdk === 'undefined' ? null : ${pagesSdk};
100818
+ const load = (path) => {
100819
+ if (cache[path] !== undefined) {
100820
+ return cache[path].exports;
100956
100821
  }
100957
- const segments = memberPathSegments(argument);
100958
- const bindingEntries = segments?.length === 3 && segments[2] === "slug" ? slugMembers.get(segments[0]) : void 0;
100959
- return bindingEntries !== void 0 && Object.hasOwn(bindingEntries, segments[1]) ? bindingEntries[segments[1]].slug : null;
100822
+
100823
+ const [factory, requires${hasForeign ? ", foreign" : ""}] = modules[path];
100824
+ const module = { exports: {} };
100825
+ cache[path] = module;
100826
+ const require = (specifier) => {${foreignRequire}
100827
+ if (specifier === ${JSON.stringify(AUTHORING_MODULE)}) {
100828
+ return runtime;
100829
+ }
100830
+
100831
+ if (specifier === ${JSON.stringify(PAGES_SDK_MODULE)} && pagesSdk !== null) {
100832
+ return pagesSdk;
100833
+ }
100834
+
100835
+ if (specifier === 'react' && typeof React !== 'undefined') {
100836
+ return React;
100837
+ }
100838
+
100839
+ return requires[specifier] === undefined ? outer(specifier) : load(requires[specifier]);
100840
+ };
100841
+ factory(module.exports, require, module);
100842
+
100843
+ return module.exports;
100960
100844
  };
100961
- const warnings2 = [];
100962
- const pending = [menu.body];
100963
- while (pending.length > 0) {
100964
- const current = pending.pop();
100965
- pending.push(...childNodes(current));
100966
- const callee = current.type === "CallExpression" ? current.callee : null;
100967
- const argument = current.arguments?.[0];
100968
- if (callee?.type !== "MemberExpression" || callee.computed || callee.object.type !== "Identifier" || callee.object.name !== context.name || callee.property.name !== "can") {
100969
- continue;
100970
- }
100971
- const slug = slugOf(argument);
100972
- if (slug === null || !references.has(slug)) {
100973
- continue;
100974
- }
100975
- const { reference, module } = references.get(slug);
100976
- warnings2.push(generatedReferenceDiagnostic(path, argument, reference, module));
100845
+
100846
+ return load;
100847
+ })({
100848
+ ${entries.join(",\n")}
100849
+ }, typeof require === 'function' ? require : (specifier) => { throw new Error(\`Cannot import \${specifier}.\`); });
100850
+ `;
100851
+ }
100852
+ function compileModule(path, source) {
100853
+ try {
100854
+ return (0, import_sucrase.transform)(source, {
100855
+ transforms: path.endsWith("x") ? ["typescript", "jsx", "imports"] : ["typescript", "imports"],
100856
+ jsxPragma: "React.createElement",
100857
+ jsxFragmentPragma: "React.Fragment",
100858
+ production: true,
100859
+ filePath: path
100860
+ }).code;
100861
+ } catch (error) {
100862
+ throw new SourceError(`${path} does not compile: ${error.message}`, null);
100977
100863
  }
100978
- return warnings2;
100979
100864
  }
100980
100865
 
100981
- // scripts/lib/runtime-build/role-references.mjs
100866
+ // scripts/lib/runtime-build/script-sdk.mjs
100982
100867
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
100983
- var ROLES_DIRECTORY = "roles";
100984
- var LEGACY_ROLES_PATH = "roles.ts";
100985
- var GENERATED_ROLES_PATH = "generated/roles.ts";
100986
- var ROLES_EXPORT = "Roles";
100987
- var SYSTEM_ROLES_EXPORT = "SystemRoles";
100988
- var OPTIONS2 = /* @__PURE__ */ new Set(["uid", "slug", "name", "description", "resource", "permissions"]);
100989
- var MAX_LENGTH2 = 255;
100990
- var systemRoles = Object.entries(SystemRoles).map(([constName, role]) => ({
100991
- constName,
100992
- ...role
100993
- }));
100994
- var systemBySlug2 = new Map(systemRoles.map((role) => [role.slug, role]));
100995
- var systemByName2 = new Map(systemRoles.map((role) => [role.name, role]));
100996
- var systemByUid2 = new Map(systemRoles.map((role) => [role.uid, role]));
100997
- function defineRoleArgument(ast) {
100998
- const { declaration } = defaultExportOf(ast, {
100999
- extraImports: [GENERATED_RESOURCES_MODULE, GENERATED_PERMISSIONS_MODULE]
101000
- });
101001
- return expectDefineCall(declaration, "defineRole", 1)[0];
100868
+ import { readFileSync as readFileSync7, readdirSync as readdirSync3, statSync as statSync4 } from "node:fs";
100869
+ import { createRequire as createRequire3 } from "node:module";
100870
+ import { dirname as dirname3, join as join9, relative as relative4, resolve as resolve4 } from "node:path";
100871
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
100872
+ var SCRIPT_SDK_ROOT = resolve4(
100873
+ dirname3(fileURLToPath2(import.meta.url)),
100874
+ "../../../packages/workflows/src"
100875
+ );
100876
+ var SDK_RUNTIME_ENTRY_POINTS = {
100877
+ workflow: join9(SCRIPT_SDK_ROOT, "index.ts"),
100878
+ testing: join9(SCRIPT_SDK_ROOT, "testing/index.ts"),
100879
+ "quickjs-testing": fileURLToPath2(new URL("./quickjs-testing.mjs", import.meta.url))
100880
+ };
100881
+ function walk(directory) {
100882
+ return readdirSync3(directory).flatMap(
100883
+ (name) => statSync4(join9(directory, name)).isDirectory() ? walk(join9(directory, name)) : [join9(directory, name)]
100884
+ );
101002
100885
  }
101003
- function systemRoleMessage(slug, what, system) {
101004
- return `Role "${slug}" has the ${what} of the system role ${SYSTEM_ROLES_EXPORT}.${system.constName}. The platform declares that role, and it holds every permission, so do not declare it. Give this role another ${what}`;
100886
+ function readSandboxSdkFiles() {
100887
+ return Object.fromEntries(
100888
+ walk(SCRIPT_SDK_ROOT).filter(
100889
+ (file2) => file2.endsWith(".ts") && !file2.includes("/testing/") && !file2.endsWith("/http-transport.ts") && !file2.endsWith("/workspace.generated.ts")
100890
+ ).map((file2) => [`/sdk/${relative4(SCRIPT_SDK_ROOT, file2)}`, readFileSync7(file2, "utf8")])
100891
+ );
101005
100892
  }
101006
- function buildRole(path, definition, bindings, known, diagnostics) {
101007
- const { slug, name } = definitionFileSlug(path, definition, { noun: "role", exportName: ROLES_EXPORT });
101008
- if (definition.type !== "ObjectExpression") {
101009
- throw new SourceError("defineRole(...) takes an object literal", definition);
101010
- }
101011
- const { value } = staticObject(definition, {
101012
- resources: bindings.resources,
101013
- permissions: bindings.permissions
100893
+ function bundleQuickJsSdkRuntime(buildSync) {
100894
+ const result = buildSync({
100895
+ entryPoints: [join9(SCRIPT_SDK_ROOT, "runtime/quickjs.ts")],
100896
+ bundle: true,
100897
+ write: false,
100898
+ format: "esm",
100899
+ target: "es2023",
100900
+ platform: "neutral",
100901
+ logLevel: "silent"
101014
100902
  });
101015
- if (!isPlainObject2(value)) {
101016
- throw new SourceError("defineRole(...) takes an object literal", definition);
101017
- }
101018
- refuseUnknownOptions2(value, definition, OPTIONS2, "role", slug);
101019
- if (typeof value.name !== "string" || value.name.trim() === "" || value.name.length > MAX_LENGTH2) {
101020
- throw new SourceError(
101021
- `Role "${slug}" needs a "name" of 1 to ${MAX_LENGTH2} characters`,
101022
- definition
101023
- );
101024
- }
101025
- const description = value.description ?? null;
101026
- if (description !== null && typeof description !== "string") {
101027
- throw new SourceError(
101028
- `The "description" of role "${slug}" must be a string`,
101029
- propertyNode(definition, "description")
101030
- );
101031
- }
101032
- const resource = value.resource ?? null;
101033
- const resourceNode = propertyNode(definition, "resource");
101034
- if (resource !== null && typeof resource !== "string") {
101035
- throw new SourceError(
101036
- `The "resource" of role "${slug}" must be Resources.<Name>.slug`,
101037
- resourceNode
101038
- );
101039
- }
101040
- const permissions = value.permissions;
101041
- const permissionsNode = propertyNode(definition, "permissions");
101042
- if (!Array.isArray(permissions)) {
101043
- throw new SourceError(
101044
- `Role "${slug}" needs "permissions": a list of Permissions.<Name>.uid or SystemPermissions.<Name>.uid. Use [] for a role that grants no permission`,
101045
- permissionsNode ?? definition
101046
- );
101047
- }
101048
- const role = {
101049
- key: slug,
101050
- name,
101051
- uid: null,
101052
- slug,
101053
- label: value.name,
101054
- description,
101055
- resource,
101056
- permissions,
101057
- path,
101058
- node: definition
101059
- };
101060
- checkRoleResource(role, resourceNode, known, diagnostics);
101061
- checkRolePermissions(
101062
- role,
101063
- permissionsNode,
101064
- knownPermissionUids(known.permissions),
101065
- known.permissions,
101066
- diagnostics
100903
+ return result.outputFiles[0].text;
100904
+ }
100905
+ function bundleSdkRuntime(buildSync) {
100906
+ const result = buildSync({
100907
+ entryPoints: SDK_RUNTIME_ENTRY_POINTS,
100908
+ outdir: "/sdk",
100909
+ bundle: true,
100910
+ splitting: true,
100911
+ platform: "node",
100912
+ target: "node24",
100913
+ format: "esm",
100914
+ define: { __SDK_RUNTIME__: JSON.stringify(bundleQuickJsSdkRuntime(buildSync)) },
100915
+ write: false,
100916
+ logLevel: "silent"
100917
+ });
100918
+ return Object.fromEntries(
100919
+ result.outputFiles.map((file2) => [relative4("/sdk", file2.path), file2.text])
101067
100920
  );
101068
- return role;
101069
100921
  }
101070
- function checkRoleResource(role, node, known, diagnostics) {
101071
- if (role.resource === null) {
101072
- return;
101073
- }
101074
- const resource = known.resources.find((item) => item.slug === role.resource);
101075
- if (resource === void 0 || BUILT_IN_RESOURCE_SLUGS.has(role.resource)) {
101076
- diagnostics.push(
101077
- diagnosticAt(
101078
- role.path,
101079
- node,
101080
- `The "resource" of role "${role.slug}" is "${role.resource}", which is not a resource of the files. Use Resources.<Name>.slug of an authenticatable resource`
101081
- )
101082
- );
101083
- return;
101084
- }
101085
- if (!Object.hasOwn(resource.capabilities ?? {}, "authenticatable")) {
101086
- diagnostics.push(
101087
- diagnosticAt(
101088
- role.path,
101089
- node,
101090
- `The "resource" of role "${role.slug}" is "${role.resource}", which does not have the authenticatable capability. A role gives its permissions to signed-in records, so name an authenticatable resource`
101091
- )
101092
- );
100922
+ var sdkFiles;
100923
+ var surface = null;
100924
+ try {
100925
+ ({ SDK_FILES: sdkFiles, SDK_SURFACE: surface } = await Promise.resolve().then(() => (init_sdk_files_generated(), sdk_files_generated_exports)));
100926
+ } catch (error) {
100927
+ if (error?.code !== "ERR_MODULE_NOT_FOUND") {
100928
+ throw error;
101093
100929
  }
100930
+ sdkFiles = readSandboxSdkFiles();
101094
100931
  }
101095
- function checkRolePermissions(role, node, permissionUids, permissions, diagnostics) {
101096
- const seen = /* @__PURE__ */ new Set();
101097
- role.permissions.forEach((permission, position) => {
101098
- const permissionNode = elementNode(node, position);
101099
- if (typeof permission !== "string" || !permissionUids.has(permission)) {
101100
- const problem2 = typeof permission === "string" ? permissionReferenceProblem(permission, permissions) : "Use Permissions.<Name>.uid or SystemPermissions.<Name>.uid";
101101
- diagnostics.push(
101102
- diagnosticAt(role.path, permissionNode, `Role "${role.slug}" permissions: ${problem2}`)
101103
- );
101104
- return;
101105
- }
101106
- if (seen.has(permission)) {
101107
- diagnostics.push(
101108
- diagnosticAt(
101109
- role.path,
101110
- permissionNode,
101111
- `Role "${role.slug}" lists the permission "${permission}" twice`
101112
- )
101113
- );
101114
- }
101115
- seen.add(permission);
101116
- });
100932
+ var SDK_SURFACE_MODULE = "../workflow-script/sdk-surface.mjs";
100933
+ var { sdkSurface } = surface === null ? await import(SDK_SURFACE_MODULE) : {};
100934
+ var SCRIPT_SDK_FILES = sdkFiles;
100935
+ function scriptSdkSurface() {
100936
+ surface ??= sdkSurface(SCRIPT_SDK_FILES);
100937
+ return surface;
101117
100938
  }
101118
- function checkRoles(roles, diagnostics) {
101119
- for (const role of roles) {
101120
- const systemSlug = systemBySlug2.get(role.slug);
101121
- if (systemSlug !== void 0) {
101122
- diagnostics.push(
101123
- diagnosticAt(role.path, null, systemRoleMessage(role.slug, "slug", systemSlug))
101124
- );
100939
+ var sdkRuntimeFiles = null;
100940
+ function scriptSdkRuntimeFiles() {
100941
+ sdkRuntimeFiles ??= define_globalThis_DIAGONAL_SDK_RUNTIME_default ?? bundleSdkRuntime(createRequire3(import.meta.url)("esbuild").buildSync);
100942
+ return sdkRuntimeFiles;
100943
+ }
100944
+
100945
+ // scripts/lib/runtime-build/workflow-tests.mjs
100946
+ var WORKFLOW_TEST_STAGE = "workflow test";
100947
+ var TEST_SUFFIX = ".test.ts";
100948
+ var WORKFLOW_TEST_SUBJECT = {
100949
+ noun: "workflow",
100950
+ directory: "workflows",
100951
+ sdk: "@diagonal/workflow",
100952
+ stage: WORKFLOW_TEST_STAGE
100953
+ };
100954
+ var MIGRATION_TEST_SUBJECT = {
100955
+ noun: "migration",
100956
+ directory: "migrations",
100957
+ sdk: "@diagonal/workflow",
100958
+ stage: "migration test"
100959
+ };
100960
+ var TEST_TIMEOUT_MS = 1e4;
100961
+ var RUN_TIMEOUT_MS = 6e4;
100962
+ var RESULT_PREFIX = "\0diagonal-test ";
100963
+ var SDK_MODULES = {
100964
+ "@diagonal/workflow": "sdk/workflow.js",
100965
+ "@diagonal/workflow/testing": "sdk/quickjs-testing.js",
100966
+ "@diagonal/workflow/workspace": "sdk/workspace.js",
100967
+ [AUTHORING_MODULE]: "sdk/runtime.js"
100968
+ };
100969
+ var NODE_TEST_MODULES = /* @__PURE__ */ new Set(["node:test", "node:assert", "node:assert/strict"]);
100970
+ var TEST_MODULE_EXTERNALS = /* @__PURE__ */ new Set([...Object.keys(SDK_MODULES), ...NODE_TEST_MODULES]);
100971
+ var RELATIVE_WORKFLOW = /^\.\/([^/]+?)(?:\.ts|\.js)?$/;
100972
+ var REPORTER_SOURCE = `const PREFIX = ${JSON.stringify(RESULT_PREFIX)};
100973
+ export default async function* reporter(source) {
100974
+ const names = [];
100975
+ for await (const event of source) {
100976
+ const data = event.data;
100977
+ if (event.type === 'test:start') {
100978
+ names.length = data.nesting;
100979
+ names.push(data.name);
100980
+ continue;
101125
100981
  }
101126
- const systemName = systemByName2.get(role.label);
101127
- if (systemName !== void 0) {
101128
- diagnostics.push(
101129
- diagnosticAt(role.path, role.node, systemRoleMessage(role.slug, "name", systemName))
101130
- );
100982
+ if (event.type !== 'test:pass' && event.type !== 'test:fail') {
100983
+ continue;
100984
+ }
100985
+ const error = data.details?.error;
100986
+ if (data.details?.type === 'suite' && (event.type === 'test:pass' || error?.failureType === 'subtestsFailed')) {
100987
+ continue;
101131
100988
  }
100989
+ const path = [...names.slice(0, data.nesting), data.name].join(' > ');
100990
+ const cause = error?.cause ?? error;
100991
+ yield PREFIX + JSON.stringify({
100992
+ file: data.file ?? null,
100993
+ name: path,
100994
+ leaf: data.name,
100995
+ ok: event.type === 'test:pass',
100996
+ message: event.type === 'test:pass' ? null : String(cause?.message ?? cause ?? 'The test failed').trim()
100997
+ }) + '\\n';
101132
100998
  }
101133
- checkDuplicateDefinitions(roles, "roles", ROLES_EXPORT, diagnostics);
101134
100999
  }
101135
- function checkRoleUids(roles, diagnostics) {
101136
- for (const role of roles) {
101137
- const system = role.uid === null ? void 0 : systemByUid2.get(role.uid);
101138
- if (system !== void 0) {
101139
- diagnostics.push(
101140
- diagnosticAt(role.path, role.node, systemRoleMessage(role.slug, "uid", system))
101141
- );
101000
+ `;
101001
+ function moduleSpecifierNodes(ast) {
101002
+ return ast.program.body.filter(
101003
+ (statement2) => (statement2.type === "ImportDeclaration" || statement2.type === "ExportNamedDeclaration" || statement2.type === "ExportAllDeclaration") && statement2.source
101004
+ ).map((statement2) => statement2.source);
101005
+ }
101006
+ function rewriteSpecifiers(source, ast, resolveSpecifier) {
101007
+ let rewritten = source;
101008
+ for (const node of moduleSpecifierNodes(ast).toSorted(
101009
+ (left, right) => right.start - left.start
101010
+ )) {
101011
+ const target = resolveSpecifier(node.value);
101012
+ if (target !== null) {
101013
+ rewritten = `${rewritten.slice(0, node.start)}${JSON.stringify(target)}${rewritten.slice(node.end)}`;
101142
101014
  }
101143
101015
  }
101016
+ return rewritten;
101144
101017
  }
101145
- function generatedRolesSource(entries) {
101146
- return generatedModuleSource(ROLES_EXPORT, entries);
101147
- }
101148
- function roleValues(entries) {
101149
- return { entries, exportName: ROLES_EXPORT, noun: "role", directory: "roles/", exampleMember: "uid" };
101018
+ function sdkSpecifier(fromDirectory) {
101019
+ return (specifier) => Object.hasOwn(SDK_MODULES, specifier) ? `${fromDirectory}${SDK_MODULES[specifier]}` : null;
101150
101020
  }
101151
-
101152
- // scripts/lib/runtime-build/skill-references.mjs
101153
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
101154
- import { basename as basename6 } from "node:path";
101155
- var GENERATED_SKILLS_PATH = "generated/skills.ts";
101156
- var SKILLS_EXPORT = "Skills";
101157
- function skillNames(paths, diagnostics) {
101158
- const pathsByName = /* @__PURE__ */ new Map();
101159
- for (const path of paths.toSorted(byteOrder2)) {
101160
- const name = pathName(
101161
- path,
101162
- basename6(path, ".md"),
101163
- { exportName: SKILLS_EXPORT, label: "skill", showText: false, severity: "warning" },
101164
- diagnostics
101165
- );
101166
- if (name === null) {
101167
- continue;
101021
+ function testCallNode(ast, name) {
101022
+ const pending = [ast.program];
101023
+ while (pending.length > 0) {
101024
+ const node = pending.pop();
101025
+ const [first] = node.type === "CallExpression" ? node.arguments : [];
101026
+ 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) {
101027
+ return node;
101168
101028
  }
101169
- const other = pathsByName.get(name);
101170
- if (other !== void 0) {
101171
- diagnostics.push(
101172
- diagnosticAt(
101173
- path,
101174
- null,
101175
- `The skill files ${other} and ${path} both have the name ${SKILLS_EXPORT}.${name}, so ${SKILLS_EXPORT}.${name} names ${other}. Rename one of the files to give ${path} a name in ${SKILLS_EXPORT}`,
101176
- { severity: "warning" }
101177
- )
101178
- );
101029
+ pending.push(...childNodes(node));
101030
+ }
101031
+ return null;
101032
+ }
101033
+ function importDiagnostics(test, scriptNames, workspaceRoot, subject) {
101034
+ const diagnostics = [];
101035
+ for (const node of moduleSpecifierNodes(test.ast)) {
101036
+ const specifier = node.value;
101037
+ const relative6 = RELATIVE_WORKFLOW.exec(specifier);
101038
+ if (NODE_TEST_MODULES.has(specifier) || Object.hasOwn(SDK_MODULES, specifier) || relative6 !== null && scriptNames.has(relative6[1]) || isAppSpecifier(specifier) && workspaceRoot !== null && resolveAppSpecifier(workspaceRoot, specifier) !== null) {
101179
101039
  continue;
101180
101040
  }
101181
- pathsByName.set(name, path);
101041
+ diagnostics.push(
101042
+ diagnosticAt(
101043
+ test.path,
101044
+ node,
101045
+ `A ${subject.noun} test can import only node:test, node:assert, ${subject.sdk}, @diagonal/workflow/testing, @diagonal/workflow/workspace, the ${subject.noun}s in ${subject.directory}/, and workspace files by @app/. "${specifier}" is not one of them`,
101046
+ { stage: subject.stage }
101047
+ )
101048
+ );
101182
101049
  }
101183
- return pathsByName;
101050
+ return diagnostics;
101184
101051
  }
101185
- function skillEntries(pathsByName, skills) {
101186
- const skillsByPath = new Map(skills.map((skill) => [skill.path, skill]));
101187
- const entries = /* @__PURE__ */ Object.create(null);
101188
- for (const name of [...pathsByName.keys()].toSorted(byteOrder2)) {
101189
- const skill = skillsByPath.get(pathsByName.get(name));
101190
- entries[name] = skill === void 0 ? { uid: null, name: null, description: null } : { uid: skill.uid ?? null, name: skill.name, description: skill.description };
101191
- }
101192
- return entries;
101052
+ function compiledScriptModule(script) {
101053
+ const prefix2 = sandboxPrefix(script.path);
101054
+ const source = JSON.stringify(`./${basename5(script.path, ".ts")}.mjs`);
101055
+ return [
101056
+ `import * as script from ${source};`,
101057
+ `import { registerCompiledScript } from ${JSON.stringify(`${prefix2}sdk/quickjs-testing.js`)};`,
101058
+ `export * from ${source};`,
101059
+ "export default script.default;",
101060
+ `registerCompiledScript(script.default, ${JSON.stringify(script.compiled)}, script.validateInput);`,
101061
+ ""
101062
+ ].join("\n");
101193
101063
  }
101194
- function generatedSkillsSource(entries) {
101195
- return generatedModuleSource(SKILLS_EXPORT, entries);
101064
+ function sandboxPath(path) {
101065
+ return path.replace(/\.(ts|tsx|js|jsx)$/, ".js");
101196
101066
  }
101197
- function skillValues(entries) {
101198
- return { entries, exportName: SKILLS_EXPORT, noun: "skill", directory: "skills/" };
101067
+ function sandboxPrefix(path) {
101068
+ return "../".repeat(path.split("/").length - 1) || "./";
101199
101069
  }
101200
-
101201
- // scripts/lib/runtime-build/notification-references.mjs
101202
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
101203
- var GENERATED_NOTIFICATION_TYPES_PATH = "generated/notification-types.ts";
101204
- var GENERATED_NOTIFICATION_TYPES_MODULE = "@app/generated/notification-types";
101205
- var NOTIFICATION_TYPES_EXPORT = "NotificationTypes";
101206
- var TYPE_PATH = /^notifications\/([^/]+)\/type\.ts$/;
101207
- var TEMPLATE_PATH = /^notifications\/([^/]+)\/([^/]+)\.template\.ts$/;
101208
- var SCHEDULE_PATH = /^notifications\/[^/]+\/[^/]+\.schedule\.ts$/;
101209
- function notificationFolder(path) {
101210
- return path.split("/")[1];
101070
+ function relativeSandboxPath(from, target) {
101071
+ const path = relative5(dirname4(from), sandboxPath(target));
101072
+ return path.startsWith(".") ? path : `./${path}`;
101211
101073
  }
101212
- function isNotificationSchedulePath(path) {
101213
- return SCHEDULE_PATH.test(path);
101074
+ function writeFile(root, path, content) {
101075
+ mkdirSync2(dirname4(join10(root, path)), { recursive: true });
101076
+ writeFileSync4(join10(root, path), content);
101214
101077
  }
101215
- function templateSlugOf(path) {
101216
- return TEMPLATE_PATH.exec(path)[2];
101078
+ function parseResults(stdout) {
101079
+ return stdout.split("\n").filter((line) => line.startsWith(RESULT_PREFIX)).map((line) => JSON.parse(line.slice(RESULT_PREFIX.length)));
101217
101080
  }
101218
- function notificationTypeNames(types2, templates, diagnostics) {
101219
- const names2 = /* @__PURE__ */ new Map();
101220
- const typesByFolder = /* @__PURE__ */ new Map();
101221
- for (const { path, slug = null } of types2.toSorted((left, right) => byteOrder2(left.path, right.path))) {
101222
- const folder = TYPE_PATH.exec(path)[1];
101223
- const name = pathName(path, folder, { exportName: NOTIFICATION_TYPES_EXPORT, label: "notification type", part: "folder" }, diagnostics);
101224
- if (name === null) {
101225
- continue;
101226
- }
101227
- const other = names2.get(name);
101228
- if (other !== void 0) {
101229
- diagnostics.push(
101230
- diagnosticAt(
101231
- path,
101232
- null,
101233
- `The notification types ${other.path} and ${path} both have the name ${NOTIFICATION_TYPES_EXPORT}.${name}. Rename one of the folders`
101234
- )
101235
- );
101236
- continue;
101081
+ function testsNotReaching(tests, skippedScripts, root, modulePath) {
101082
+ return tests.filter((test) => {
101083
+ if (skippedScripts.has(`${test.path.slice(0, -TEST_SUFFIX.length)}.ts`)) {
101084
+ return false;
101237
101085
  }
101238
- const type = { name, slug: slug ?? folder, path, templates: /* @__PURE__ */ new Map() };
101239
- names2.set(name, type);
101240
- typesByFolder.set(folder, type);
101241
- }
101242
- for (const { path, slug = null } of templates.toSorted((left, right) => byteOrder2(left.path, right.path))) {
101243
- const type = typesByFolder.get(notificationFolder(path));
101244
- if (type === void 0) {
101245
- continue;
101086
+ if (root === null) {
101087
+ return true;
101246
101088
  }
101247
- const fileSlug = templateSlugOf(path);
101248
- const name = pathName(path, fileSlug, { exportName: NOTIFICATION_TYPES_EXPORT, label: "template", part: "file" }, diagnostics);
101249
- if (name === null) {
101250
- continue;
101089
+ try {
101090
+ return !appModuleClosure(
101091
+ root,
101092
+ appImportsOf(root, test.path, test.ast),
101093
+ TEST_MODULE_EXTERNALS
101094
+ ).has(modulePath);
101095
+ } catch (error) {
101096
+ if (error instanceof SourceError) {
101097
+ return true;
101098
+ }
101099
+ throw error;
101251
101100
  }
101252
- const other = type.templates.get(name);
101253
- if (other !== void 0) {
101101
+ });
101102
+ }
101103
+ function runScriptTests({
101104
+ tests,
101105
+ scripts,
101106
+ root: workspaceRoot = null,
101107
+ appModules = /* @__PURE__ */ new Map(),
101108
+ subject = WORKFLOW_TEST_SUBJECT
101109
+ }) {
101110
+ const diagnostics = [];
101111
+ const prefix2 = `${subject.directory}/`;
101112
+ const scriptNames = new Map(
101113
+ scripts.map((script) => [script.path.slice(prefix2.length, -".ts".length), script])
101114
+ );
101115
+ const runnable = [];
101116
+ for (const test of tests) {
101117
+ const scriptPath = `${test.path.slice(0, -TEST_SUFFIX.length)}.ts`;
101118
+ if (!scriptNames.has(scriptPath.slice(prefix2.length, -".ts".length))) {
101254
101119
  diagnostics.push(
101255
101120
  diagnosticAt(
101256
- path,
101121
+ test.path,
101257
101122
  null,
101258
- `The templates ${other.path} and ${path} both have the name ${NOTIFICATION_TYPES_EXPORT}.${type.name}.templates.${name}. Rename one of the files`
101123
+ `The test file has no ${subject.noun}. Add ${scriptPath} or remove the test file`,
101124
+ { stage: subject.stage }
101259
101125
  )
101260
101126
  );
101261
101127
  continue;
101262
101128
  }
101263
- type.templates.set(name, { slug: slug ?? fileSlug, path });
101264
- }
101265
- return names2;
101266
- }
101267
- function notificationTypeEntries2(names2, notifications, uidsByPath = /* @__PURE__ */ new Map()) {
101268
- const typesByPath = new Map(notifications.types.map((type) => [type.path, type]));
101269
- const templatesByPath = new Map(notifications.templates.map((template) => [template.path, template]));
101270
- const entries = /* @__PURE__ */ Object.create(null);
101271
- for (const name of [...names2.keys()].toSorted(byteOrder2)) {
101272
- const { slug, path, templates } = names2.get(name);
101273
- const templateEntries = /* @__PURE__ */ Object.create(null);
101274
- for (const templateName of [...templates.keys()].toSorted(byteOrder2)) {
101275
- const reference = templates.get(templateName);
101276
- const template = templatesByPath.get(reference.path);
101277
- templateEntries[templateName] = template === void 0 ? { uid: uidsByPath.get(reference.path) ?? null, slug: reference.slug, name: null, channels: null } : {
101278
- uid: template.uid,
101279
- slug: template.slug,
101280
- name: template.name,
101281
- channels: { email: template.email !== null, sms: template.sms !== null }
101282
- };
101283
- }
101284
- const type = typesByPath.get(path);
101285
- if (type === void 0) {
101286
- entries[name] = { uid: uidsByPath.get(path) ?? null, slug, name: null, variables: null, templates: templateEntries };
101287
- continue;
101288
- }
101289
- const variables = /* @__PURE__ */ Object.create(null);
101290
- for (const variable of type.variables) {
101291
- variables[variable.key] = fieldMetadata(variable);
101129
+ const imports = importDiagnostics(test, scriptNames, workspaceRoot, subject);
101130
+ diagnostics.push(...imports);
101131
+ if (imports.length === 0) {
101132
+ runnable.push({ ...test, script: scriptPath });
101292
101133
  }
101293
- entries[name] = { uid: type.uid, slug, name: type.name, variables, templates: templateEntries };
101294
101134
  }
101295
- return entries;
101296
- }
101297
- function generatedNotificationTypesSource(entries) {
101298
- return generatedModuleSource(NOTIFICATION_TYPES_EXPORT, entries);
101299
- }
101300
- function unknownNotificationName(path, key, depth) {
101301
- if (depth === 0) {
101302
- return `Unknown notification type "${path}.${key}". Each name in ${path} is a folder in notifications/ with a type.ts`;
101135
+ if (runnable.length === 0) {
101136
+ return { testResults: [], diagnostics };
101303
101137
  }
101304
- if (depth === 2 && path.endsWith(".templates")) {
101305
- return `Unknown template "${path}.${key}". Each name in ${path} is a .template.ts file in the folder of the type`;
101138
+ const modules = new Map(appModules);
101139
+ for (const test of runnable) {
101140
+ for (const [path, module] of appModuleClosure(
101141
+ workspaceRoot,
101142
+ workspaceRoot === null ? [] : appImportsOf(workspaceRoot, test.path, test.ast),
101143
+ TEST_MODULE_EXTERNALS
101144
+ )) {
101145
+ modules.set(path, module);
101146
+ }
101306
101147
  }
101307
- return null;
101308
- }
101309
- function notificationTypeValues(entries) {
101148
+ const files = [];
101149
+ for (const [path, module] of modules) {
101150
+ const resolveSdk = sdkSpecifier(sandboxPrefix(path));
101151
+ files.push({
101152
+ path,
101153
+ target: sandboxPath(path),
101154
+ source: rewriteSpecifiers(
101155
+ module.source,
101156
+ parseSource(module.source, { jsx: path.endsWith("x") }),
101157
+ (specifier) => module.requires[specifier] === void 0 ? resolveSdk(specifier) : relativeSandboxPath(path, module.requires[specifier])
101158
+ )
101159
+ });
101160
+ }
101161
+ for (const script of scripts) {
101162
+ files.push({
101163
+ path: script.path,
101164
+ target: script.path.replace(/\.ts$/, script.compiled ? ".mjs" : ".js"),
101165
+ source: rewriteSpecifiers(script.source, script.ast, (specifier) => {
101166
+ const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
101167
+ return target === null ? sdkSpecifier("../")(specifier) : relativeSandboxPath(script.path, target);
101168
+ })
101169
+ });
101170
+ }
101171
+ for (const test of runnable) {
101172
+ const resolveSdk = sdkSpecifier("../");
101173
+ files.push({
101174
+ path: test.path,
101175
+ target: test.path.replace(/\.ts$/, ".js"),
101176
+ source: rewriteSpecifiers(test.source, test.ast, (specifier) => {
101177
+ const relative6 = RELATIVE_WORKFLOW.exec(specifier);
101178
+ const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
101179
+ if (target !== null) {
101180
+ return relativeSandboxPath(test.path, target);
101181
+ }
101182
+ return relative6 !== null ? `./${relative6[1]}.js` : resolveSdk(specifier);
101183
+ })
101184
+ });
101185
+ }
101186
+ const stripped = stripTypes(files.map(({ path, source }) => ({ path, source })));
101187
+ const stripErrors = files.flatMap((file2, index3) => {
101188
+ const result = stripped[index3];
101189
+ return result.ok ? [] : [
101190
+ diagnostic(
101191
+ file2.path,
101192
+ result.line,
101193
+ result.column,
101194
+ `The ${subject.noun} tests did not run, because this file does not compile: ${result.message}`,
101195
+ { stage: subject.stage }
101196
+ )
101197
+ ];
101198
+ });
101199
+ if (stripErrors.length > 0) {
101200
+ return { testResults: [], diagnostics: [...diagnostics, ...stripErrors] };
101201
+ }
101202
+ const root = realpathSync2(mkdtempSync2(join10(tmpdir2(), "diagonal-workflow-tests-")));
101203
+ try {
101204
+ writeFile(root, "package.json", '{"type":"module"}\n');
101205
+ writeFile(root, "reporter.mjs", REPORTER_SOURCE);
101206
+ for (const [path, content] of Object.entries(scriptSdkRuntimeFiles())) {
101207
+ writeFile(root, `sdk/${path}`, content);
101208
+ }
101209
+ writeFile(root, "sdk/workspace.js", "export {};\n");
101210
+ writeFile(root, "sdk/runtime.js", AUTHORING_HELPERS_MODULE);
101211
+ for (const [index3, file2] of files.entries()) {
101212
+ writeFile(root, file2.target, stripped[index3].code);
101213
+ }
101214
+ for (const script of scripts) {
101215
+ if (script.compiled) {
101216
+ writeFile(root, script.path.replace(/\.ts$/, ".js"), compiledScriptModule(script));
101217
+ }
101218
+ }
101219
+ const run = spawnSync2(
101220
+ process.execPath,
101221
+ [
101222
+ "--permission",
101223
+ `--allow-fs-read=${root}`,
101224
+ "--test",
101225
+ "--test-isolation=none",
101226
+ `--test-timeout=${TEST_TIMEOUT_MS}`,
101227
+ "--test-reporter=./reporter.mjs",
101228
+ ...runnable.map((test) => test.path.replace(/\.ts$/, ".js"))
101229
+ ],
101230
+ {
101231
+ cwd: root,
101232
+ env: { TZ: "UTC" },
101233
+ encoding: "utf8",
101234
+ timeout: RUN_TIMEOUT_MS,
101235
+ maxBuffer: 16 * 1024 * 1024
101236
+ }
101237
+ );
101238
+ if (run.error !== void 0 && run.error.code !== "ETIMEDOUT") {
101239
+ throw run.error;
101240
+ }
101241
+ const results = parseResults(run.stdout ?? "");
101242
+ const timedOut = run.error?.code === "ETIMEDOUT" || run.signal !== null;
101243
+ const testResults = runnable.map((test) => {
101244
+ const file2 = join10(root, test.path.replace(/\.ts$/, ".js"));
101245
+ const own = results.filter((result) => result.file === file2);
101246
+ for (const result of own) {
101247
+ if (!result.ok) {
101248
+ const node = testCallNode(test.ast, result.leaf);
101249
+ diagnostics.push(
101250
+ diagnosticAt(test.path, node, `Test "${result.name}" failed: ${result.message}`, {
101251
+ stage: subject.stage
101252
+ })
101253
+ );
101254
+ }
101255
+ }
101256
+ if (timedOut) {
101257
+ diagnostics.push(
101258
+ diagnostic(
101259
+ test.path,
101260
+ 1,
101261
+ 1,
101262
+ `The ${subject.noun} tests did not finish in ${RUN_TIMEOUT_MS / 1e3} seconds`,
101263
+ { stage: subject.stage }
101264
+ )
101265
+ );
101266
+ } else if (own.length === 0 && run.status !== 0) {
101267
+ diagnostics.push(
101268
+ diagnostic(
101269
+ test.path,
101270
+ 1,
101271
+ 1,
101272
+ `The ${subject.noun} tests did not run: ${(run.stderr ?? "").trim().split("\n")[0] || `exit code ${run.status}`}`,
101273
+ { stage: subject.stage }
101274
+ )
101275
+ );
101276
+ }
101277
+ return {
101278
+ path: test.path,
101279
+ [subject.noun]: test.script,
101280
+ passed: own.filter((result) => result.ok).length,
101281
+ failed: own.filter((result) => !result.ok).length,
101282
+ results: own.map((result) => ({
101283
+ name: result.name,
101284
+ ok: result.ok,
101285
+ message: result.message
101286
+ }))
101287
+ };
101288
+ });
101289
+ return { testResults, diagnostics };
101290
+ } finally {
101291
+ rmSync2(root, { recursive: true, force: true });
101292
+ }
101293
+ }
101294
+
101295
+ // scripts/lib/runtime-build/workflows.mjs
101296
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
101297
+ import { basename as basename10 } from "node:path";
101298
+
101299
+ // scripts/lib/workflow-script/quickjs-runner.mjs
101300
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
101301
+ var DEFAULT_LIMITS = {
101302
+ memory_bytes: 128 * 1024 * 1024,
101303
+ // Node's own WebAssembly stack overflows above roughly 512 KiB, which
101304
+ // aborts the interpreter instead of raising a catchable stack overflow.
101305
+ stack_bytes: 256 * 1024,
101306
+ cpu_ms: 5e3,
101307
+ max_calls: 5e4,
101308
+ max_log_bytes: 128 * 1024,
101309
+ max_result_bytes: 3 * 1024 * 1024,
101310
+ // The largest call message the host reads. PHP sets it to its own line limit.
101311
+ max_call_bytes: 32 * 1024 * 1024
101312
+ };
101313
+ function moduleMapText({ entry, imports, modules }) {
101314
+ return JSON.stringify({ entry, imports, modules });
101315
+ }
101316
+
101317
+ // scripts/lib/runtime-build/skill-references.mjs
101318
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
101319
+ import { basename as basename6 } from "node:path";
101320
+ var GENERATED_SKILLS_PATH = "generated/skills.ts";
101321
+ var SKILLS_EXPORT = "Skills";
101322
+ function skillNames(paths, diagnostics) {
101323
+ const pathsByName = /* @__PURE__ */ new Map();
101324
+ for (const path of paths.toSorted(byteOrder2)) {
101325
+ const name = pathName(
101326
+ path,
101327
+ basename6(path, ".md"),
101328
+ { exportName: SKILLS_EXPORT, label: "skill", showText: false, severity: "warning" },
101329
+ diagnostics
101330
+ );
101331
+ if (name === null) {
101332
+ continue;
101333
+ }
101334
+ const other = pathsByName.get(name);
101335
+ if (other !== void 0) {
101336
+ diagnostics.push(
101337
+ diagnosticAt(
101338
+ path,
101339
+ null,
101340
+ `The skill files ${other} and ${path} both have the name ${SKILLS_EXPORT}.${name}, so ${SKILLS_EXPORT}.${name} names ${other}. Rename one of the files to give ${path} a name in ${SKILLS_EXPORT}`,
101341
+ { severity: "warning" }
101342
+ )
101343
+ );
101344
+ continue;
101345
+ }
101346
+ pathsByName.set(name, path);
101347
+ }
101348
+ return pathsByName;
101349
+ }
101350
+ function skillEntries(pathsByName, skills) {
101351
+ const skillsByPath = new Map(skills.map((skill) => [skill.path, skill]));
101352
+ const entries = /* @__PURE__ */ Object.create(null);
101353
+ for (const name of [...pathsByName.keys()].toSorted(byteOrder2)) {
101354
+ const skill = skillsByPath.get(pathsByName.get(name));
101355
+ entries[name] = skill === void 0 ? { uid: null, name: null, description: null } : { uid: skill.uid ?? null, name: skill.name, description: skill.description };
101356
+ }
101357
+ return entries;
101358
+ }
101359
+ function generatedSkillsSource(entries) {
101360
+ return generatedModuleSource(SKILLS_EXPORT, entries);
101361
+ }
101362
+ function skillValues(entries) {
101363
+ return { entries, exportName: SKILLS_EXPORT, noun: "skill", directory: "skills/" };
101364
+ }
101365
+
101366
+ // scripts/lib/runtime-build/notification-references.mjs
101367
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
101368
+ var GENERATED_NOTIFICATION_TYPES_PATH = "generated/notification-types.ts";
101369
+ var GENERATED_NOTIFICATION_TYPES_MODULE = "@app/generated/notification-types";
101370
+ var NOTIFICATION_TYPES_EXPORT = "NotificationTypes";
101371
+ var TYPE_PATH = /^notifications\/([^/]+)\/type\.ts$/;
101372
+ var TEMPLATE_PATH = /^notifications\/([^/]+)\/([^/]+)\.template\.ts$/;
101373
+ var SCHEDULE_PATH = /^notifications\/[^/]+\/[^/]+\.schedule\.ts$/;
101374
+ function notificationFolder(path) {
101375
+ return path.split("/")[1];
101376
+ }
101377
+ function isNotificationSchedulePath(path) {
101378
+ return SCHEDULE_PATH.test(path);
101379
+ }
101380
+ function templateSlugOf(path) {
101381
+ return TEMPLATE_PATH.exec(path)[2];
101382
+ }
101383
+ function notificationTypeNames(types2, templates, diagnostics) {
101384
+ const names2 = /* @__PURE__ */ new Map();
101385
+ const typesByFolder = /* @__PURE__ */ new Map();
101386
+ for (const { path, slug = null } of types2.toSorted((left, right) => byteOrder2(left.path, right.path))) {
101387
+ const folder = TYPE_PATH.exec(path)[1];
101388
+ const name = pathName(path, folder, { exportName: NOTIFICATION_TYPES_EXPORT, label: "notification type", part: "folder" }, diagnostics);
101389
+ if (name === null) {
101390
+ continue;
101391
+ }
101392
+ const other = names2.get(name);
101393
+ if (other !== void 0) {
101394
+ diagnostics.push(
101395
+ diagnosticAt(
101396
+ path,
101397
+ null,
101398
+ `The notification types ${other.path} and ${path} both have the name ${NOTIFICATION_TYPES_EXPORT}.${name}. Rename one of the folders`
101399
+ )
101400
+ );
101401
+ continue;
101402
+ }
101403
+ const type = { name, slug: slug ?? folder, path, templates: /* @__PURE__ */ new Map() };
101404
+ names2.set(name, type);
101405
+ typesByFolder.set(folder, type);
101406
+ }
101407
+ for (const { path, slug = null } of templates.toSorted((left, right) => byteOrder2(left.path, right.path))) {
101408
+ const type = typesByFolder.get(notificationFolder(path));
101409
+ if (type === void 0) {
101410
+ continue;
101411
+ }
101412
+ const fileSlug = templateSlugOf(path);
101413
+ const name = pathName(path, fileSlug, { exportName: NOTIFICATION_TYPES_EXPORT, label: "template", part: "file" }, diagnostics);
101414
+ if (name === null) {
101415
+ continue;
101416
+ }
101417
+ const other = type.templates.get(name);
101418
+ if (other !== void 0) {
101419
+ diagnostics.push(
101420
+ diagnosticAt(
101421
+ path,
101422
+ null,
101423
+ `The templates ${other.path} and ${path} both have the name ${NOTIFICATION_TYPES_EXPORT}.${type.name}.templates.${name}. Rename one of the files`
101424
+ )
101425
+ );
101426
+ continue;
101427
+ }
101428
+ type.templates.set(name, { slug: slug ?? fileSlug, path });
101429
+ }
101430
+ return names2;
101431
+ }
101432
+ function notificationTypeEntries2(names2, notifications, uidsByPath = /* @__PURE__ */ new Map()) {
101433
+ const typesByPath = new Map(notifications.types.map((type) => [type.path, type]));
101434
+ const templatesByPath = new Map(notifications.templates.map((template) => [template.path, template]));
101435
+ const entries = /* @__PURE__ */ Object.create(null);
101436
+ for (const name of [...names2.keys()].toSorted(byteOrder2)) {
101437
+ const { slug, path, templates } = names2.get(name);
101438
+ const templateEntries = /* @__PURE__ */ Object.create(null);
101439
+ for (const templateName of [...templates.keys()].toSorted(byteOrder2)) {
101440
+ const reference = templates.get(templateName);
101441
+ const template = templatesByPath.get(reference.path);
101442
+ templateEntries[templateName] = template === void 0 ? { uid: uidsByPath.get(reference.path) ?? null, slug: reference.slug, name: null, channels: null } : {
101443
+ uid: template.uid,
101444
+ slug: template.slug,
101445
+ name: template.name,
101446
+ channels: { email: template.email !== null, sms: template.sms !== null }
101447
+ };
101448
+ }
101449
+ const type = typesByPath.get(path);
101450
+ if (type === void 0) {
101451
+ entries[name] = { uid: uidsByPath.get(path) ?? null, slug, name: null, variables: null, templates: templateEntries };
101452
+ continue;
101453
+ }
101454
+ const variables = /* @__PURE__ */ Object.create(null);
101455
+ for (const variable of type.variables) {
101456
+ variables[variable.key] = fieldMetadata(variable);
101457
+ }
101458
+ entries[name] = { uid: type.uid, slug, name: type.name, variables, templates: templateEntries };
101459
+ }
101460
+ return entries;
101461
+ }
101462
+ function generatedNotificationTypesSource(entries) {
101463
+ return generatedModuleSource(NOTIFICATION_TYPES_EXPORT, entries);
101464
+ }
101465
+ function unknownNotificationName(path, key, depth) {
101466
+ if (depth === 0) {
101467
+ return `Unknown notification type "${path}.${key}". Each name in ${path} is a folder in notifications/ with a type.ts`;
101468
+ }
101469
+ if (depth === 2 && path.endsWith(".templates")) {
101470
+ return `Unknown template "${path}.${key}". Each name in ${path} is a .template.ts file in the folder of the type`;
101471
+ }
101472
+ return null;
101473
+ }
101474
+ function notificationTypeValues(entries) {
101310
101475
  return {
101311
101476
  entries,
101312
101477
  exportName: NOTIFICATION_TYPES_EXPORT,
@@ -101401,1636 +101566,955 @@ function objectExpressions(node) {
101401
101566
  return objects;
101402
101567
  }
101403
101568
 
101404
- // scripts/lib/runtime-build/workspace-field-references.mjs
101405
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
101406
- import { basename as basename8 } from "node:path";
101407
-
101408
- // scripts/lib/runtime-build/workspace-fields.mjs
101569
+ // scripts/lib/runtime-build/workflow-entity-references.mjs
101409
101570
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
101410
- import { readFileSync as readFileSync6 } from "node:fs";
101411
- import { basename as basename7, join as join8 } from "node:path";
101412
-
101413
- // packages/cli/workspace-settings-catalog.json
101414
- var workspace_settings_catalog_default = {
101415
- settings: {
101416
- ai_custom_system_prompt: {
101417
- type: "text",
101418
- label: "AI Custom System Prompt",
101419
- default: null,
101420
- values: null,
101421
- max: null,
101422
- url: false,
101423
- pattern: null
101424
- },
101425
- custom_401_error_page: {
101426
- type: "page_reference",
101427
- label: "Custom 401 Error Page",
101428
- default: null,
101429
- values: null,
101430
- max: null,
101431
- url: false,
101432
- pattern: null
101433
- },
101434
- custom_403_error_page: {
101435
- type: "page_reference",
101436
- label: "Custom 403 Error Page",
101437
- default: null,
101438
- values: null,
101439
- max: null,
101440
- url: false,
101441
- pattern: null
101442
- },
101443
- custom_404_error_page: {
101444
- type: "page_reference",
101445
- label: "Custom 404 Error Page",
101446
- default: null,
101447
- values: null,
101448
- max: null,
101449
- url: false,
101450
- pattern: null
101451
- },
101452
- custom_422_error_page: {
101453
- type: "page_reference",
101454
- label: "Custom 422 Error Page",
101455
- default: null,
101456
- values: null,
101457
- max: null,
101458
- url: false,
101459
- pattern: null
101460
- },
101461
- custom_500_error_page: {
101462
- type: "page_reference",
101463
- label: "Custom 500 Error Page",
101464
- default: null,
101465
- values: null,
101466
- max: null,
101467
- url: false,
101468
- pattern: null
101469
- },
101470
- default_currency: {
101471
- type: "select",
101472
- label: "Default Currency",
101473
- default: "usd",
101474
- values: [
101475
- "aed",
101476
- "ars",
101477
- "aud",
101478
- "brl",
101479
- "cad",
101480
- "chf",
101481
- "clp",
101482
- "cny",
101483
- "cop",
101484
- "czk",
101485
- "dkk",
101486
- "eur",
101487
- "gbp",
101488
- "hkd",
101489
- "idr",
101490
- "ils",
101491
- "inr",
101492
- "jpy",
101493
- "krw",
101494
- "mxn",
101495
- "myr",
101496
- "nok",
101497
- "nzd",
101498
- "pen",
101499
- "php",
101500
- "pln",
101501
- "sar",
101502
- "sek",
101503
- "sgd",
101504
- "thb",
101505
- "twd",
101506
- "usd",
101507
- "zar"
101508
- ],
101509
- max: null,
101510
- url: false,
101511
- pattern: null
101512
- },
101513
- default_timezone: {
101514
- type: "timezone",
101515
- label: "Default Timezone",
101516
- default: "America/Chicago",
101517
- values: null,
101518
- max: null,
101519
- url: false,
101520
- pattern: null
101521
- },
101522
- fathom_site_id: {
101523
- type: "text",
101524
- label: "Fathom Site ID",
101525
- default: null,
101526
- values: null,
101527
- max: null,
101528
- url: false,
101529
- pattern: null
101530
- },
101531
- head_html: {
101532
- type: "text",
101533
- label: "Custom Head HTML",
101534
- default: null,
101535
- values: null,
101536
- max: 5e4,
101537
- url: false,
101538
- pattern: null
101539
- },
101540
- sidebar_icon: {
101541
- type: "text",
101542
- label: "Sidebar Icon",
101543
- default: "building-2",
101544
- values: null,
101545
- max: null,
101546
- url: false,
101547
- pattern: null
101548
- },
101549
- sidebar_icon_color: {
101550
- type: "color",
101551
- label: "Sidebar Icon Color",
101552
- default: "#2B3990",
101553
- values: null,
101554
- max: 256,
101555
- url: false,
101556
- pattern: "^[#A-Za-z0-9 .,%+\\-\\/()]+$"
101557
- },
101558
- website: {
101559
- type: "text",
101560
- label: "Website",
101561
- default: null,
101562
- values: null,
101563
- max: null,
101564
- url: true,
101565
- pattern: null
101566
- }
101567
- },
101568
- refused: {
101569
- brand_kit: "Set the Brand Kit with the root `brand` option.",
101570
- name: "Set the workspace name with the root `name` option.",
101571
- slug: "The workspace slug is set in the Control Panel."
101572
- }
101573
- };
101574
101571
 
101575
- // scripts/lib/runtime-build/workspace-settings.mjs
101572
+ // scripts/lib/runtime-build/permission-references.mjs
101576
101573
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
101577
- var URL_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
101578
- function readWorkspaceSettings(settings, node, pagesByUid) {
101579
- if (settings === void 0) {
101580
- return {};
101581
- }
101582
- if (!isPlainObject2(settings)) {
101583
- throw new SourceError('"settings" must be an object', node);
101584
- }
101585
- for (const [key, value] of Object.entries(settings)) {
101586
- const settingNode = propertyNode(node, key);
101587
- const refused = workspace_settings_catalog_default.refused[key];
101588
- if (refused !== void 0) {
101589
- throw new SourceError(`"settings.${key}" is not allowed. ${refused}`, settingNode);
101590
- }
101591
- const setting = workspace_settings_catalog_default.settings[key];
101592
- if (setting === void 0) {
101593
- throw new SourceError(
101594
- `Unknown workspace setting "${key}". Use one of: ${Object.keys(workspace_settings_catalog_default.settings).join(", ")}`,
101595
- settingNode
101596
- );
101597
- }
101598
- const problem2 = valueProblem(setting, value, pagesByUid);
101599
- if (problem2 !== null) {
101600
- throw new SourceError(`"settings.${key}" ${problem2}`, settingNode);
101601
- }
101602
- }
101603
- return settings;
101574
+ import { basename as basename7, extname } from "node:path";
101575
+ var PERMISSIONS_DIRECTORY = "permissions";
101576
+ var LEGACY_PERMISSIONS_PATH = "permissions.ts";
101577
+ var GENERATED_PERMISSIONS_PATH = "generated/permissions.ts";
101578
+ var GENERATED_PERMISSIONS_MODULE = "@app/generated/permissions";
101579
+ var PERMISSIONS_EXPORT = "Permissions";
101580
+ var SYSTEM_PERMISSIONS_EXPORT = "SystemPermissions";
101581
+ var SLUG_PATTERN2 = /^[a-z][a-z0-9_]*$/;
101582
+ var OPTIONS = /* @__PURE__ */ new Set(["uid", "slug", "name", "description"]);
101583
+ var MAX_LENGTH = 255;
101584
+ var systemPermissions = Object.entries(SystemPermissions).map(([constName, permission]) => ({
101585
+ constName,
101586
+ ...permission
101587
+ }));
101588
+ var systemBySlug = new Map(systemPermissions.map((permission) => [permission.slug, permission]));
101589
+ var systemByName = new Map(systemPermissions.map((permission) => [permission.name, permission]));
101590
+ var systemByUid = new Map(systemPermissions.map((permission) => [permission.uid, permission]));
101591
+ var SLUG_RULE2 = `start with a lowercase letter, contain only a-z, 0-9, and _, and have at most ${MAX_LENGTH} characters`;
101592
+ function isDefinitionSlug(slug) {
101593
+ return SLUG_PATTERN2.test(slug) && slug.length <= MAX_LENGTH;
101604
101594
  }
101605
- function valueProblem(setting, value, pagesByUid) {
101606
- if (value === null) {
101607
- return null;
101608
- }
101609
- if (setting.type === "page_reference") {
101610
- return pageReferenceProblem(value, pagesByUid);
101611
- }
101612
- if (typeof value !== "string") {
101613
- return "must be a string or null";
101614
- }
101615
- if (setting.values !== null && !setting.values.includes(value)) {
101616
- const lower = value.toLowerCase();
101617
- const hint = lower !== value && setting.values.includes(lower) ? ` Use "${lower}".` : "";
101618
- return `must be one of the supported values, such as "${setting.default ?? setting.values[0]}".${hint}`;
101619
- }
101620
- if (setting.type === "timezone" && !isTimezone(value)) {
101621
- return `must be an IANA timezone, such as "${setting.default}"`;
101622
- }
101623
- if (setting.max !== null && value.length > setting.max) {
101624
- return `must be at most ${setting.max} characters`;
101625
- }
101626
- if (setting.pattern !== null && value.trim() !== "" && !new RegExp(setting.pattern).test(value.trim())) {
101627
- return "has characters that the setting does not allow";
101595
+ function definitionFileSlug(path, definition, { noun, exportName }) {
101596
+ const fileName = basename7(path, extname(path));
101597
+ const declared = declaredSlug(definition);
101598
+ if (declared.problem !== null) {
101599
+ throw new SourceError(declared.problem, declared.node);
101628
101600
  }
101629
- if (setting.url && !isUrl(value)) {
101630
- return 'must be a URL, such as "https://example.com"';
101601
+ if (!isDefinitionSlug(fileName)) {
101602
+ const role = declared.slug === null ? `is the slug of the ${noun}` : `gives the ${exportName} name of the ${noun}`;
101603
+ throw new SourceError(`The file name "${fileName}" ${role}, so it must ${SLUG_RULE2}`, null);
101631
101604
  }
101632
- return null;
101633
- }
101634
- function isUrl(value) {
101635
- return URL_PATTERN.test(value) && URL.canParse(value);
101636
- }
101637
- function isTimezone(value) {
101638
- try {
101639
- new Intl.DateTimeFormat("en-US", { timeZone: value });
101640
- } catch (error) {
101641
- if (error instanceof RangeError) {
101642
- return false;
101643
- }
101644
- throw error;
101605
+ if (declared.slug !== null && !isDefinitionSlug(declared.slug)) {
101606
+ throw new SourceError(`The "slug" of the ${noun} is "${declared.slug}". A slug must ${SLUG_RULE2}`, declared.node);
101645
101607
  }
101646
- return value.includes("/") || value === "UTC";
101608
+ return { slug: declared.slug ?? fileName, name: studlyName(fileName) };
101647
101609
  }
101648
-
101649
- // scripts/lib/runtime-build/workspace-fields.mjs
101650
- var WORKSPACE_FIELDS_DIRECTORY = "workspace-fields";
101651
- var RESERVED_KEYS = /* @__PURE__ */ new Set([
101652
- ...Object.keys(workspace_settings_catalog_default.settings),
101653
- ...Object.keys(workspace_settings_catalog_default.refused),
101654
- ...FIELD_CATALOG.record_meta_fields
101655
- ]);
101656
- var ENTRY_KEYS = /* @__PURE__ */ new Set(["uid", "key", "section", "definition", "value"]);
101657
- var RESOURCE_ONLY_OPTIONS = ["uid", "unique", "index", "computed", "getter", "setter", "setterWhenEmpty"];
101658
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
101659
- var DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
101660
- var TIME_PATTERN = /^\d{2}:\d{2}(?::\d{2})?$/;
101661
- var STRING_TYPES = /* @__PURE__ */ new Set(["color", "liquid", "markdown", "password", "phone", "text"]);
101662
- var UUID_TYPES = /* @__PURE__ */ new Set(["resource_reference", "uuid", "wallet_accounting_account", "wallet_accounting_entity"]);
101663
- var OBJECT_TYPES2 = /* @__PURE__ */ new Set(["content", "dictionary", "event_schedule", "location", "money", "regular_hours"]);
101664
- function readWorkspaceFields(root, paths, diagnostics, { write = false, recordBindingEntries = {} } = {}) {
101665
- const read2 = [];
101666
- const keysByPath = /* @__PURE__ */ new Map();
101667
- for (const path of paths) {
101668
- try {
101669
- const source = readFileSync6(join8(root, path), "utf8");
101670
- const ast = parseSource(source, { jsx: false });
101671
- const argument = defineWorkspaceFieldArgument(ast);
101672
- const declared = declaredSlug(argument, "key");
101673
- keysByPath.set(path, declared.slug ?? basename7(path, ".ts"));
101674
- const field2 = readWorkspaceField(path, argument, declared, diagnostics, recordBindingsBinding(ast, recordBindingEntries));
101675
- read2.push({ field: field2, uidDefinition: { type: "workspace field", path, source, node: argument } });
101676
- } catch (error) {
101677
- diagnostics.push(diagnosticFromError(path, error));
101610
+ function refuseUnknownOptions2(value, definition, options, noun, slug) {
101611
+ for (const option of Object.keys(value)) {
101612
+ if (options.has(option)) {
101613
+ continue;
101678
101614
  }
101615
+ throw new SourceError(`Unknown option "${option}" of ${noun} "${slug}"`, propertyNode(definition, option) ?? definition);
101679
101616
  }
101680
- const uidCheck = checkDefinitionUids(root, read2.map((item) => item.uidDefinition), { write });
101681
- diagnostics.push(...uidCheck.diagnostics);
101682
- return {
101683
- fields: read2.map(({ field: field2 }, position) => ({ ...field2, uid: uidCheck.uids[position] })),
101684
- keysByPath
101685
- };
101686
- }
101687
- function defineWorkspaceFieldArgument(ast) {
101688
- const { declaration } = defaultExportOf(ast, { extraImports: [GENERATED_RECORD_BINDINGS_MODULE] });
101689
- return expectDefineCall(declaration, "defineWorkspaceField", 1)[0];
101690
- }
101691
- function isWorkspaceFieldFileName(name) {
101692
- return FIELD_KEY_PATTERN.test(name);
101693
101617
  }
101694
- function workspaceFieldKeyProblem(path, key, declared) {
101695
- const fileName = basename7(path, ".ts");
101696
- if (!isWorkspaceFieldFileName(fileName)) {
101697
- const suggestion = fileName.toLowerCase().replaceAll("-", "_");
101698
- const hint = isWorkspaceFieldFileName(suggestion) ? `. Rename the file to ${suggestion}.ts` : "";
101699
- const role = declared ? "gives the WorkspaceFields name of the field" : "is the workspace field key";
101700
- return `The file name "${fileName}" ${role}, so it must start with a lowercase letter and contain only a-z, 0-9, and _${hint}`;
101701
- }
101702
- if (declared && !FIELD_KEY_PATTERN.test(key)) {
101703
- return '"key" must start with a lowercase letter and contain only a-z, 0-9, and _';
101704
- }
101705
- if (RESERVED_KEYS.has(key)) {
101706
- return declared ? `"${key}" is the key of a field that the workspace already has. Give the custom field another key` : `The file name "${key}" is the key of a field that the workspace already has. Rename the file to give the custom field another key`;
101707
- }
101708
- return null;
101618
+ function definePermissionArgument(ast) {
101619
+ const { declaration } = defaultExportOf(ast);
101620
+ return expectDefineCall(declaration, "definePermission", 1)[0];
101709
101621
  }
101710
- function readWorkspaceField(path, argument, declared, diagnostics, generatedEntries) {
101711
- if (declared.problem !== null) {
101712
- throw new SourceError(declared.problem, declared.node);
101713
- }
101714
- const key = declared.slug ?? basename7(path, ".ts");
101715
- const keyProblem = workspaceFieldKeyProblem(path, key, declared.slug !== null);
101716
- if (keyProblem !== null) {
101717
- throw new SourceError(keyProblem, declared.node);
101718
- }
101719
- const { value: entry, nodes } = staticObject(argument, { fieldBuilders: true, generatedEntries });
101720
- for (const option of Object.keys(entry)) {
101721
- if (option === "slug") {
101722
- throw new SourceError('Remove "slug". A workspace field sets its key with "key"', nodes.slug);
101723
- }
101724
- if (!ENTRY_KEYS.has(option)) {
101725
- throw new SourceError(`Unknown option "${option}". Use "uid", "key", "section", "definition", and "value"`, nodes[option]);
101726
- }
101727
- }
101728
- if (entry.section !== void 0 && (typeof entry.section !== "string" || entry.section.length > 255)) {
101729
- throw new SourceError('"section" must be a string with at most 255 characters', nodes.section);
101622
+ function buildPermission(path, definition) {
101623
+ const { slug, name } = definitionFileSlug(path, definition, { noun: "permission", exportName: PERMISSIONS_EXPORT });
101624
+ if (definition.type !== "ObjectExpression") {
101625
+ throw new SourceError("definePermission(...) takes an object literal", definition);
101730
101626
  }
101731
- const builder = entry.definition;
101732
- const { field: field2, metadata } = readWorkspaceFieldDefinition(key, builder, nodes.definition ?? argument);
101733
- if (!Object.hasOwn(entry, "value")) {
101734
- throw new SourceError('Add "value". Write null for a field without a value', argument);
101627
+ const value = staticValue(definition);
101628
+ if (!isPlainObject2(value)) {
101629
+ throw new SourceError("definePermission(...) takes an object literal", definition);
101735
101630
  }
101736
- const problem2 = valueProblem2(field2, entry.value);
101737
- if (problem2 !== null) {
101738
- throw new SourceError(`"value" ${problem2}`, nodes.value);
101631
+ refuseUnknownOptions2(value, definition, OPTIONS, "permission", slug);
101632
+ if (typeof value.name !== "string" || value.name.trim() === "" || value.name.length > MAX_LENGTH) {
101633
+ throw new SourceError(
101634
+ `Permission "${slug}" needs a "name" of 1 to ${MAX_LENGTH} characters`,
101635
+ definition
101636
+ );
101739
101637
  }
101740
- if (builder.options.default !== void 0) {
101741
- diagnostics.push(
101742
- diagnosticAt(
101743
- path,
101744
- optionNode(builder, "default"),
101745
- '"default" is not used. A workspace field takes its value from "value"',
101746
- { severity: "warning" }
101747
- )
101638
+ const description = value.description ?? null;
101639
+ if (description !== null && typeof description !== "string") {
101640
+ throw new SourceError(
101641
+ `The "description" of permission "${slug}" must be a string`,
101642
+ propertyNode(definition, "description")
101748
101643
  );
101749
101644
  }
101750
101645
  return {
101646
+ key: slug,
101647
+ name,
101648
+ uid: null,
101649
+ slug,
101650
+ label: value.name,
101651
+ description,
101751
101652
  path,
101752
- key,
101753
- ...metadata,
101754
- section: entry.section ?? null,
101755
- value: entry.value,
101756
- nodes: { definition: builder.node, value: nodes.value }
101653
+ node: definition
101757
101654
  };
101758
101655
  }
101759
- function readWorkspaceFieldDefinition(key, builder, node) {
101760
- if (!(builder instanceof FieldBuilderValue)) {
101761
- throw new SourceError('"definition" must be a field.<type>({...}) call', node);
101762
- }
101763
- checkBuilderOptions(builder);
101764
- const field2 = buildField(key, builder, node, { checkKey: false });
101765
- if (field2.type === "relation") {
101766
- throw new SourceError("A workspace field cannot be a relation. A workspace field has no record", builder.node);
101767
- }
101768
- return {
101769
- field: field2,
101770
- metadata: {
101771
- type: field2.type,
101772
- label: field2.label,
101773
- description: field2.description,
101774
- guard: [field2.required ? "required" : "nullable", ...field2.guard],
101775
- settings: field2.settings
101656
+ function checkPermissions(permissions, diagnostics) {
101657
+ for (const permission of permissions) {
101658
+ const system = systemBySlug.get(permission.slug);
101659
+ if (system !== void 0) {
101660
+ diagnostics.push(
101661
+ diagnosticAt(
101662
+ permission.path,
101663
+ null,
101664
+ `Permission "${permission.slug}": "${permission.slug}" is the slug of the system permission ${SYSTEM_PERMISSIONS_EXPORT}.${system.constName}. Name it with ${SYSTEM_PERMISSIONS_EXPORT}.${system.constName}.uid from ${AUTHORING_MODULE}, or give this permission another slug`
101665
+ )
101666
+ );
101667
+ }
101668
+ const systemName = systemByName.get(permission.label);
101669
+ if (systemName !== void 0) {
101670
+ diagnostics.push(
101671
+ diagnosticAt(
101672
+ permission.path,
101673
+ permission.node,
101674
+ `Permission "${permission.slug}": "${permission.label}" is the name of the system permission ${SYSTEM_PERMISSIONS_EXPORT}.${systemName.constName}. Give this permission another name`
101675
+ )
101676
+ );
101776
101677
  }
101777
- };
101778
- }
101779
- function checkBuilderOptions(builder) {
101780
- const option = RESOURCE_ONLY_OPTIONS.find((item) => builder.options[item] !== void 0);
101781
- if (option !== void 0) {
101782
- throw new SourceError(
101783
- `A workspace field cannot use "${option}". It is an option of a resource field`,
101784
- optionNode(builder, option)
101785
- );
101786
- }
101787
- }
101788
- function valueProblem2(field2, value) {
101789
- if (value === null) {
101790
- return field2.required ? "is required, so it cannot be null" : null;
101791
- }
101792
- const { type, settings } = field2;
101793
- if (STRING_TYPES.has(type)) {
101794
- return typeof value === "string" ? null : "must be a string";
101795
- }
101796
- if (UUID_TYPES.has(type)) {
101797
- return typeof value === "string" && UID_PATTERN.test(value.toLowerCase()) || value?.$type === "record.binding" ? null : "must be a UUID or a record binding reference";
101798
- }
101799
- if (OBJECT_TYPES2.has(type)) {
101800
- return objectProblem(type, value);
101801
- }
101802
- switch (type) {
101803
- case "boolean":
101804
- return typeof value === "boolean" ? null : "must be true or false";
101805
- case "number":
101806
- return numberProblem(value, settings);
101807
- case "email":
101808
- return typeof value === "string" && EMAIL_PATTERN.test(value) ? null : 'must be an email address, such as "help@example.com"';
101809
- case "url":
101810
- return typeof value === "string" && isUrl(value) ? null : 'must be a URL, such as "https://example.com"';
101811
- case "date":
101812
- return typeof value === "string" && DATE_PATTERN.test(value) && !Number.isNaN(Date.parse(value)) ? null : 'must be a date, such as "2026-01-31"';
101813
- case "datetime":
101814
- return typeof value === "string" && !Number.isNaN(Date.parse(value)) ? null : 'must be a date and time, such as "2026-01-31T09:00:00Z"';
101815
- case "time":
101816
- return typeof value === "string" && TIME_PATTERN.test(value) ? null : 'must be a time, such as "09:30"';
101817
- case "timezone":
101818
- return typeof value === "string" && isTimezone(value) ? null : 'must be an IANA timezone, such as "America/Chicago"';
101819
- case "select":
101820
- return selectProblem(value, settings.options);
101821
- case "list":
101822
- return Array.isArray(value) ? null : "must be a list";
101823
- default:
101824
- return null;
101825
- }
101826
- }
101827
- function numberProblem(value, settings) {
101828
- if (typeof value !== "number" || !Number.isFinite(value)) {
101829
- return "must be a number";
101830
- }
101831
- if (settings.integer === true && !Number.isInteger(value)) {
101832
- return "must be a whole number";
101833
- }
101834
- if (typeof settings.minimum === "number" && value < settings.minimum) {
101835
- return `must be at least ${settings.minimum}`;
101836
- }
101837
- if (typeof settings.maximum === "number" && value > settings.maximum) {
101838
- return `must be at most ${settings.maximum}`;
101839
- }
101840
- return null;
101841
- }
101842
- function selectProblem(value, options) {
101843
- const values = options.map((option) => option.value);
101844
- return values.includes(value) ? null : `must be one of the option values: ${values.map((item) => JSON.stringify(item)).join(", ")}`;
101845
- }
101846
- function objectProblem(type, value) {
101847
- if (!isPlainObject2(value)) {
101848
- return "must be an object";
101849
- }
101850
- if (type === "money" && (typeof value.amount !== "number" || typeof value.currency !== "string")) {
101851
- return 'must be { amount: <number>, currency: "<code>" }';
101852
101678
  }
101853
- return null;
101679
+ checkDuplicateDefinitions(permissions, "permissions", PERMISSIONS_EXPORT, diagnostics);
101854
101680
  }
101855
-
101856
- // scripts/lib/runtime-build/workspace-field-references.mjs
101857
- var GENERATED_WORKSPACE_FIELDS_PATH = "generated/workspace-fields.ts";
101858
- var WORKSPACE_FIELDS_EXPORT = "WorkspaceFields";
101859
- function workspaceFieldNames(paths, keysByPath, diagnostics) {
101860
- const keysByName = /* @__PURE__ */ new Map();
101861
- const pathsByName = /* @__PURE__ */ new Map();
101862
- const pathsByKey = /* @__PURE__ */ new Map();
101863
- for (const path of paths.toSorted(byteOrder2)) {
101864
- const fileName = basename8(path, ".ts");
101865
- if (!isWorkspaceFieldFileName(fileName)) {
101681
+ function checkDuplicateDefinitions(definitions, plural2, exportName, diagnostics) {
101682
+ const firstBySlug = /* @__PURE__ */ new Map();
101683
+ const firstByName = /* @__PURE__ */ new Map();
101684
+ const firstByLabel = /* @__PURE__ */ new Map();
101685
+ for (const definition of definitions) {
101686
+ const sameSlug = firstBySlug.get(definition.slug);
101687
+ if (sameSlug !== void 0) {
101688
+ diagnostics.push(
101689
+ diagnosticAt(
101690
+ definition.path,
101691
+ definition.node,
101692
+ `The ${plural2} ${sameSlug.path} and ${definition.path} have the same slug "${definition.slug}". Change one of them`,
101693
+ { relatedPath: sameSlug.path }
101694
+ )
101695
+ );
101866
101696
  continue;
101867
101697
  }
101868
- const key = keysByPath.get(path) ?? fileName;
101869
- const name = studlyName(fileName);
101870
- const otherName = pathsByName.get(name);
101871
- const otherKey = pathsByKey.get(key);
101872
- if (otherName !== void 0 || otherKey !== void 0) {
101698
+ firstBySlug.set(definition.slug, definition);
101699
+ for (const [first, value, label] of [
101700
+ [firstByName, definition.name, `name ${exportName}.${definition.name}`],
101701
+ [firstByLabel, definition.label, `name "${definition.label}"`]
101702
+ ]) {
101703
+ const other = first.get(value);
101704
+ if (other === void 0) {
101705
+ first.set(value, definition);
101706
+ continue;
101707
+ }
101873
101708
  diagnostics.push(
101874
101709
  diagnosticAt(
101875
- path,
101876
- null,
101877
- otherName !== void 0 ? `The workspace field files ${otherName} and ${path} both have the name ${WORKSPACE_FIELDS_EXPORT}.${name}. Rename one of the files` : `The workspace field files ${otherKey} and ${path} have the same key "${key}". Change the key of one of them`,
101878
- { relatedPath: otherName ?? otherKey }
101710
+ definition.path,
101711
+ definition.node,
101712
+ `The ${plural2} "${other.slug}" and "${definition.slug}" have the same ${label}. Change one of them`,
101713
+ { relatedPath: other.path }
101879
101714
  )
101880
101715
  );
101881
- continue;
101882
101716
  }
101883
- keysByName.set(name, key);
101884
- pathsByName.set(name, path);
101885
- pathsByKey.set(key, path);
101886
101717
  }
101887
- return keysByName;
101888
101718
  }
101889
- function workspaceFieldEntries(keysByName, fields) {
101890
- const fieldsByKey = new Map(fields.map((field2) => [field2.key, field2]));
101719
+ function checkPermissionUids(permissions, diagnostics) {
101720
+ for (const permission of permissions) {
101721
+ const system = permission.uid === null ? void 0 : systemByUid.get(permission.uid);
101722
+ if (system !== void 0) {
101723
+ diagnostics.push(
101724
+ diagnosticAt(
101725
+ permission.path,
101726
+ permission.node,
101727
+ `Permission "${permission.slug}" has the uid of the system permission ${SYSTEM_PERMISSIONS_EXPORT}.${system.constName}. Give it a new uid`
101728
+ )
101729
+ );
101730
+ }
101731
+ }
101732
+ }
101733
+ function definitionEntries(definitions) {
101891
101734
  const entries = /* @__PURE__ */ Object.create(null);
101892
- for (const name of [...keysByName.keys()].toSorted(byteOrder2)) {
101893
- const key = keysByName.get(name);
101894
- const field2 = fieldsByKey.get(key);
101895
- entries[name] = field2 === void 0 ? { key } : { uid: field2.uid ?? null, ...fieldMetadata({ ...field2, required: field2.guard[0] === "required" }) };
101735
+ for (const definition of definitions.toSorted(
101736
+ (left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0
101737
+ )) {
101738
+ entries[definition.name] = {
101739
+ uid: definition.uid,
101740
+ slug: definition.slug,
101741
+ name: definition.label
101742
+ };
101896
101743
  }
101897
101744
  return entries;
101898
101745
  }
101899
- function generatedWorkspaceFieldsSource(entries, fields = [], { workflowPackageDeclared = false } = {}) {
101900
- const keys2 = new Set(Object.values(entries).map((field2) => field2.key));
101901
- const declared = fields.filter((field2) => keys2.has(field2.key));
101902
- return generatedWorkflowTypesSource(WORKSPACE_FIELDS_EXPORT, entries, "", {
101903
- augment: (module) => workspaceFieldAugmentation(declared, module),
101904
- workflowPackageDeclared
101905
- });
101746
+ function generatedPermissionsSource(entries) {
101747
+ return generatedModuleSource(PERMISSIONS_EXPORT, entries);
101906
101748
  }
101907
- function workspaceFieldValues(entries) {
101908
- return {
101909
- entries,
101910
- exportName: WORKSPACE_FIELDS_EXPORT,
101911
- noun: "workspace field",
101912
- directory: "workspace-fields/",
101913
- exampleMember: "key"
101914
- };
101749
+ function permissionValues(entries) {
101750
+ return { entries, exportName: PERMISSIONS_EXPORT, noun: "permission", directory: "permissions/", exampleMember: "uid" };
101915
101751
  }
101916
-
101917
- // scripts/lib/runtime-build/module-graph.mjs
101918
- var STYLE_KINDS = /* @__PURE__ */ new Set(["style", "style_module"]);
101919
- var GENERATED_IMPORT_KINDS = /* @__PURE__ */ new Map([
101920
- [GENERATED_ASSETS_PATH, "assets"],
101921
- [GENERATED_PAGES_PATH, "pages"],
101922
- [GENERATED_PERMISSIONS_PATH, "permissions"],
101923
- [GENERATED_ROLES_PATH, "roles"],
101924
- [GENERATED_RESOURCES_PATH, "resources"],
101925
- [GENERATED_WORKFLOWS_PATH, "workflows"],
101926
- [GENERATED_SKILLS_PATH, "skills"],
101927
- [GENERATED_NOTIFICATION_TYPES_PATH, "notification_types"],
101928
- [GENERATED_EMAIL_LAYOUTS_PATH, "email_layouts"],
101929
- [GENERATED_WORKSPACE_FIELDS_PATH, "workspace_fields"],
101930
- [GENERATED_RECORD_BINDINGS_PATH, "record_bindings"],
101931
- [GENERATED_DOMAINS_PATH, "domains"]
101932
- ]);
101933
- function isGeneratedImport(item) {
101934
- return [...GENERATED_IMPORT_KINDS.values()].includes(item.kind);
101752
+ function knownPermissionUids(permissions) {
101753
+ return /* @__PURE__ */ new Set([
101754
+ ...systemByUid.keys(),
101755
+ ...permissions.map((permission) => permission.uid).filter((uid2) => uid2 !== null)
101756
+ ]);
101935
101757
  }
101936
- function resolveFileSpecifier(root, from, specifier) {
101937
- const request2 = specifier.startsWith(APP_PREFIX) ? specifier.slice(APP_PREFIX.length) : posix2.join(posix2.dirname(from), specifier);
101938
- const path = posix2.normalize(request2);
101939
- if (path.startsWith("../") || path === ".." || path.startsWith("/")) {
101940
- return null;
101758
+ function permissionReferenceProblem(reference, permissions) {
101759
+ const system = systemBySlug.get(reference);
101760
+ if (system !== void 0) {
101761
+ return `"${reference}" is the slug of a system permission. Use ${SYSTEM_PERMISSIONS_EXPORT}.${system.constName}.uid from ${AUTHORING_MODULE}`;
101941
101762
  }
101942
- const file2 = checkoutFile(root, path);
101943
- return file2 !== null && isExactFile(file2) ? path : null;
101944
- }
101945
- function declaredPackages(manifest) {
101946
- return /* @__PURE__ */ new Set([...Object.keys(manifest?.dependencies ?? {}), ...Object.keys(manifest?.peerDependencies ?? {})]);
101947
- }
101948
- function ownExports(ast) {
101949
- const names2 = /* @__PURE__ */ new Set();
101950
- const starTargets = [];
101951
- for (const statement2 of ast.program.body) {
101952
- if (statement2.type === "ExportDefaultDeclaration") {
101953
- names2.add("default");
101954
- } else if (statement2.type === "ExportAllDeclaration") {
101955
- if (statement2.exportKind === "type") {
101956
- continue;
101957
- }
101958
- if (statement2.exported) {
101959
- names2.add(statement2.exported.name ?? statement2.exported.value);
101960
- } else {
101961
- starTargets.push(statement2.source.value);
101962
- }
101963
- } else if (statement2.type === "ExportNamedDeclaration" && statement2.exportKind !== "type") {
101964
- const declaration = statement2.declaration;
101965
- if (declaration?.type === "VariableDeclaration") {
101966
- for (const declarator of declaration.declarations) {
101967
- for (const name of bindingNames(declarator.id)) {
101968
- names2.add(name);
101969
- }
101970
- }
101971
- } else if (declaration?.id && declaration.type !== "TSTypeAliasDeclaration" && declaration.type !== "TSInterfaceDeclaration" && !declaration.declare) {
101972
- names2.add(declaration.id.name);
101973
- }
101974
- for (const specifier of statement2.specifiers ?? []) {
101975
- if (specifier.exportKind !== "type") {
101976
- names2.add(specifier.exported.name ?? specifier.exported.value);
101977
- }
101978
- }
101979
- }
101763
+ const declared = permissions.find((permission) => permission.slug === reference);
101764
+ if (declared !== void 0) {
101765
+ return `"${reference}" is the slug of a permission. Use ${PERMISSIONS_EXPORT}.${declared.name}.uid from ${GENERATED_PERMISSIONS_MODULE}`;
101980
101766
  }
101981
- return { names: names2, starTargets };
101767
+ return `Unknown permission "${reference}". Use ${PERMISSIONS_EXPORT}.<Name>.uid from ${GENERATED_PERMISSIONS_MODULE}, or ${SYSTEM_PERMISSIONS_EXPORT}.<Name>.uid from ${AUTHORING_MODULE}`;
101982
101768
  }
101983
- function bindingNames(pattern) {
101984
- switch (pattern?.type) {
101985
- case "Identifier":
101986
- return [pattern.name];
101987
- case "ObjectPattern":
101988
- return pattern.properties.flatMap(
101989
- (property) => bindingNames(property.type === "RestElement" ? property.argument : property.value)
101990
- );
101991
- case "ArrayPattern":
101992
- return pattern.elements.flatMap((element) => bindingNames(element));
101993
- case "AssignmentPattern":
101994
- return bindingNames(pattern.left);
101995
- case "RestElement":
101996
- return bindingNames(pattern.argument);
101997
- default:
101998
- return [];
101769
+ function permissionsBinding(ast, entries) {
101770
+ const bindings = [];
101771
+ const declared = generatedBindingLocal(ast, GENERATED_PERMISSIONS_MODULE, PERMISSIONS_EXPORT);
101772
+ const system = generatedBindingLocal(ast, AUTHORING_MODULE, SYSTEM_PERMISSIONS_EXPORT);
101773
+ if (declared !== null) {
101774
+ bindings.push({
101775
+ local: declared,
101776
+ entries: entries ?? /* @__PURE__ */ Object.create(null),
101777
+ source: `${PERMISSIONS_DIRECTORY}/`
101778
+ });
101999
101779
  }
101780
+ if (system !== null) {
101781
+ bindings.push({ local: system, entries: SystemPermissions, source: AUTHORING_MODULE });
101782
+ }
101783
+ return bindings.length === 0 ? null : bindings;
102000
101784
  }
102001
- function requestedNames(statement2) {
102002
- if (statement2 === null || statement2.importKind === "type" || statement2.exportKind === "type") {
101785
+ function menuPermissionSlugWarnings(path, ast, entries) {
101786
+ const declaration = ast.program.body.find((statement2) => statement2.type === "ExportDefaultDeclaration")?.declaration;
101787
+ const menu = declaration?.type === "CallExpression" ? declaration.arguments[0] : null;
101788
+ const context = menu?.params?.[0];
101789
+ if (context?.type !== "Identifier") {
102003
101790
  return [];
102004
101791
  }
102005
- if (statement2.type === "ExportAllDeclaration") {
102006
- return ["*"];
102007
- }
102008
- if (statement2.type === "ExportNamedDeclaration") {
102009
- return (statement2.specifiers ?? []).filter((specifier) => specifier.exportKind !== "type").map(
102010
- (specifier) => specifier.type === "ExportNamespaceSpecifier" ? "*" : specifier.local.name ?? specifier.local.value
102011
- );
102012
- }
102013
- if (statement2.type !== "ImportDeclaration") {
102014
- return [];
102015
- }
102016
- return statement2.specifiers.flatMap((specifier) => {
102017
- if (specifier.type === "ImportDefaultSpecifier") {
102018
- return ["default"];
101792
+ const references = new Map([
101793
+ ...systemPermissions.map((permission) => [
101794
+ permission.slug,
101795
+ { reference: `${SYSTEM_PERMISSIONS_EXPORT}.${permission.constName}.uid`, module: AUTHORING_MODULE }
101796
+ ]),
101797
+ ...Object.entries(entries).map(([name, entry]) => [
101798
+ entry.slug,
101799
+ { reference: `${PERMISSIONS_EXPORT}.${name}.uid`, module: GENERATED_PERMISSIONS_MODULE }
101800
+ ])
101801
+ ]);
101802
+ const slugMembers = new Map(
101803
+ (permissionsBinding(ast, entries) ?? []).map((binding) => [binding.local, binding.entries])
101804
+ );
101805
+ const slugOf = (argument) => {
101806
+ if (argument?.type === "StringLiteral") {
101807
+ return argument.value;
102019
101808
  }
102020
- if (specifier.type === "ImportNamespaceSpecifier") {
102021
- return ["*"];
101809
+ const segments = memberPathSegments(argument);
101810
+ const bindingEntries = segments?.length === 3 && segments[2] === "slug" ? slugMembers.get(segments[0]) : void 0;
101811
+ return bindingEntries !== void 0 && Object.hasOwn(bindingEntries, segments[1]) ? bindingEntries[segments[1]].slug : null;
101812
+ };
101813
+ const warnings2 = [];
101814
+ const pending = [menu.body];
101815
+ while (pending.length > 0) {
101816
+ const current = pending.pop();
101817
+ pending.push(...childNodes(current));
101818
+ const callee = current.type === "CallExpression" ? current.callee : null;
101819
+ const argument = current.arguments?.[0];
101820
+ if (callee?.type !== "MemberExpression" || callee.computed || callee.object.type !== "Identifier" || callee.object.name !== context.name || callee.property.name !== "can") {
101821
+ continue;
102022
101822
  }
102023
- if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type") {
102024
- return [specifier.imported.name ?? specifier.imported.value];
101823
+ const slug = slugOf(argument);
101824
+ if (slug === null || !references.has(slug)) {
101825
+ continue;
102025
101826
  }
102026
- return [];
101827
+ const { reference, module } = references.get(slug);
101828
+ warnings2.push(generatedReferenceDiagnostic(path, argument, reference, module));
101829
+ }
101830
+ return warnings2;
101831
+ }
101832
+
101833
+ // scripts/lib/runtime-build/role-references.mjs
101834
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
101835
+ var ROLES_DIRECTORY = "roles";
101836
+ var LEGACY_ROLES_PATH = "roles.ts";
101837
+ var GENERATED_ROLES_PATH = "generated/roles.ts";
101838
+ var ROLES_EXPORT = "Roles";
101839
+ var SYSTEM_ROLES_EXPORT = "SystemRoles";
101840
+ var OPTIONS2 = /* @__PURE__ */ new Set(["uid", "slug", "name", "description", "resource", "permissions"]);
101841
+ var MAX_LENGTH2 = 255;
101842
+ var systemRoles = Object.entries(SystemRoles).map(([constName, role]) => ({
101843
+ constName,
101844
+ ...role
101845
+ }));
101846
+ var systemBySlug2 = new Map(systemRoles.map((role) => [role.slug, role]));
101847
+ var systemByName2 = new Map(systemRoles.map((role) => [role.name, role]));
101848
+ var systemByUid2 = new Map(systemRoles.map((role) => [role.uid, role]));
101849
+ function defineRoleArgument(ast) {
101850
+ const { declaration } = defaultExportOf(ast, {
101851
+ extraImports: [GENERATED_RESOURCES_MODULE, GENERATED_PERMISSIONS_MODULE]
102027
101852
  });
101853
+ return expectDefineCall(declaration, "defineRole", 1)[0];
102028
101854
  }
102029
- function missingFileMessage(root, path, specifier, importType) {
102030
- const message = `Cannot find "${specifier}" from ${path}`;
102031
- const suggestion = importType === "app" ? suggestedRelativeSpecifier(root, path, specifier) : null;
102032
- return suggestion === null || suggestion === specifier ? message : `${message}. Use "${suggestion}"`;
101855
+ function systemRoleMessage(slug, what, system) {
101856
+ return `Role "${slug}" has the ${what} of the system role ${SYSTEM_ROLES_EXPORT}.${system.constName}. The platform declares that role, and it holds every permission, so do not declare it. Give this role another ${what}`;
102033
101857
  }
102034
- function checkModuleImports(root, path, ast, packages) {
102035
- const diagnostics = [];
102036
- const imports = [];
102037
- let blocksUnitBuild = false;
102038
- for (const found2 of moduleSpecifiers(ast)) {
102039
- if (found2.specifier === null) {
102040
- diagnostics.push(diagnosticAt(path, found2.node, "A dynamic import must name its module with a string literal"));
102041
- continue;
102042
- }
102043
- if (found2.typeOnly) {
102044
- continue;
102045
- }
102046
- const importType = importKind(found2.specifier);
102047
- const refused = unsupportedImportMessage(
102048
- found2.specifier,
102049
- importType,
102050
- importType === "alias" ? suggestedRelativeSpecifier(root, path, found2.specifier) : null
101858
+ function buildRole(path, definition, bindings, known, diagnostics) {
101859
+ const { slug, name } = definitionFileSlug(path, definition, { noun: "role", exportName: ROLES_EXPORT });
101860
+ if (definition.type !== "ObjectExpression") {
101861
+ throw new SourceError("defineRole(...) takes an object literal", definition);
101862
+ }
101863
+ const { value } = staticObject(definition, {
101864
+ resources: bindings.resources,
101865
+ permissions: bindings.permissions
101866
+ });
101867
+ if (!isPlainObject2(value)) {
101868
+ throw new SourceError("defineRole(...) takes an object literal", definition);
101869
+ }
101870
+ refuseUnknownOptions2(value, definition, OPTIONS2, "role", slug);
101871
+ if (typeof value.name !== "string" || value.name.trim() === "" || value.name.length > MAX_LENGTH2) {
101872
+ throw new SourceError(
101873
+ `Role "${slug}" needs a "name" of 1 to ${MAX_LENGTH2} characters`,
101874
+ definition
102051
101875
  );
102052
- if (refused !== null) {
102053
- diagnostics.push(diagnosticAt(path, found2.node, refused));
102054
- blocksUnitBuild = true;
102055
- continue;
102056
- }
102057
- if (importType === "host") {
102058
- imports.push({
102059
- specifier: found2.specifier,
102060
- kind: "host",
102061
- target: found2.specifier,
102062
- dynamic: found2.dynamic,
102063
- names: found2.dynamic ? [] : requestedNames(found2.statement),
102064
- node: found2.node
102065
- });
102066
- continue;
102067
- }
102068
- if (importType === "package") {
102069
- if (!packages.has(packageName(found2.specifier))) {
102070
- diagnostics.push(
102071
- diagnosticAt(
102072
- path,
102073
- found2.node,
102074
- `"${packageName(found2.specifier)}" is not a dependency. Add it to "dependencies" in package.json`
102075
- )
102076
- );
102077
- continue;
102078
- }
102079
- imports.push({
102080
- specifier: found2.specifier,
102081
- kind: "package",
102082
- target: found2.specifier,
102083
- dynamic: found2.dynamic,
102084
- package_names: found2.dynamic ? ["*"] : requestedNames(found2.statement)
102085
- });
102086
- continue;
102087
- }
102088
- const target = importType === "app" ? resolveLocalSpecifier(root, path, found2.specifier) : resolveFileSpecifier(root, path, found2.specifier);
102089
- if (target === null) {
102090
- diagnostics.push(diagnosticAt(path, found2.node, missingFileMessage(root, path, found2.specifier, importType)));
102091
- blocksUnitBuild ||= importType === "app" && !found2.dynamic;
102092
- continue;
102093
- }
102094
- const testSource = testSourceImportMessage(path, target);
102095
- if (testSource !== null) {
102096
- diagnostics.push(diagnosticAt(path, found2.node, testSource));
102097
- blocksUnitBuild = true;
102098
- continue;
102099
- }
102100
- if (GENERATED_IMPORT_KINDS.has(target)) {
102101
- imports.push({
102102
- specifier: found2.specifier,
102103
- kind: GENERATED_IMPORT_KINDS.get(target),
102104
- target,
102105
- dynamic: found2.dynamic
102106
- });
102107
- continue;
102108
- }
102109
- imports.push({
102110
- specifier: found2.specifier,
102111
- kind: importType,
102112
- target,
102113
- dynamic: found2.dynamic,
102114
- names: requestedNames(found2.statement),
102115
- node: found2.node
102116
- });
102117
101876
  }
102118
- return { diagnostics, imports, blocksUnitBuild };
102119
- }
102120
- function buildModuleGraph(root, entries, packages, diagnostics, assetKeys = /* @__PURE__ */ new Set(), generated = /* @__PURE__ */ new Map()) {
102121
- const scannedStyles = /* @__PURE__ */ new Set();
102122
- const modules = {};
102123
- const parsed = new Map(entries.map((entry) => [entry.path, entry]));
102124
- const pending = entries.map((entry) => entry.path);
102125
- const usedPackages = /* @__PURE__ */ new Set();
102126
- while (pending.length > 0) {
102127
- const path = pending.shift();
102128
- if (Object.hasOwn(modules, path)) {
102129
- continue;
102130
- }
102131
- const kind = importKind(`./${posix2.basename(path)}`);
102132
- if (STYLE_KINDS.has(kind)) {
102133
- checkStylesheet(root, path, assetKeys, diagnostics, scannedStyles);
102134
- modules[path] = { kind, source_sha256: sha256(readFileSync7(join9(root, path))), imports: [] };
102135
- continue;
102136
- }
102137
- let entry = parsed.get(path);
102138
- if (entry === void 0) {
102139
- const source = readFileSync7(join9(root, path), "utf8");
102140
- try {
102141
- entry = { path, source, ast: parseSource(source, { jsx: path.endsWith("x") }) };
102142
- } catch (error) {
102143
- diagnostics.push(diagnosticAt(path, null, `The module does not parse: ${error.message}`));
102144
- modules[path] = { kind: "module", source_sha256: sha256(source), imports: [], exports: null };
102145
- continue;
102146
- }
102147
- parsed.set(path, entry);
102148
- }
102149
- const comments = entry.ast.comments ?? [];
102150
- let commentIndex = 0;
102151
- for (const match of entry.source.matchAll(/url\(\s*['"]?asset:/gi)) {
102152
- while (commentIndex < comments.length && comments[commentIndex].end <= match.index) {
102153
- commentIndex++;
102154
- }
102155
- if (commentIndex < comments.length && comments[commentIndex].start <= match.index) {
102156
- continue;
102157
- }
102158
- const prefix2 = entry.source.slice(0, match.index);
102159
- diagnostics.push(
102160
- diagnostic(
102161
- path,
102162
- prefix2.split("\n").length,
102163
- match.index - prefix2.lastIndexOf("\n"),
102164
- "asset: URLs work only in CSS url() and in email layout and template HTML. Move this background into a CSS file. In code, use Assets.<Name>.url from @app/generated/assets"
102165
- )
102166
- );
102167
- }
102168
- const checked = checkModuleImports(root, path, entry.ast, packages);
102169
- diagnostics.push(...checked.diagnostics);
102170
- const workflows = generated.get(GENERATED_WORKFLOWS_PATH) ?? null;
102171
- if (workflows !== null) {
102172
- diagnostics.push(...pageWorkflowReferenceDiagnostics(path, entry.ast, workflows.entries));
102173
- }
102174
- const { imports } = checked;
102175
- for (const item of imports) {
102176
- if (item.kind === "package") {
102177
- usedPackages.add(item.specifier);
102178
- } else if (item.kind !== "host" && !isGeneratedImport(item)) {
102179
- pending.push(item.target);
102180
- }
102181
- }
102182
- if (imports.some(isGeneratedImport)) {
102183
- checkGeneratedReferences(root, entry, generated, diagnostics);
102184
- }
102185
- modules[path] = { kind: "module", source_sha256: sha256(entry.source), imports, exports: ownExports(entry.ast) };
101877
+ const description = value.description ?? null;
101878
+ if (description !== null && typeof description !== "string") {
101879
+ throw new SourceError(
101880
+ `The "description" of role "${slug}" must be a string`,
101881
+ propertyNode(definition, "description")
101882
+ );
102186
101883
  }
102187
- checkLinkage(modules, diagnostics);
102188
- for (const module of Object.values(modules)) {
102189
- for (const item of module.imports) {
102190
- delete item.node;
102191
- if (item.kind === "host") {
102192
- delete item.names;
102193
- }
102194
- }
102195
- delete module.exports;
101884
+ const resource = value.resource ?? null;
101885
+ const resourceNode = propertyNode(definition, "resource");
101886
+ if (resource !== null && typeof resource !== "string") {
101887
+ throw new SourceError(
101888
+ `The "resource" of role "${slug}" must be Resources.<Name>.slug`,
101889
+ resourceNode
101890
+ );
101891
+ }
101892
+ const permissions = value.permissions;
101893
+ const permissionsNode = propertyNode(definition, "permissions");
101894
+ if (!Array.isArray(permissions)) {
101895
+ throw new SourceError(
101896
+ `Role "${slug}" needs "permissions": a list of Permissions.<Name>.uid or SystemPermissions.<Name>.uid. Use [] for a role that grants no permission`,
101897
+ permissionsNode ?? definition
101898
+ );
102196
101899
  }
102197
- return { modules, packages: [...usedPackages].toSorted() };
101900
+ const role = {
101901
+ key: slug,
101902
+ name,
101903
+ uid: null,
101904
+ slug,
101905
+ label: value.name,
101906
+ description,
101907
+ resource,
101908
+ permissions,
101909
+ path,
101910
+ node: definition
101911
+ };
101912
+ checkRoleResource(role, resourceNode, known, diagnostics);
101913
+ checkRolePermissions(
101914
+ role,
101915
+ permissionsNode,
101916
+ knownPermissionUids(known.permissions),
101917
+ known.permissions,
101918
+ diagnostics
101919
+ );
101920
+ return role;
102198
101921
  }
102199
- function checkGeneratedReferences(root, entry, generated, diagnostics) {
102200
- const generatedModuleOf = (specifier) => generated.get(resolveLocalSpecifier(root, entry.path, specifier)) ?? null;
102201
- const { problems, otherUses } = inlineGeneratedValues(entry.source, entry.ast, generatedModuleOf);
102202
- for (const problem2 of problems) {
102203
- diagnostics.push(diagnosticAt(entry.path, problem2.node, problem2.message));
101922
+ function checkRoleResource(role, node, known, diagnostics) {
101923
+ if (role.resource === null) {
101924
+ return;
102204
101925
  }
102205
- for (const { node, exportName, exampleMember } of otherUses) {
101926
+ const resource = known.resources.find((item) => item.slug === role.resource);
101927
+ if (resource === void 0 || BUILT_IN_RESOURCE_SLUGS.has(role.resource)) {
102206
101928
  diagnostics.push(
102207
101929
  diagnosticAt(
102208
- entry.path,
101930
+ role.path,
102209
101931
  node,
102210
- `Read a value such as ${exportName}.<Name>.${exampleMember}. The build replaces each reference with its value, so a page cannot use ${exportName} as a whole`
101932
+ `The "resource" of role "${role.slug}" is "${role.resource}", which is not a resource of the files. Use Resources.<Name>.slug of an authenticatable resource`
102211
101933
  )
102212
101934
  );
102213
- }
102214
- for (const found2 of moduleSpecifiers(entry.ast)) {
102215
- const values = found2.specifier === null || found2.typeOnly ? null : generatedModuleOf(found2.specifier);
102216
- if (values === null) {
102217
- continue;
102218
- }
102219
- if (found2.dynamic) {
102220
- diagnostics.push(diagnosticAt(entry.path, found2.node, `Import ${values.exportName} with a static import`));
102221
- } else if (found2.statement?.type !== "ImportDeclaration") {
102222
- diagnostics.push(
102223
- diagnosticAt(entry.path, found2.node, `A page module cannot re-export ${values.exportName}. Import it where you read it`)
102224
- );
102225
- }
102226
- }
102227
- }
102228
- var ROW_MENU_MEMBERS = /* @__PURE__ */ new Set(["navigationMenu", "navigationMenuIds"]);
102229
- var NAVIGATION_MENU_REMOVED = "navigationMenu is not available in file-based workspaces. Import the menu module and pass it to useMenu";
102230
- function pagesSdkNameMessage(name) {
102231
- if (name === "*" || Object.hasOwn(PAGE_SDK_EXPORTS, name) || Object.hasOwn(PAGE_SDK_TYPES, name)) {
102232
- return null;
102233
- }
102234
- if (name === "default") {
102235
- return `${PAGES_SDK_MODULE} has no default export`;
102236
- }
102237
- if (ROW_MENU_MEMBERS.has(name)) {
102238
- return NAVIGATION_MENU_REMOVED;
102239
- }
102240
- return name === "Sdk" ? `"Sdk" is not exported by ${PAGES_SDK_MODULE}. Import each member by name` : `"${name}" is not exported by ${PAGES_SDK_MODULE}`;
102241
- }
102242
- function checkLinkage(modules, diagnostics) {
102243
- const resolved = /* @__PURE__ */ new Map();
102244
- const exportsOf = (path, visiting = /* @__PURE__ */ new Set()) => {
102245
- if (resolved.has(path)) {
102246
- return resolved.get(path);
102247
- }
102248
- const module = modules[path];
102249
- if (module?.exports === null || module?.exports === void 0 || visiting.has(path)) {
102250
- return null;
102251
- }
102252
- visiting.add(path);
102253
- const names2 = new Set(module.exports.names);
102254
- for (const specifier of module.exports.starTargets) {
102255
- const item = module.imports.find((candidate) => candidate.specifier === specifier);
102256
- const target = item?.kind === "app" ? exportsOf(item.target, visiting) : null;
102257
- if (target === null) {
102258
- resolved.set(path, null);
102259
- return null;
102260
- }
102261
- for (const name of target) {
102262
- if (name !== "default") {
102263
- names2.add(name);
102264
- }
102265
- }
102266
- }
102267
- resolved.set(path, names2);
102268
- return names2;
102269
- };
102270
- for (const [path, module] of Object.entries(modules)) {
102271
- for (const item of module.imports) {
102272
- if (item.kind === "host" && item.target === PAGES_SDK_MODULE) {
102273
- for (const name of item.names) {
102274
- const message = pagesSdkNameMessage(name);
102275
- if (message !== null) {
102276
- diagnostics.push(diagnosticAt(path, item.node, message));
102277
- }
102278
- }
102279
- continue;
102280
- }
102281
- if (item.kind !== "app" || item.names.length === 0) {
102282
- continue;
102283
- }
102284
- const available = exportsOf(item.target);
102285
- if (available === null) {
102286
- continue;
102287
- }
102288
- for (const name of item.names) {
102289
- if (name !== "*" && !available.has(name)) {
102290
- diagnostics.push(
102291
- diagnosticAt(
102292
- path,
102293
- item.node,
102294
- name === "default" ? `${item.target} has no default export` : `"${name}" is not exported by ${item.target}`
102295
- )
102296
- );
102297
- }
102298
- }
102299
- }
102300
- }
102301
- }
102302
- function checkStylesheet(root, path, assetKeys, diagnostics, scanned) {
102303
- if (scanned.has(path)) {
102304
101935
  return;
102305
101936
  }
102306
- scanned.add(path);
102307
- const { urls, imports } = cssReferences(readFileSync7(join9(root, path), "utf8"));
102308
- for (const url of urls) {
102309
- const key = assetUrlKey(url.value);
102310
- if (key !== null && assetKeys !== null && !assetKeys.has(key)) {
102311
- diagnostics.push(diagnostic(path, url.line, url.column, `Unknown asset "${key}". Add it to assets.ts`));
102312
- } else if (!isExternalCssUrl(url.value)) {
102313
- diagnostics.push(diagnostic(path, url.line, url.column, binaryCssUrlMessage(url.value)));
102314
- }
101937
+ if (!Object.hasOwn(resource.capabilities ?? {}, "authenticatable")) {
101938
+ diagnostics.push(
101939
+ diagnosticAt(
101940
+ role.path,
101941
+ node,
101942
+ `The "resource" of role "${role.slug}" is "${role.resource}", which does not have the authenticatable capability. A role gives its permissions to signed-in records, so name an authenticatable resource`
101943
+ )
101944
+ );
102315
101945
  }
102316
- for (const target of imports) {
102317
- if (assetUrlKey(target.value) !== null) {
101946
+ }
101947
+ function checkRolePermissions(role, node, permissionUids, permissions, diagnostics) {
101948
+ const seen = /* @__PURE__ */ new Set();
101949
+ role.permissions.forEach((permission, position) => {
101950
+ const permissionNode = elementNode(node, position);
101951
+ if (typeof permission !== "string" || !permissionUids.has(permission)) {
101952
+ const problem2 = typeof permission === "string" ? permissionReferenceProblem(permission, permissions) : "Use Permissions.<Name>.uid or SystemPermissions.<Name>.uid";
102318
101953
  diagnostics.push(
102319
- diagnostic(path, target.line, target.column, "asset: URLs work only in CSS url() and in email layout and template HTML")
101954
+ diagnosticAt(role.path, permissionNode, `Role "${role.slug}" permissions: ${problem2}`)
102320
101955
  );
102321
- continue;
102322
- }
102323
- if (isExternalCssUrl(target.value)) {
102324
- continue;
102325
- }
102326
- const binary = binaryCssImportMessage(target.value);
102327
- if (binary !== null) {
102328
- diagnostics.push(diagnostic(path, target.line, target.column, binary));
102329
- continue;
101956
+ return;
102330
101957
  }
102331
- const resolved = resolveCssReference(root, path, target.value);
102332
- if (resolved === null) {
102333
- diagnostics.push(diagnostic(path, target.line, target.column, `Cannot find "${target.value}" from ${path}`));
102334
- continue;
101958
+ if (seen.has(permission)) {
101959
+ diagnostics.push(
101960
+ diagnosticAt(
101961
+ role.path,
101962
+ permissionNode,
101963
+ `Role "${role.slug}" lists the permission "${permission}" twice`
101964
+ )
101965
+ );
102335
101966
  }
102336
- checkStylesheet(root, resolved, assetKeys, diagnostics, scanned);
102337
- }
102338
- }
102339
-
102340
- // scripts/lib/runtime-build/app-modules.mjs
102341
- var APP_IMPORT = "__appImport";
102342
- var PRELUDE_SKIPPED_KINDS = /* @__PURE__ */ new Set(["host", "package", "style", "style_module", "binary"]);
102343
- var AUTHORING_HELPERS_SOURCE = objectLiteral(cli_exports);
102344
- var AUTHORING_HELPERS_MODULE = Object.entries(cli_exports).map(([name, value]) => `export const ${name} = ${helperSource(value)};
102345
- `).join("");
102346
- function helperSource(value) {
102347
- if (typeof value === "function") {
102348
- return String(value);
102349
- }
102350
- return value !== null && typeof value === "object" ? objectLiteral(value) : JSON.stringify(value);
102351
- }
102352
- function objectLiteral(entries) {
102353
- const members = Object.entries(entries).map(([name, value]) => `${name}: ${helperSource(value)}`);
102354
- return `{ ${members.join(", ")} }`;
102355
- }
102356
- function isAppSpecifier(specifier) {
102357
- return specifier.startsWith(APP_PREFIX);
102358
- }
102359
- function resolveAppSpecifier(root, specifier) {
102360
- return isAppSpecifier(specifier) ? resolveLocalSpecifier(root, "", specifier) : null;
102361
- }
102362
- function namesWorkspaceFile(specifier, ui) {
102363
- return isAppSpecifier(specifier) || ui && importKind(specifier) === "app";
101967
+ seen.add(permission);
101968
+ });
102364
101969
  }
102365
- function appImportsOf(root, path, ast, { ui = false } = {}) {
102366
- const imports = [];
102367
- for (const statement2 of ast.program.body) {
102368
- if (statement2.type !== "ImportDeclaration" || !namesWorkspaceFile(statement2.source.value, ui)) {
102369
- continue;
102370
- }
102371
- const target = resolveLocalSpecifier(root, path, statement2.source.value);
102372
- if (target === null) {
102373
- const suggestion = suggestedRelativeSpecifier(root, path, statement2.source.value);
102374
- const message = isAppSpecifier(statement2.source.value) ? `Cannot find "${statement2.source.value}". An @app/ import names a file from the workspace root, such as @app/lib/format` : `Cannot find "${statement2.source.value}" from ${path}`;
102375
- throw new SourceError(
102376
- suggestion === null || suggestion === statement2.source.value ? message : `${message}. Use "${suggestion}"`,
102377
- statement2.source
101970
+ function checkRoles(roles, diagnostics) {
101971
+ for (const role of roles) {
101972
+ const systemSlug = systemBySlug2.get(role.slug);
101973
+ if (systemSlug !== void 0) {
101974
+ diagnostics.push(
101975
+ diagnosticAt(role.path, null, systemRoleMessage(role.slug, "slug", systemSlug))
102378
101976
  );
102379
101977
  }
102380
- const testSource = testSourceImportMessage(path, target);
102381
- if (testSource !== null) {
102382
- throw new SourceError(testSource, statement2.source);
102383
- }
102384
- imports.push({ statement: statement2, specifier: statement2.source.value, path: target, from: path });
102385
- }
102386
- return imports;
102387
- }
102388
- function appBindings(source, imports) {
102389
- return imports.map(({ statement: statement2, path }) => ({
102390
- start: statement2.start,
102391
- end: statement2.end,
102392
- text: bindingFor(statement2, path),
102393
- original: sliceOf(source, statement2)
102394
- }));
102395
- }
102396
- function bindingFor(statement2, path) {
102397
- if (statement2.importKind === "type") {
102398
- return "";
102399
- }
102400
- const load = `${APP_IMPORT}(${JSON.stringify(path)})`;
102401
- const named = [];
102402
- const statements2 = [];
102403
- for (const specifier of statement2.specifiers) {
102404
- if (specifier.type === "ImportDefaultSpecifier") {
102405
- statements2.push(`const ${specifier.local.name} = ${load}.default;`);
102406
- } else if (specifier.type === "ImportNamespaceSpecifier") {
102407
- statements2.push(`const ${specifier.local.name} = ${load};`);
102408
- } else if (specifier.importKind !== "type") {
102409
- const imported = specifier.imported.type === "StringLiteral" ? JSON.stringify(specifier.imported.value) : specifier.imported.name;
102410
- named.push(
102411
- imported === specifier.local.name ? imported : `${imported}: ${specifier.local.name}`
101978
+ const systemName = systemByName2.get(role.label);
101979
+ if (systemName !== void 0) {
101980
+ diagnostics.push(
101981
+ diagnosticAt(role.path, role.node, systemRoleMessage(role.slug, "name", systemName))
102412
101982
  );
102413
101983
  }
102414
101984
  }
102415
- if (named.length > 0) {
102416
- statements2.push(`const { ${named.join(", ")} } = ${load};`);
102417
- }
102418
- if (statements2.length === 0) {
102419
- statements2.push(`${load};`);
102420
- }
102421
- return statements2.join(" ");
101985
+ checkDuplicateDefinitions(roles, "roles", ROLES_EXPORT, diagnostics);
102422
101986
  }
102423
- function appModuleClosure(root, imports, external = /* @__PURE__ */ new Set(), { ui = false, transform: transform3 = null } = {}) {
102424
- const modules = /* @__PURE__ */ new Map();
102425
- const pending = imports.map((item) => item.path);
102426
- while (pending.length > 0) {
102427
- const path = pending.shift();
102428
- if (modules.has(path)) {
102429
- continue;
102430
- }
102431
- const read2 = readFileSync8(join10(root, path), "utf8");
102432
- const source = transform3 === null ? read2 : transform3(path, read2);
102433
- const ast = parseModule(path, source);
102434
- const requires = {};
102435
- const foreign = {};
102436
- const references = ui ? moduleSpecifiers(ast).filter((item) => item.specifier !== null && !item.typeOnly).map((item) => ({ specifier: item.specifier, source: item.node })) : ast.program.body.filter(
102437
- (statement2) => statement2.type === "ImportDeclaration" || statement2.type === "ExportAllDeclaration" || statement2.type === "ExportNamedDeclaration"
102438
- ).map((statement2) => ({ specifier: statement2.source?.value, source: statement2.source }));
102439
- for (const statement2 of references) {
102440
- const specifier = statement2.specifier;
102441
- if (specifier === void 0 || isAuthoringModule(specifier) || external.has(specifier)) {
102442
- continue;
102443
- }
102444
- const kind = importKind(specifier);
102445
- if (ui && PRELUDE_SKIPPED_KINDS.has(kind)) {
102446
- const value = foreignValue(root, path, specifier, kind);
102447
- if (value !== null) {
102448
- foreign[specifier] = value;
102449
- }
102450
- continue;
102451
- }
102452
- if (ui && unsupportedImportMessage(specifier, kind) !== null) {
102453
- continue;
102454
- }
102455
- if (!namesWorkspaceFile(specifier, ui)) {
102456
- throw new SourceError(
102457
- `${path} imports "${specifier}". A workspace module can import only ${[AUTHORING_MODULE, ...external].map((name) => `"${name}"`).join(", ")}, and @app/ files`,
102458
- statement2.source
102459
- );
102460
- }
102461
- const target = resolveLocalSpecifier(root, path, specifier);
102462
- if (target === null) {
102463
- if (ui) {
102464
- continue;
102465
- }
102466
- throw new SourceError(
102467
- `${path} imports "${specifier}", which does not exist`,
102468
- statement2.source
102469
- );
102470
- }
102471
- const testSource = testSourceImportMessage(path, target);
102472
- if (testSource !== null) {
102473
- throw new SourceError(testSource, statement2.source);
102474
- }
102475
- requires[specifier] = target;
102476
- pending.push(target);
101987
+ function checkRoleUids(roles, diagnostics) {
101988
+ for (const role of roles) {
101989
+ const system = role.uid === null ? void 0 : systemByUid2.get(role.uid);
101990
+ if (system !== void 0) {
101991
+ diagnostics.push(
101992
+ diagnosticAt(role.path, role.node, systemRoleMessage(role.slug, "uid", system))
101993
+ );
102477
101994
  }
102478
- modules.set(path, {
102479
- source,
102480
- requires,
102481
- foreign,
102482
- pagesNames: ui ? pagesSdkNames(ast) : []
102483
- });
102484
- }
102485
- return modules;
102486
- }
102487
- function foreignValue(root, path, specifier, kind) {
102488
- switch (kind) {
102489
- case "package":
102490
- return `{ __esModule: true, ...${packageExpression(specifier)} }`;
102491
- case "style_module":
102492
- return styleModuleExpression(resolveLocalSpecifier(root, path, specifier));
102493
- case "style":
102494
- return "{}";
102495
- default:
102496
- return null;
102497
101995
  }
102498
101996
  }
102499
- function pagesSdkNames(ast) {
102500
- return moduleSpecifiers(ast).filter((item) => item.specifier === PAGES_SDK_MODULE && !item.typeOnly).flatMap((item) => item.dynamic ? ["*"] : requestedNames(item.statement));
101997
+ function generatedRolesSource(entries) {
101998
+ return generatedModuleSource(ROLES_EXPORT, entries);
102501
101999
  }
102502
- function parseModule(path, source) {
102503
- try {
102504
- return parseSource(source, { jsx: path.endsWith("x") });
102505
- } catch (error) {
102506
- throw new SourceError(`${path} does not parse: ${error.message}`, null);
102507
- }
102000
+ function roleValues(entries) {
102001
+ return { entries, exportName: ROLES_EXPORT, noun: "role", directory: "roles/", exampleMember: "uid" };
102508
102002
  }
102509
- function appPrelude(modules) {
102510
- if (modules.size === 0) {
102511
- return "";
102512
- }
102513
- const hasForeign = [...modules.values()].some((module) => Object.keys(module.foreign ?? {}).length > 0);
102514
- const entries = [...modules].map(([path, module]) => {
102515
- const code2 = compileModule(path, module.source);
102516
- const foreign = Object.entries(module.foreign ?? {}).map(([specifier, value]) => `${JSON.stringify(specifier)}: () => (${value})`);
102517
- const foreignEntry = hasForeign ? `, { ${foreign.join(", ")} }` : "";
102518
- return `${JSON.stringify(path)}: [function (exports, require, module) {
102519
- ${code2}
102520
- }, ${JSON.stringify(module.requires)}${foreignEntry}]`;
102521
- });
102522
- const foreignRequire = hasForeign ? `
102523
- if (foreign[specifier] !== undefined) {
102524
- return foreign[specifier]();
102525
- }
102526
- ` : "";
102527
- const pagesNames = new Set([...modules.values()].flatMap((module) => module.pagesNames));
102528
- const pagesSdk = pagesNames.has("*") ? pagesSdkObjectText() : pagesSdkObjectText([...pagesNames].toSorted());
102529
- return `const ${APP_IMPORT} = ((modules, outer) => {
102530
- const cache = {};
102531
- const runtime = ${AUTHORING_HELPERS_SOURCE};
102532
- const pagesSdk = typeof Sdk === 'undefined' ? null : ${pagesSdk};
102533
- const load = (path) => {
102534
- if (cache[path] !== undefined) {
102535
- return cache[path].exports;
102536
- }
102537
-
102538
- const [factory, requires${hasForeign ? ", foreign" : ""}] = modules[path];
102539
- const module = { exports: {} };
102540
- cache[path] = module;
102541
- const require = (specifier) => {${foreignRequire}
102542
- if (specifier === ${JSON.stringify(AUTHORING_MODULE)}) {
102543
- return runtime;
102544
- }
102545
-
102546
- if (specifier === ${JSON.stringify(PAGES_SDK_MODULE)} && pagesSdk !== null) {
102547
- return pagesSdk;
102548
- }
102549
102003
 
102550
- if (specifier === 'react' && typeof React !== 'undefined') {
102551
- return React;
102552
- }
102004
+ // scripts/lib/runtime-build/workspace-field-references.mjs
102005
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
102006
+ import { basename as basename9 } from "node:path";
102553
102007
 
102554
- return requires[specifier] === undefined ? outer(specifier) : load(requires[specifier]);
102555
- };
102556
- factory(module.exports, require, module);
102008
+ // scripts/lib/runtime-build/workspace-fields.mjs
102009
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
102010
+ import { readFileSync as readFileSync8 } from "node:fs";
102011
+ import { basename as basename8, join as join11 } from "node:path";
102557
102012
 
102558
- return module.exports;
102559
- };
102013
+ // packages/cli/workspace-settings-catalog.json
102014
+ var workspace_settings_catalog_default = {
102015
+ settings: {
102016
+ ai_custom_system_prompt: {
102017
+ type: "text",
102018
+ label: "AI Custom System Prompt",
102019
+ default: null,
102020
+ values: null,
102021
+ max: null,
102022
+ url: false,
102023
+ pattern: null
102024
+ },
102025
+ custom_401_error_page: {
102026
+ type: "page_reference",
102027
+ label: "Custom 401 Error Page",
102028
+ default: null,
102029
+ values: null,
102030
+ max: null,
102031
+ url: false,
102032
+ pattern: null
102033
+ },
102034
+ custom_403_error_page: {
102035
+ type: "page_reference",
102036
+ label: "Custom 403 Error Page",
102037
+ default: null,
102038
+ values: null,
102039
+ max: null,
102040
+ url: false,
102041
+ pattern: null
102042
+ },
102043
+ custom_404_error_page: {
102044
+ type: "page_reference",
102045
+ label: "Custom 404 Error Page",
102046
+ default: null,
102047
+ values: null,
102048
+ max: null,
102049
+ url: false,
102050
+ pattern: null
102051
+ },
102052
+ custom_422_error_page: {
102053
+ type: "page_reference",
102054
+ label: "Custom 422 Error Page",
102055
+ default: null,
102056
+ values: null,
102057
+ max: null,
102058
+ url: false,
102059
+ pattern: null
102060
+ },
102061
+ custom_500_error_page: {
102062
+ type: "page_reference",
102063
+ label: "Custom 500 Error Page",
102064
+ default: null,
102065
+ values: null,
102066
+ max: null,
102067
+ url: false,
102068
+ pattern: null
102069
+ },
102070
+ default_currency: {
102071
+ type: "select",
102072
+ label: "Default Currency",
102073
+ default: "usd",
102074
+ values: [
102075
+ "aed",
102076
+ "ars",
102077
+ "aud",
102078
+ "brl",
102079
+ "cad",
102080
+ "chf",
102081
+ "clp",
102082
+ "cny",
102083
+ "cop",
102084
+ "czk",
102085
+ "dkk",
102086
+ "eur",
102087
+ "gbp",
102088
+ "hkd",
102089
+ "idr",
102090
+ "ils",
102091
+ "inr",
102092
+ "jpy",
102093
+ "krw",
102094
+ "mxn",
102095
+ "myr",
102096
+ "nok",
102097
+ "nzd",
102098
+ "pen",
102099
+ "php",
102100
+ "pln",
102101
+ "sar",
102102
+ "sek",
102103
+ "sgd",
102104
+ "thb",
102105
+ "twd",
102106
+ "usd",
102107
+ "zar"
102108
+ ],
102109
+ max: null,
102110
+ url: false,
102111
+ pattern: null
102112
+ },
102113
+ default_timezone: {
102114
+ type: "timezone",
102115
+ label: "Default Timezone",
102116
+ default: "America/Chicago",
102117
+ values: null,
102118
+ max: null,
102119
+ url: false,
102120
+ pattern: null
102121
+ },
102122
+ fathom_site_id: {
102123
+ type: "text",
102124
+ label: "Fathom Site ID",
102125
+ default: null,
102126
+ values: null,
102127
+ max: null,
102128
+ url: false,
102129
+ pattern: null
102130
+ },
102131
+ head_html: {
102132
+ type: "text",
102133
+ label: "Custom Head HTML",
102134
+ default: null,
102135
+ values: null,
102136
+ max: 5e4,
102137
+ url: false,
102138
+ pattern: null
102139
+ },
102140
+ sidebar_icon: {
102141
+ type: "text",
102142
+ label: "Sidebar Icon",
102143
+ default: "building-2",
102144
+ values: null,
102145
+ max: null,
102146
+ url: false,
102147
+ pattern: null
102148
+ },
102149
+ sidebar_icon_color: {
102150
+ type: "color",
102151
+ label: "Sidebar Icon Color",
102152
+ default: "#2B3990",
102153
+ values: null,
102154
+ max: 256,
102155
+ url: false,
102156
+ pattern: "^[#A-Za-z0-9 .,%+\\-\\/()]+$"
102157
+ },
102158
+ website: {
102159
+ type: "text",
102160
+ label: "Website",
102161
+ default: null,
102162
+ values: null,
102163
+ max: null,
102164
+ url: true,
102165
+ pattern: null
102166
+ }
102167
+ },
102168
+ refused: {
102169
+ brand_kit: "Set the Brand Kit with the root `brand` option.",
102170
+ name: "Set the workspace name with the root `name` option.",
102171
+ slug: "The workspace slug is set in the Control Panel."
102172
+ }
102173
+ };
102560
102174
 
102561
- return load;
102562
- })({
102563
- ${entries.join(",\n")}
102564
- }, typeof require === 'function' ? require : (specifier) => { throw new Error(\`Cannot import \${specifier}.\`); });
102565
- `;
102175
+ // scripts/lib/runtime-build/workspace-settings.mjs
102176
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
102177
+ var URL_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
102178
+ function readWorkspaceSettings(settings, node, pagesByUid) {
102179
+ if (settings === void 0) {
102180
+ return {};
102181
+ }
102182
+ if (!isPlainObject2(settings)) {
102183
+ throw new SourceError('"settings" must be an object', node);
102184
+ }
102185
+ for (const [key, value] of Object.entries(settings)) {
102186
+ const settingNode = propertyNode(node, key);
102187
+ const refused = workspace_settings_catalog_default.refused[key];
102188
+ if (refused !== void 0) {
102189
+ throw new SourceError(`"settings.${key}" is not allowed. ${refused}`, settingNode);
102190
+ }
102191
+ const setting = workspace_settings_catalog_default.settings[key];
102192
+ if (setting === void 0) {
102193
+ throw new SourceError(
102194
+ `Unknown workspace setting "${key}". Use one of: ${Object.keys(workspace_settings_catalog_default.settings).join(", ")}`,
102195
+ settingNode
102196
+ );
102197
+ }
102198
+ const problem2 = valueProblem(setting, value, pagesByUid);
102199
+ if (problem2 !== null) {
102200
+ throw new SourceError(`"settings.${key}" ${problem2}`, settingNode);
102201
+ }
102202
+ }
102203
+ return settings;
102566
102204
  }
102567
- function compileModule(path, source) {
102205
+ function valueProblem(setting, value, pagesByUid) {
102206
+ if (value === null) {
102207
+ return null;
102208
+ }
102209
+ if (setting.type === "page_reference") {
102210
+ return pageReferenceProblem(value, pagesByUid);
102211
+ }
102212
+ if (typeof value !== "string") {
102213
+ return "must be a string or null";
102214
+ }
102215
+ if (setting.values !== null && !setting.values.includes(value)) {
102216
+ const lower = value.toLowerCase();
102217
+ const hint = lower !== value && setting.values.includes(lower) ? ` Use "${lower}".` : "";
102218
+ return `must be one of the supported values, such as "${setting.default ?? setting.values[0]}".${hint}`;
102219
+ }
102220
+ if (setting.type === "timezone" && !isTimezone(value)) {
102221
+ return `must be an IANA timezone, such as "${setting.default}"`;
102222
+ }
102223
+ if (setting.max !== null && value.length > setting.max) {
102224
+ return `must be at most ${setting.max} characters`;
102225
+ }
102226
+ if (setting.pattern !== null && value.trim() !== "" && !new RegExp(setting.pattern).test(value.trim())) {
102227
+ return "has characters that the setting does not allow";
102228
+ }
102229
+ if (setting.url && !isUrl(value)) {
102230
+ return 'must be a URL, such as "https://example.com"';
102231
+ }
102232
+ return null;
102233
+ }
102234
+ function isUrl(value) {
102235
+ return URL_PATTERN.test(value) && URL.canParse(value);
102236
+ }
102237
+ function isTimezone(value) {
102568
102238
  try {
102569
- return (0, import_sucrase.transform)(source, {
102570
- transforms: path.endsWith("x") ? ["typescript", "jsx", "imports"] : ["typescript", "imports"],
102571
- jsxPragma: "React.createElement",
102572
- jsxFragmentPragma: "React.Fragment",
102573
- production: true,
102574
- filePath: path
102575
- }).code;
102239
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
102576
102240
  } catch (error) {
102577
- throw new SourceError(`${path} does not compile: ${error.message}`, null);
102241
+ if (error instanceof RangeError) {
102242
+ return false;
102243
+ }
102244
+ throw error;
102578
102245
  }
102246
+ return value.includes("/") || value === "UTC";
102579
102247
  }
102580
102248
 
102581
- // scripts/lib/runtime-build/script-sdk.mjs
102582
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
102583
- import { readFileSync as readFileSync9, readdirSync as readdirSync3, statSync as statSync4 } from "node:fs";
102584
- import { createRequire as createRequire3 } from "node:module";
102585
- import { dirname as dirname3, join as join11, relative as relative4, resolve as resolve4 } from "node:path";
102586
- import { fileURLToPath as fileURLToPath2 } from "node:url";
102587
- var SCRIPT_SDK_ROOT = resolve4(
102588
- dirname3(fileURLToPath2(import.meta.url)),
102589
- "../../../packages/workflows/src"
102590
- );
102591
- var SDK_RUNTIME_ENTRY_POINTS = {
102592
- workflow: join11(SCRIPT_SDK_ROOT, "index.ts"),
102593
- testing: join11(SCRIPT_SDK_ROOT, "testing/index.ts"),
102594
- "quickjs-testing": fileURLToPath2(new URL("./quickjs-testing.mjs", import.meta.url))
102595
- };
102596
- function walk(directory) {
102597
- return readdirSync3(directory).flatMap(
102598
- (name) => statSync4(join11(directory, name)).isDirectory() ? walk(join11(directory, name)) : [join11(directory, name)]
102599
- );
102600
- }
102601
- function readSandboxSdkFiles() {
102602
- return Object.fromEntries(
102603
- walk(SCRIPT_SDK_ROOT).filter(
102604
- (file2) => file2.endsWith(".ts") && !file2.includes("/testing/") && !file2.endsWith("/http-transport.ts") && !file2.endsWith("/workspace.generated.ts")
102605
- ).map((file2) => [`/sdk/${relative4(SCRIPT_SDK_ROOT, file2)}`, readFileSync9(file2, "utf8")])
102606
- );
102249
+ // scripts/lib/runtime-build/workspace-fields.mjs
102250
+ var WORKSPACE_FIELDS_DIRECTORY = "workspace-fields";
102251
+ var RESERVED_KEYS = /* @__PURE__ */ new Set([
102252
+ ...Object.keys(workspace_settings_catalog_default.settings),
102253
+ ...Object.keys(workspace_settings_catalog_default.refused),
102254
+ ...FIELD_CATALOG.record_meta_fields
102255
+ ]);
102256
+ var ENTRY_KEYS = /* @__PURE__ */ new Set(["uid", "key", "section", "definition", "value"]);
102257
+ var RESOURCE_ONLY_OPTIONS = ["uid", "unique", "index", "computed", "getter", "setter", "setterWhenEmpty"];
102258
+ var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
102259
+ var DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
102260
+ var TIME_PATTERN = /^\d{2}:\d{2}(?::\d{2})?$/;
102261
+ var STRING_TYPES = /* @__PURE__ */ new Set(["color", "liquid", "markdown", "password", "phone", "text"]);
102262
+ var UUID_TYPES = /* @__PURE__ */ new Set(["resource_reference", "uuid", "wallet_accounting_account", "wallet_accounting_entity"]);
102263
+ var OBJECT_TYPES2 = /* @__PURE__ */ new Set(["content", "dictionary", "event_schedule", "location", "money", "regular_hours"]);
102264
+ function readWorkspaceFields(root, paths, diagnostics, { write = false, recordBindingEntries = {} } = {}) {
102265
+ const read2 = [];
102266
+ const keysByPath = /* @__PURE__ */ new Map();
102267
+ for (const path of paths) {
102268
+ try {
102269
+ const source = readFileSync8(join11(root, path), "utf8");
102270
+ const ast = parseSource(source, { jsx: false });
102271
+ const argument = defineWorkspaceFieldArgument(ast);
102272
+ const declared = declaredSlug(argument, "key");
102273
+ keysByPath.set(path, declared.slug ?? basename8(path, ".ts"));
102274
+ const field2 = readWorkspaceField(path, argument, declared, diagnostics, recordBindingsBinding(ast, recordBindingEntries));
102275
+ read2.push({ field: field2, uidDefinition: { type: "workspace field", path, source, node: argument } });
102276
+ } catch (error) {
102277
+ diagnostics.push(diagnosticFromError(path, error));
102278
+ }
102279
+ }
102280
+ const uidCheck = checkDefinitionUids(root, read2.map((item) => item.uidDefinition), { write });
102281
+ diagnostics.push(...uidCheck.diagnostics);
102282
+ return {
102283
+ fields: read2.map(({ field: field2 }, position) => ({ ...field2, uid: uidCheck.uids[position] })),
102284
+ keysByPath
102285
+ };
102607
102286
  }
102608
- function bundleQuickJsSdkRuntime(buildSync) {
102609
- const result = buildSync({
102610
- entryPoints: [join11(SCRIPT_SDK_ROOT, "runtime/quickjs.ts")],
102611
- bundle: true,
102612
- write: false,
102613
- format: "esm",
102614
- target: "es2023",
102615
- platform: "neutral",
102616
- logLevel: "silent"
102617
- });
102618
- return result.outputFiles[0].text;
102287
+ function defineWorkspaceFieldArgument(ast) {
102288
+ const { declaration } = defaultExportOf(ast, { extraImports: [GENERATED_RECORD_BINDINGS_MODULE] });
102289
+ return expectDefineCall(declaration, "defineWorkspaceField", 1)[0];
102619
102290
  }
102620
- function bundleSdkRuntime(buildSync) {
102621
- const result = buildSync({
102622
- entryPoints: SDK_RUNTIME_ENTRY_POINTS,
102623
- outdir: "/sdk",
102624
- bundle: true,
102625
- splitting: true,
102626
- platform: "node",
102627
- target: "node24",
102628
- format: "esm",
102629
- define: { __SDK_RUNTIME__: JSON.stringify(bundleQuickJsSdkRuntime(buildSync)) },
102630
- write: false,
102631
- logLevel: "silent"
102632
- });
102633
- return Object.fromEntries(
102634
- result.outputFiles.map((file2) => [relative4("/sdk", file2.path), file2.text])
102635
- );
102291
+ function isWorkspaceFieldFileName(name) {
102292
+ return FIELD_KEY_PATTERN.test(name);
102636
102293
  }
102637
- var sdkFiles;
102638
- var surface = null;
102639
- try {
102640
- ({ SDK_FILES: sdkFiles, SDK_SURFACE: surface } = await Promise.resolve().then(() => (init_sdk_files_generated(), sdk_files_generated_exports)));
102641
- } catch (error) {
102642
- if (error?.code !== "ERR_MODULE_NOT_FOUND") {
102643
- throw error;
102294
+ function workspaceFieldKeyProblem(path, key, declared) {
102295
+ const fileName = basename8(path, ".ts");
102296
+ if (!isWorkspaceFieldFileName(fileName)) {
102297
+ const suggestion = fileName.toLowerCase().replaceAll("-", "_");
102298
+ const hint = isWorkspaceFieldFileName(suggestion) ? `. Rename the file to ${suggestion}.ts` : "";
102299
+ const role = declared ? "gives the WorkspaceFields name of the field" : "is the workspace field key";
102300
+ return `The file name "${fileName}" ${role}, so it must start with a lowercase letter and contain only a-z, 0-9, and _${hint}`;
102644
102301
  }
102645
- sdkFiles = readSandboxSdkFiles();
102646
- }
102647
- var SDK_SURFACE_MODULE = "../workflow-script/sdk-surface.mjs";
102648
- var { sdkSurface } = surface === null ? await import(SDK_SURFACE_MODULE) : {};
102649
- var SCRIPT_SDK_FILES = sdkFiles;
102650
- function scriptSdkSurface() {
102651
- surface ??= sdkSurface(SCRIPT_SDK_FILES);
102652
- return surface;
102653
- }
102654
- var sdkRuntimeFiles = null;
102655
- function scriptSdkRuntimeFiles() {
102656
- sdkRuntimeFiles ??= define_globalThis_DIAGONAL_SDK_RUNTIME_default ?? bundleSdkRuntime(createRequire3(import.meta.url)("esbuild").buildSync);
102657
- return sdkRuntimeFiles;
102302
+ if (declared && !FIELD_KEY_PATTERN.test(key)) {
102303
+ return '"key" must start with a lowercase letter and contain only a-z, 0-9, and _';
102304
+ }
102305
+ if (RESERVED_KEYS.has(key)) {
102306
+ return declared ? `"${key}" is the key of a field that the workspace already has. Give the custom field another key` : `The file name "${key}" is the key of a field that the workspace already has. Rename the file to give the custom field another key`;
102307
+ }
102308
+ return null;
102658
102309
  }
102659
-
102660
- // scripts/lib/runtime-build/workflow-tests.mjs
102661
- var WORKFLOW_TEST_STAGE = "workflow test";
102662
- var TEST_SUFFIX = ".test.ts";
102663
- var WORKFLOW_TEST_SUBJECT = {
102664
- noun: "workflow",
102665
- directory: "workflows",
102666
- sdk: "@diagonal/workflow",
102667
- stage: WORKFLOW_TEST_STAGE
102668
- };
102669
- var MIGRATION_TEST_SUBJECT = {
102670
- noun: "migration",
102671
- directory: "migrations",
102672
- sdk: "@diagonal/workflow",
102673
- stage: "migration test"
102674
- };
102675
- var TEST_TIMEOUT_MS = 1e4;
102676
- var RUN_TIMEOUT_MS = 6e4;
102677
- var RESULT_PREFIX = "\0diagonal-test ";
102678
- var SDK_MODULES = {
102679
- "@diagonal/workflow": "sdk/workflow.js",
102680
- "@diagonal/workflow/testing": "sdk/quickjs-testing.js",
102681
- "@diagonal/workflow/workspace": "sdk/workspace.js",
102682
- [AUTHORING_MODULE]: "sdk/runtime.js"
102683
- };
102684
- var NODE_TEST_MODULES = /* @__PURE__ */ new Set(["node:test", "node:assert", "node:assert/strict"]);
102685
- var TEST_MODULE_EXTERNALS = /* @__PURE__ */ new Set([...Object.keys(SDK_MODULES), ...NODE_TEST_MODULES]);
102686
- var RELATIVE_WORKFLOW = /^\.\/([^/]+?)(?:\.ts|\.js)?$/;
102687
- var REPORTER_SOURCE = `const PREFIX = ${JSON.stringify(RESULT_PREFIX)};
102688
- export default async function* reporter(source) {
102689
- const names = [];
102690
- for await (const event of source) {
102691
- const data = event.data;
102692
- if (event.type === 'test:start') {
102693
- names.length = data.nesting;
102694
- names.push(data.name);
102695
- continue;
102310
+ function readWorkspaceField(path, argument, declared, diagnostics, generatedEntries) {
102311
+ if (declared.problem !== null) {
102312
+ throw new SourceError(declared.problem, declared.node);
102313
+ }
102314
+ const key = declared.slug ?? basename8(path, ".ts");
102315
+ const keyProblem = workspaceFieldKeyProblem(path, key, declared.slug !== null);
102316
+ if (keyProblem !== null) {
102317
+ throw new SourceError(keyProblem, declared.node);
102318
+ }
102319
+ const { value: entry, nodes } = staticObject(argument, { fieldBuilders: true, generatedEntries });
102320
+ for (const option of Object.keys(entry)) {
102321
+ if (option === "slug") {
102322
+ throw new SourceError('Remove "slug". A workspace field sets its key with "key"', nodes.slug);
102696
102323
  }
102697
- if (event.type !== 'test:pass' && event.type !== 'test:fail') {
102698
- continue;
102324
+ if (!ENTRY_KEYS.has(option)) {
102325
+ throw new SourceError(`Unknown option "${option}". Use "uid", "key", "section", "definition", and "value"`, nodes[option]);
102699
102326
  }
102700
- const error = data.details?.error;
102701
- if (data.details?.type === 'suite' && (event.type === 'test:pass' || error?.failureType === 'subtestsFailed')) {
102702
- continue;
102327
+ }
102328
+ if (entry.section !== void 0 && (typeof entry.section !== "string" || entry.section.length > 255)) {
102329
+ throw new SourceError('"section" must be a string with at most 255 characters', nodes.section);
102330
+ }
102331
+ const builder = entry.definition;
102332
+ const { field: field2, metadata } = readWorkspaceFieldDefinition(key, builder, nodes.definition ?? argument);
102333
+ if (!Object.hasOwn(entry, "value")) {
102334
+ throw new SourceError('Add "value". Write null for a field without a value', argument);
102335
+ }
102336
+ const problem2 = valueProblem2(field2, entry.value);
102337
+ if (problem2 !== null) {
102338
+ throw new SourceError(`"value" ${problem2}`, nodes.value);
102339
+ }
102340
+ if (builder.options.default !== void 0) {
102341
+ diagnostics.push(
102342
+ diagnosticAt(
102343
+ path,
102344
+ optionNode(builder, "default"),
102345
+ '"default" is not used. A workspace field takes its value from "value"',
102346
+ { severity: "warning" }
102347
+ )
102348
+ );
102349
+ }
102350
+ return {
102351
+ path,
102352
+ key,
102353
+ ...metadata,
102354
+ section: entry.section ?? null,
102355
+ value: entry.value,
102356
+ nodes: { definition: builder.node, value: nodes.value }
102357
+ };
102358
+ }
102359
+ function readWorkspaceFieldDefinition(key, builder, node) {
102360
+ if (!(builder instanceof FieldBuilderValue)) {
102361
+ throw new SourceError('"definition" must be a field.<type>({...}) call', node);
102362
+ }
102363
+ checkBuilderOptions(builder);
102364
+ const field2 = buildField(key, builder, node, { checkKey: false });
102365
+ if (field2.type === "relation") {
102366
+ throw new SourceError("A workspace field cannot be a relation. A workspace field has no record", builder.node);
102367
+ }
102368
+ return {
102369
+ field: field2,
102370
+ metadata: {
102371
+ type: field2.type,
102372
+ label: field2.label,
102373
+ description: field2.description,
102374
+ guard: [field2.required ? "required" : "nullable", ...field2.guard],
102375
+ settings: field2.settings
102703
102376
  }
102704
- const path = [...names.slice(0, data.nesting), data.name].join(' > ');
102705
- const cause = error?.cause ?? error;
102706
- yield PREFIX + JSON.stringify({
102707
- file: data.file ?? null,
102708
- name: path,
102709
- leaf: data.name,
102710
- ok: event.type === 'test:pass',
102711
- message: event.type === 'test:pass' ? null : String(cause?.message ?? cause ?? 'The test failed').trim()
102712
- }) + '\\n';
102377
+ };
102378
+ }
102379
+ function checkBuilderOptions(builder) {
102380
+ const option = RESOURCE_ONLY_OPTIONS.find((item) => builder.options[item] !== void 0);
102381
+ if (option !== void 0) {
102382
+ throw new SourceError(
102383
+ `A workspace field cannot use "${option}". It is an option of a resource field`,
102384
+ optionNode(builder, option)
102385
+ );
102386
+ }
102387
+ }
102388
+ function valueProblem2(field2, value) {
102389
+ if (value === null) {
102390
+ return field2.required ? "is required, so it cannot be null" : null;
102391
+ }
102392
+ const { type, settings } = field2;
102393
+ if (STRING_TYPES.has(type)) {
102394
+ return typeof value === "string" ? null : "must be a string";
102395
+ }
102396
+ if (UUID_TYPES.has(type)) {
102397
+ return typeof value === "string" && UID_PATTERN.test(value.toLowerCase()) || value?.$type === "record.binding" ? null : "must be a UUID or a record binding reference";
102398
+ }
102399
+ if (OBJECT_TYPES2.has(type)) {
102400
+ return objectProblem(type, value);
102401
+ }
102402
+ switch (type) {
102403
+ case "boolean":
102404
+ return typeof value === "boolean" ? null : "must be true or false";
102405
+ case "number":
102406
+ return numberProblem(value, settings);
102407
+ case "email":
102408
+ return typeof value === "string" && EMAIL_PATTERN.test(value) ? null : 'must be an email address, such as "help@example.com"';
102409
+ case "url":
102410
+ return typeof value === "string" && isUrl(value) ? null : 'must be a URL, such as "https://example.com"';
102411
+ case "date":
102412
+ return typeof value === "string" && DATE_PATTERN.test(value) && !Number.isNaN(Date.parse(value)) ? null : 'must be a date, such as "2026-01-31"';
102413
+ case "datetime":
102414
+ return typeof value === "string" && !Number.isNaN(Date.parse(value)) ? null : 'must be a date and time, such as "2026-01-31T09:00:00Z"';
102415
+ case "time":
102416
+ return typeof value === "string" && TIME_PATTERN.test(value) ? null : 'must be a time, such as "09:30"';
102417
+ case "timezone":
102418
+ return typeof value === "string" && isTimezone(value) ? null : 'must be an IANA timezone, such as "America/Chicago"';
102419
+ case "select":
102420
+ return selectProblem(value, settings.options);
102421
+ case "list":
102422
+ return Array.isArray(value) ? null : "must be a list";
102423
+ default:
102424
+ return null;
102713
102425
  }
102714
102426
  }
102715
- `;
102716
- function moduleSpecifierNodes(ast) {
102717
- return ast.program.body.filter(
102718
- (statement2) => (statement2.type === "ImportDeclaration" || statement2.type === "ExportNamedDeclaration" || statement2.type === "ExportAllDeclaration") && statement2.source
102719
- ).map((statement2) => statement2.source);
102720
- }
102721
- function rewriteSpecifiers(source, ast, resolveSpecifier) {
102722
- let rewritten = source;
102723
- for (const node of moduleSpecifierNodes(ast).toSorted(
102724
- (left, right) => right.start - left.start
102725
- )) {
102726
- const target = resolveSpecifier(node.value);
102727
- if (target !== null) {
102728
- rewritten = `${rewritten.slice(0, node.start)}${JSON.stringify(target)}${rewritten.slice(node.end)}`;
102729
- }
102427
+ function numberProblem(value, settings) {
102428
+ if (typeof value !== "number" || !Number.isFinite(value)) {
102429
+ return "must be a number";
102730
102430
  }
102731
- return rewritten;
102431
+ if (settings.integer === true && !Number.isInteger(value)) {
102432
+ return "must be a whole number";
102433
+ }
102434
+ if (typeof settings.minimum === "number" && value < settings.minimum) {
102435
+ return `must be at least ${settings.minimum}`;
102436
+ }
102437
+ if (typeof settings.maximum === "number" && value > settings.maximum) {
102438
+ return `must be at most ${settings.maximum}`;
102439
+ }
102440
+ return null;
102732
102441
  }
102733
- function sdkSpecifier(fromDirectory) {
102734
- return (specifier) => Object.hasOwn(SDK_MODULES, specifier) ? `${fromDirectory}${SDK_MODULES[specifier]}` : null;
102442
+ function selectProblem(value, options) {
102443
+ const values = options.map((option) => option.value);
102444
+ return values.includes(value) ? null : `must be one of the option values: ${values.map((item) => JSON.stringify(item)).join(", ")}`;
102735
102445
  }
102736
- function testCallNode(ast, name) {
102737
- const pending = [ast.program];
102738
- while (pending.length > 0) {
102739
- const node = pending.pop();
102740
- const [first] = node.type === "CallExpression" ? node.arguments : [];
102741
- 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) {
102742
- return node;
102743
- }
102744
- pending.push(...childNodes(node));
102446
+ function objectProblem(type, value) {
102447
+ if (!isPlainObject2(value)) {
102448
+ return "must be an object";
102449
+ }
102450
+ if (type === "money" && (typeof value.amount !== "number" || typeof value.currency !== "string")) {
102451
+ return 'must be { amount: <number>, currency: "<code>" }';
102745
102452
  }
102746
102453
  return null;
102747
102454
  }
102748
- function importDiagnostics(test, scriptNames, workspaceRoot, subject) {
102749
- const diagnostics = [];
102750
- for (const node of moduleSpecifierNodes(test.ast)) {
102751
- const specifier = node.value;
102752
- const relative6 = RELATIVE_WORKFLOW.exec(specifier);
102753
- if (NODE_TEST_MODULES.has(specifier) || Object.hasOwn(SDK_MODULES, specifier) || relative6 !== null && scriptNames.has(relative6[1]) || isAppSpecifier(specifier) && workspaceRoot !== null && resolveAppSpecifier(workspaceRoot, specifier) !== null) {
102455
+
102456
+ // scripts/lib/runtime-build/workspace-field-references.mjs
102457
+ var GENERATED_WORKSPACE_FIELDS_PATH = "generated/workspace-fields.ts";
102458
+ var WORKSPACE_FIELDS_EXPORT = "WorkspaceFields";
102459
+ function workspaceFieldNames(paths, keysByPath, diagnostics) {
102460
+ const keysByName = /* @__PURE__ */ new Map();
102461
+ const pathsByName = /* @__PURE__ */ new Map();
102462
+ const pathsByKey = /* @__PURE__ */ new Map();
102463
+ for (const path of paths.toSorted(byteOrder2)) {
102464
+ const fileName = basename9(path, ".ts");
102465
+ if (!isWorkspaceFieldFileName(fileName)) {
102754
102466
  continue;
102755
102467
  }
102756
- diagnostics.push(
102757
- diagnosticAt(
102758
- test.path,
102759
- node,
102760
- `A ${subject.noun} test can import only node:test, node:assert, ${subject.sdk}, @diagonal/workflow/testing, @diagonal/workflow/workspace, the ${subject.noun}s in ${subject.directory}/, and workspace files by @app/. "${specifier}" is not one of them`,
102761
- { stage: subject.stage }
102762
- )
102763
- );
102764
- }
102765
- return diagnostics;
102766
- }
102767
- function compiledScriptModule(script) {
102768
- const prefix2 = sandboxPrefix(script.path);
102769
- const source = JSON.stringify(`./${basename9(script.path, ".ts")}.mjs`);
102770
- return [
102771
- `import * as script from ${source};`,
102772
- `import { registerCompiledScript } from ${JSON.stringify(`${prefix2}sdk/quickjs-testing.js`)};`,
102773
- `export * from ${source};`,
102774
- "export default script.default;",
102775
- `registerCompiledScript(script.default, ${JSON.stringify(script.compiled)}, script.validateInput);`,
102776
- ""
102777
- ].join("\n");
102778
- }
102779
- function sandboxPath(path) {
102780
- return path.replace(/\.(ts|tsx|js|jsx)$/, ".js");
102781
- }
102782
- function sandboxPrefix(path) {
102783
- return "../".repeat(path.split("/").length - 1) || "./";
102784
- }
102785
- function relativeSandboxPath(from, target) {
102786
- const path = relative5(dirname4(from), sandboxPath(target));
102787
- return path.startsWith(".") ? path : `./${path}`;
102788
- }
102789
- function writeFile(root, path, content) {
102790
- mkdirSync2(dirname4(join12(root, path)), { recursive: true });
102791
- writeFileSync4(join12(root, path), content);
102792
- }
102793
- function parseResults(stdout) {
102794
- return stdout.split("\n").filter((line) => line.startsWith(RESULT_PREFIX)).map((line) => JSON.parse(line.slice(RESULT_PREFIX.length)));
102795
- }
102796
- function testsNotReaching(tests, skippedScripts, root, modulePath) {
102797
- return tests.filter((test) => {
102798
- if (skippedScripts.has(`${test.path.slice(0, -TEST_SUFFIX.length)}.ts`)) {
102799
- return false;
102800
- }
102801
- if (root === null) {
102802
- return true;
102803
- }
102804
- try {
102805
- return !appModuleClosure(
102806
- root,
102807
- appImportsOf(root, test.path, test.ast),
102808
- TEST_MODULE_EXTERNALS
102809
- ).has(modulePath);
102810
- } catch (error) {
102811
- if (error instanceof SourceError) {
102812
- return true;
102813
- }
102814
- throw error;
102815
- }
102816
- });
102817
- }
102818
- function runScriptTests({
102819
- tests,
102820
- scripts,
102821
- root: workspaceRoot = null,
102822
- appModules = /* @__PURE__ */ new Map(),
102823
- subject = WORKFLOW_TEST_SUBJECT
102824
- }) {
102825
- const diagnostics = [];
102826
- const prefix2 = `${subject.directory}/`;
102827
- const scriptNames = new Map(
102828
- scripts.map((script) => [script.path.slice(prefix2.length, -".ts".length), script])
102829
- );
102830
- const runnable = [];
102831
- for (const test of tests) {
102832
- const scriptPath = `${test.path.slice(0, -TEST_SUFFIX.length)}.ts`;
102833
- if (!scriptNames.has(scriptPath.slice(prefix2.length, -".ts".length))) {
102468
+ const key = keysByPath.get(path) ?? fileName;
102469
+ const name = studlyName(fileName);
102470
+ const otherName = pathsByName.get(name);
102471
+ const otherKey = pathsByKey.get(key);
102472
+ if (otherName !== void 0 || otherKey !== void 0) {
102834
102473
  diagnostics.push(
102835
102474
  diagnosticAt(
102836
- test.path,
102475
+ path,
102837
102476
  null,
102838
- `The test file has no ${subject.noun}. Add ${scriptPath} or remove the test file`,
102839
- { stage: subject.stage }
102477
+ otherName !== void 0 ? `The workspace field files ${otherName} and ${path} both have the name ${WORKSPACE_FIELDS_EXPORT}.${name}. Rename one of the files` : `The workspace field files ${otherKey} and ${path} have the same key "${key}". Change the key of one of them`,
102478
+ { relatedPath: otherName ?? otherKey }
102840
102479
  )
102841
102480
  );
102842
102481
  continue;
102843
102482
  }
102844
- const imports = importDiagnostics(test, scriptNames, workspaceRoot, subject);
102845
- diagnostics.push(...imports);
102846
- if (imports.length === 0) {
102847
- runnable.push({ ...test, script: scriptPath });
102848
- }
102849
- }
102850
- if (runnable.length === 0) {
102851
- return { testResults: [], diagnostics };
102852
- }
102853
- const modules = new Map(appModules);
102854
- for (const test of runnable) {
102855
- for (const [path, module] of appModuleClosure(
102856
- workspaceRoot,
102857
- workspaceRoot === null ? [] : appImportsOf(workspaceRoot, test.path, test.ast),
102858
- TEST_MODULE_EXTERNALS
102859
- )) {
102860
- modules.set(path, module);
102861
- }
102862
- }
102863
- const files = [];
102864
- for (const [path, module] of modules) {
102865
- const resolveSdk = sdkSpecifier(sandboxPrefix(path));
102866
- files.push({
102867
- path,
102868
- target: sandboxPath(path),
102869
- source: rewriteSpecifiers(
102870
- module.source,
102871
- parseSource(module.source, { jsx: path.endsWith("x") }),
102872
- (specifier) => module.requires[specifier] === void 0 ? resolveSdk(specifier) : relativeSandboxPath(path, module.requires[specifier])
102873
- )
102874
- });
102875
- }
102876
- for (const script of scripts) {
102877
- files.push({
102878
- path: script.path,
102879
- target: script.path.replace(/\.ts$/, script.compiled ? ".mjs" : ".js"),
102880
- source: rewriteSpecifiers(script.source, script.ast, (specifier) => {
102881
- const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
102882
- return target === null ? sdkSpecifier("../")(specifier) : relativeSandboxPath(script.path, target);
102883
- })
102884
- });
102483
+ keysByName.set(name, key);
102484
+ pathsByName.set(name, path);
102485
+ pathsByKey.set(key, path);
102885
102486
  }
102886
- for (const test of runnable) {
102887
- const resolveSdk = sdkSpecifier("../");
102888
- files.push({
102889
- path: test.path,
102890
- target: test.path.replace(/\.ts$/, ".js"),
102891
- source: rewriteSpecifiers(test.source, test.ast, (specifier) => {
102892
- const relative6 = RELATIVE_WORKFLOW.exec(specifier);
102893
- const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
102894
- if (target !== null) {
102895
- return relativeSandboxPath(test.path, target);
102896
- }
102897
- return relative6 !== null ? `./${relative6[1]}.js` : resolveSdk(specifier);
102898
- })
102899
- });
102487
+ return keysByName;
102488
+ }
102489
+ function workspaceFieldEntries(keysByName, fields) {
102490
+ const fieldsByKey = new Map(fields.map((field2) => [field2.key, field2]));
102491
+ const entries = /* @__PURE__ */ Object.create(null);
102492
+ for (const name of [...keysByName.keys()].toSorted(byteOrder2)) {
102493
+ const key = keysByName.get(name);
102494
+ const field2 = fieldsByKey.get(key);
102495
+ entries[name] = field2 === void 0 ? { key } : { uid: field2.uid ?? null, ...fieldMetadata({ ...field2, required: field2.guard[0] === "required" }) };
102900
102496
  }
102901
- const stripped = stripTypes(files.map(({ path, source }) => ({ path, source })));
102902
- const stripErrors = files.flatMap((file2, index3) => {
102903
- const result = stripped[index3];
102904
- return result.ok ? [] : [
102905
- diagnostic(
102906
- file2.path,
102907
- result.line,
102908
- result.column,
102909
- `The ${subject.noun} tests did not run, because this file does not compile: ${result.message}`,
102910
- { stage: subject.stage }
102911
- )
102912
- ];
102497
+ return entries;
102498
+ }
102499
+ function generatedWorkspaceFieldsSource(entries, fields = [], { workflowPackageDeclared = false } = {}) {
102500
+ const keys2 = new Set(Object.values(entries).map((field2) => field2.key));
102501
+ const declared = fields.filter((field2) => keys2.has(field2.key));
102502
+ return generatedWorkflowTypesSource(WORKSPACE_FIELDS_EXPORT, entries, "", {
102503
+ augment: (module) => workspaceFieldAugmentation(declared, module),
102504
+ workflowPackageDeclared
102913
102505
  });
102914
- if (stripErrors.length > 0) {
102915
- return { testResults: [], diagnostics: [...diagnostics, ...stripErrors] };
102916
- }
102917
- const root = realpathSync2(mkdtempSync2(join12(tmpdir2(), "diagonal-workflow-tests-")));
102918
- try {
102919
- writeFile(root, "package.json", '{"type":"module"}\n');
102920
- writeFile(root, "reporter.mjs", REPORTER_SOURCE);
102921
- for (const [path, content] of Object.entries(scriptSdkRuntimeFiles())) {
102922
- writeFile(root, `sdk/${path}`, content);
102923
- }
102924
- writeFile(root, "sdk/workspace.js", "export {};\n");
102925
- writeFile(root, "sdk/runtime.js", AUTHORING_HELPERS_MODULE);
102926
- for (const [index3, file2] of files.entries()) {
102927
- writeFile(root, file2.target, stripped[index3].code);
102928
- }
102929
- for (const script of scripts) {
102930
- if (script.compiled) {
102931
- writeFile(root, script.path.replace(/\.ts$/, ".js"), compiledScriptModule(script));
102932
- }
102933
- }
102934
- const run = spawnSync2(
102935
- process.execPath,
102936
- [
102937
- "--permission",
102938
- `--allow-fs-read=${root}`,
102939
- "--test",
102940
- "--test-isolation=none",
102941
- `--test-timeout=${TEST_TIMEOUT_MS}`,
102942
- "--test-reporter=./reporter.mjs",
102943
- ...runnable.map((test) => test.path.replace(/\.ts$/, ".js"))
102944
- ],
102945
- {
102946
- cwd: root,
102947
- env: { TZ: "UTC" },
102948
- encoding: "utf8",
102949
- timeout: RUN_TIMEOUT_MS,
102950
- maxBuffer: 16 * 1024 * 1024
102951
- }
102952
- );
102953
- if (run.error !== void 0 && run.error.code !== "ETIMEDOUT") {
102954
- throw run.error;
102955
- }
102956
- const results = parseResults(run.stdout ?? "");
102957
- const timedOut = run.error?.code === "ETIMEDOUT" || run.signal !== null;
102958
- const testResults = runnable.map((test) => {
102959
- const file2 = join12(root, test.path.replace(/\.ts$/, ".js"));
102960
- const own = results.filter((result) => result.file === file2);
102961
- for (const result of own) {
102962
- if (!result.ok) {
102963
- const node = testCallNode(test.ast, result.leaf);
102964
- diagnostics.push(
102965
- diagnosticAt(test.path, node, `Test "${result.name}" failed: ${result.message}`, {
102966
- stage: subject.stage
102967
- })
102968
- );
102969
- }
102970
- }
102971
- if (timedOut) {
102972
- diagnostics.push(
102973
- diagnostic(
102974
- test.path,
102975
- 1,
102976
- 1,
102977
- `The ${subject.noun} tests did not finish in ${RUN_TIMEOUT_MS / 1e3} seconds`,
102978
- { stage: subject.stage }
102979
- )
102980
- );
102981
- } else if (own.length === 0 && run.status !== 0) {
102982
- diagnostics.push(
102983
- diagnostic(
102984
- test.path,
102985
- 1,
102986
- 1,
102987
- `The ${subject.noun} tests did not run: ${(run.stderr ?? "").trim().split("\n")[0] || `exit code ${run.status}`}`,
102988
- { stage: subject.stage }
102989
- )
102990
- );
102991
- }
102992
- return {
102993
- path: test.path,
102994
- [subject.noun]: test.script,
102995
- passed: own.filter((result) => result.ok).length,
102996
- failed: own.filter((result) => !result.ok).length,
102997
- results: own.map((result) => ({
102998
- name: result.name,
102999
- ok: result.ok,
103000
- message: result.message
103001
- }))
103002
- };
103003
- });
103004
- return { testResults, diagnostics };
103005
- } finally {
103006
- rmSync2(root, { recursive: true, force: true });
103007
- }
103008
102506
  }
103009
-
103010
- // scripts/lib/runtime-build/workflows.mjs
103011
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
103012
- import { basename as basename10 } from "node:path";
103013
-
103014
- // scripts/lib/workflow-script/quickjs-runner.mjs
103015
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
103016
- var DEFAULT_LIMITS = {
103017
- memory_bytes: 128 * 1024 * 1024,
103018
- // Node's own WebAssembly stack overflows above roughly 512 KiB, which
103019
- // aborts the interpreter instead of raising a catchable stack overflow.
103020
- stack_bytes: 256 * 1024,
103021
- cpu_ms: 5e3,
103022
- max_calls: 5e4,
103023
- max_log_bytes: 128 * 1024,
103024
- max_result_bytes: 3 * 1024 * 1024,
103025
- // The largest call message the host reads. PHP sets it to its own line limit.
103026
- max_call_bytes: 32 * 1024 * 1024
103027
- };
103028
- function moduleMapText({ entry, imports, modules }) {
103029
- return JSON.stringify({ entry, imports, modules });
102507
+ function workspaceFieldValues(entries) {
102508
+ return {
102509
+ entries,
102510
+ exportName: WORKSPACE_FIELDS_EXPORT,
102511
+ noun: "workspace field",
102512
+ directory: "workspace-fields/",
102513
+ exampleMember: "key"
102514
+ };
103030
102515
  }
103031
102516
 
103032
102517
  // scripts/lib/runtime-build/workflow-entity-references.mjs
103033
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
103034
102518
  var ENTITIES = {
103035
102519
  [RESOURCES_EXPORT]: (exportName, [name, part, key], entry) => {
103036
102520
  const resource = { type: "resource", path: `${exportName}.${name}`, key: entry.slug };
@@ -103505,6 +102989,207 @@ function buildMigrations({ migrations, ...input }) {
103505
102989
  };
103506
102990
  }
103507
102991
 
102992
+ // scripts/lib/runtime-build/module-graph.mjs
102993
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
102994
+ import { readFileSync as readFileSync9 } from "node:fs";
102995
+ import { posix as posix2, join as join12 } from "node:path";
102996
+
102997
+ // scripts/lib/runtime-build/page-build-protocol.mjs
102998
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
102999
+ import { createHash } from "node:crypto";
103000
+ var PROFILE = Object.freeze({ target: "runtime-esm", version: 1 });
103001
+ var MAX_SOURCE_BYTES = 50 * 1024 * 1024;
103002
+ function sha256(value) {
103003
+ return createHash("sha256").update(value).digest("hex");
103004
+ }
103005
+
103006
+ // scripts/lib/runtime-build/module-graph.mjs
103007
+ var STYLE_KINDS = /* @__PURE__ */ new Set(["style", "style_module"]);
103008
+ var GENERATED_IMPORT_KINDS = /* @__PURE__ */ new Map([
103009
+ [GENERATED_ASSETS_PATH, "assets"],
103010
+ [GENERATED_PAGES_PATH, "pages"],
103011
+ [GENERATED_PERMISSIONS_PATH, "permissions"],
103012
+ [GENERATED_ROLES_PATH, "roles"],
103013
+ [GENERATED_RESOURCES_PATH, "resources"],
103014
+ [GENERATED_WORKFLOWS_PATH, "workflows"],
103015
+ [GENERATED_SKILLS_PATH, "skills"],
103016
+ [GENERATED_NOTIFICATION_TYPES_PATH, "notification_types"],
103017
+ [GENERATED_EMAIL_LAYOUTS_PATH, "email_layouts"],
103018
+ [GENERATED_WORKSPACE_FIELDS_PATH, "workspace_fields"],
103019
+ [GENERATED_RECORD_BINDINGS_PATH, "record_bindings"],
103020
+ [GENERATED_DOMAINS_PATH, "domains"]
103021
+ ]);
103022
+ function isGeneratedImport(item) {
103023
+ return [...GENERATED_IMPORT_KINDS.values()].includes(item.kind);
103024
+ }
103025
+ function declaredPackages(manifest) {
103026
+ return /* @__PURE__ */ new Set([...Object.keys(manifest?.dependencies ?? {}), ...Object.keys(manifest?.peerDependencies ?? {})]);
103027
+ }
103028
+ function checkModules(root, { entries, packages, assetKeys }) {
103029
+ const request2 = {
103030
+ entries,
103031
+ packages: [...packages],
103032
+ assetKeys: assetKeys === null ? null : [...assetKeys],
103033
+ generatedModules: Object.fromEntries(GENERATED_IMPORT_KINDS),
103034
+ rules: {
103035
+ ...IMPORT_RULES,
103036
+ rowMenuMembers: [...ROW_MENU_MEMBERS],
103037
+ navigationMenuRemoved: NAVIGATION_MENU_REMOVED
103038
+ }
103039
+ };
103040
+ return { root, request: request2, answers: runModuleCheck(root, request2) };
103041
+ }
103042
+ function runModuleCheck(root, request2) {
103043
+ return request2.entries.length === 0 ? { modules: {}, stylesheets: {} } : checkWorkspace({ root, modules: request2 }).modules;
103044
+ }
103045
+ function codeModuleAnswer(check2, path) {
103046
+ const answer = check2.answers.modules[path];
103047
+ if (answer === void 0 || answer.kind !== "module") {
103048
+ throw new Error(`The module check has no answer for ${path}.`);
103049
+ }
103050
+ if (!answer.parsed) {
103051
+ throw new Error(
103052
+ `The import check cannot parse ${path}, although the build parses it, so the build stops without checking its imports. Rewrite the syntax of ${path} that the oxc parser refuses, and report the file to the Diagonal platform team.`
103053
+ );
103054
+ }
103055
+ return answer;
103056
+ }
103057
+ function unitBuildBlocked(check2, path) {
103058
+ return codeModuleAnswer(check2, path).blocksUnitBuild;
103059
+ }
103060
+ function buildModuleGraph(check2, entries, diagnostics, generated = /* @__PURE__ */ new Map()) {
103061
+ const parsed = new Map(entries.map((entry) => [entry.path, entry]));
103062
+ for (let attempt = 0; attempt < 3; attempt += 1) {
103063
+ const walk2 = walkModuleGraph(check2, entries, parsed, generated);
103064
+ if (walk2.changed.size === 0) {
103065
+ diagnostics.push(...walk2.diagnostics);
103066
+ return { modules: walk2.modules, packages: walk2.packages, parsed };
103067
+ }
103068
+ check2.request = { ...check2.request, sources: { ...check2.request.sources, ...Object.fromEntries(walk2.changed) } };
103069
+ check2.answers = runModuleCheck(check2.root, check2.request);
103070
+ }
103071
+ throw new Error("The module check did not settle: a module kept changing during the build.");
103072
+ }
103073
+ function walkModuleGraph(check2, entries, parsed, generated) {
103074
+ const { root, answers } = check2;
103075
+ const diagnostics = [];
103076
+ const scannedStyles = /* @__PURE__ */ new Set();
103077
+ const modules = {};
103078
+ const failed = /* @__PURE__ */ new Set();
103079
+ const changed = /* @__PURE__ */ new Map();
103080
+ const pending = entries.map((entry) => entry.path);
103081
+ const usedPackages = /* @__PURE__ */ new Set();
103082
+ const workflows = generated.get(GENERATED_WORKFLOWS_PATH) ?? null;
103083
+ while (pending.length > 0) {
103084
+ const path = pending.shift();
103085
+ if (Object.hasOwn(modules, path)) {
103086
+ continue;
103087
+ }
103088
+ const kind = importKind(`./${posix2.basename(path)}`);
103089
+ if (STYLE_KINDS.has(kind)) {
103090
+ reportStylesheet(root, path, answers.stylesheets, diagnostics, scannedStyles);
103091
+ modules[path] = { kind, source_sha256: answerOfReadableFile(root, path, answers.modules).sha256, imports: [] };
103092
+ continue;
103093
+ }
103094
+ let entry = parsed.get(path);
103095
+ if (entry === void 0) {
103096
+ const source = readFileSync9(join12(root, path), "utf8");
103097
+ try {
103098
+ entry = { path, source, ast: parseSource(source, { jsx: path.endsWith("x") }) };
103099
+ } catch (error) {
103100
+ diagnostics.push(diagnosticAt(path, null, `The module does not parse: ${error.message}`));
103101
+ modules[path] = { kind: "module", source_sha256: sha256(source), imports: [] };
103102
+ failed.add(path);
103103
+ continue;
103104
+ }
103105
+ parsed.set(path, entry);
103106
+ }
103107
+ const answer = codeModuleAnswer(check2, path);
103108
+ const sourceSha256 = sha256(entry.source);
103109
+ if (answer.sha256 !== sourceSha256) {
103110
+ changed.set(path, entry.source);
103111
+ }
103112
+ diagnostics.push(...answer.diagnostics);
103113
+ if (workflows !== null) {
103114
+ diagnostics.push(...pageWorkflowReferenceDiagnostics(path, entry.ast, workflows.entries));
103115
+ }
103116
+ for (const item of answer.imports) {
103117
+ if (item.kind === "package") {
103118
+ usedPackages.add(item.specifier);
103119
+ } else if (item.kind !== "host" && !isGeneratedImport(item)) {
103120
+ pending.push(item.target);
103121
+ }
103122
+ }
103123
+ if (answer.imports.some(isGeneratedImport)) {
103124
+ checkGeneratedReferences(root, entry, generated, diagnostics);
103125
+ }
103126
+ modules[path] = { kind: "module", source_sha256: sourceSha256, imports: answer.imports };
103127
+ }
103128
+ for (const [path, module] of Object.entries(modules)) {
103129
+ if (module.kind !== "module" || failed.has(path)) {
103130
+ continue;
103131
+ }
103132
+ for (const { diagnostic: diagnostic2, requires } of answers.modules[path].linkage) {
103133
+ if (!requires.some((required) => failed.has(required))) {
103134
+ diagnostics.push(diagnostic2);
103135
+ }
103136
+ }
103137
+ }
103138
+ return { diagnostics, modules, packages: [...usedPackages].toSorted(), changed };
103139
+ }
103140
+ function answerOfReadableFile(root, path, answers) {
103141
+ const answer = answers[path];
103142
+ if (answer === void 0) {
103143
+ readFileSync9(join12(root, path));
103144
+ throw new Error(`The module check has no answer for ${path}.`);
103145
+ }
103146
+ return answer;
103147
+ }
103148
+ function reportStylesheet(root, path, stylesheets, diagnostics, scanned) {
103149
+ if (scanned.has(path)) {
103150
+ return;
103151
+ }
103152
+ scanned.add(path);
103153
+ for (const step of answerOfReadableFile(root, path, stylesheets).steps) {
103154
+ if (step.stylesheet === void 0) {
103155
+ diagnostics.push(step.diagnostic);
103156
+ } else {
103157
+ reportStylesheet(root, step.stylesheet, stylesheets, diagnostics, scanned);
103158
+ }
103159
+ }
103160
+ }
103161
+ function checkGeneratedReferences(root, entry, generated, diagnostics) {
103162
+ const generatedModuleOf = (specifier) => generated.get(resolveLocalSpecifier(root, entry.path, specifier)) ?? null;
103163
+ const { problems, otherUses } = inlineGeneratedValues(entry.source, entry.ast, generatedModuleOf);
103164
+ for (const problem2 of problems) {
103165
+ diagnostics.push(diagnosticAt(entry.path, problem2.node, problem2.message));
103166
+ }
103167
+ for (const { node, exportName, exampleMember } of otherUses) {
103168
+ diagnostics.push(
103169
+ diagnosticAt(
103170
+ entry.path,
103171
+ node,
103172
+ `Read a value such as ${exportName}.<Name>.${exampleMember}. The build replaces each reference with its value, so a page cannot use ${exportName} as a whole`
103173
+ )
103174
+ );
103175
+ }
103176
+ for (const found2 of moduleSpecifiers(entry.ast)) {
103177
+ const values = found2.specifier === null || found2.typeOnly ? null : generatedModuleOf(found2.specifier);
103178
+ if (values === null) {
103179
+ continue;
103180
+ }
103181
+ if (found2.dynamic) {
103182
+ diagnostics.push(diagnosticAt(entry.path, found2.node, `Import ${values.exportName} with a static import`));
103183
+ } else if (found2.statement?.type !== "ImportDeclaration") {
103184
+ diagnostics.push(
103185
+ diagnosticAt(entry.path, found2.node, `A page module cannot re-export ${values.exportName}. Import it where you read it`)
103186
+ );
103187
+ }
103188
+ }
103189
+ }
103190
+ var ROW_MENU_MEMBERS = /* @__PURE__ */ new Set(["navigationMenu", "navigationMenuIds"]);
103191
+ var NAVIGATION_MENU_REMOVED = "navigationMenu is not available in file-based workspaces. Import the menu module and pass it to useMenu";
103192
+
103508
103193
  // scripts/lib/runtime-build/navigation-menu-file.mjs
103509
103194
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
103510
103195
 
@@ -111471,6 +111156,7 @@ function buildMaterializedWorkspace(root, plan, { assetCatalog = null, writeSour
111471
111156
  const packages = declaredPackages(packageFiles.manifest).union(plan.dependencies);
111472
111157
  const uiEntries = [];
111473
111158
  const failedPages = /* @__PURE__ */ new Set();
111159
+ let moduleCheck = null;
111474
111160
  let pageAssets = null;
111475
111161
  const buildFile = (path) => {
111476
111162
  const kind = classify(path);
@@ -111521,7 +111207,7 @@ function buildMaterializedWorkspace(root, plan, { assetCatalog = null, writeSour
111521
111207
  if (kind === "page") {
111522
111208
  diagnostics.push(...rowMenuReads(path, ast));
111523
111209
  }
111524
- if (kind === "page" && checkModuleImports(root, path, ast, packages).blocksUnitBuild) {
111210
+ if (kind === "page" && unitBuildBlocked(moduleCheck, path)) {
111525
111211
  failedPages.add(path);
111526
111212
  uiEntries.push({ path, source, ast });
111527
111213
  return;
@@ -111693,7 +111379,7 @@ function buildMaterializedWorkspace(root, plan, { assetCatalog = null, writeSour
111693
111379
  const ast = parseSource(source, { jsx: path.endsWith("x") });
111694
111380
  const entry = { path, source, ast };
111695
111381
  diagnostics.push(...rowMenuReads(path, ast));
111696
- if (!checkModuleImports(root, path, ast, packages).blocksUnitBuild) {
111382
+ if (!unitBuildBlocked(moduleCheck, path)) {
111697
111383
  build(entry);
111698
111384
  }
111699
111385
  return entry;
@@ -111846,6 +111532,15 @@ function buildMaterializedWorkspace(root, plan, { assetCatalog = null, writeSour
111846
111532
  },
111847
111533
  diagnostics
111848
111534
  );
111535
+ moduleCheck = checkModules(root, {
111536
+ entries: [
111537
+ ...files.filter((path) => classify(path) === "page"),
111538
+ ...entryPaths,
111539
+ ...files.filter((path) => ["layouts", "components"].includes(topDirectory(path)) && /\.[jt]sx?$/.test(path))
111540
+ ],
111541
+ packages,
111542
+ assetKeys
111543
+ });
111849
111544
  for (const path of otherFiles) {
111850
111545
  buildFile(path);
111851
111546
  }
@@ -111925,12 +111620,10 @@ function buildMaterializedWorkspace(root, plan, { assetCatalog = null, writeSour
111925
111620
  (diagnostic2) => diagnostic2.severity === "error"
111926
111621
  );
111927
111622
  checkBrandAssets(brandAssets, assetsComplete ? output.assets : null, assetCatalog, diagnostics);
111928
- const moduleGraph = buildModuleGraph(
111929
- root,
111623
+ const { parsed: graphModules, ...moduleGraph } = buildModuleGraph(
111624
+ moduleCheck,
111930
111625
  uiEntries,
111931
- packages,
111932
111626
  diagnostics,
111933
- assetKeys,
111934
111627
  new Map([
111935
111628
  [GENERATED_RECORD_BINDINGS_PATH, recordBindingValues(recordBindings.entries)],
111936
111629
  [GENERATED_RESOURCES_PATH, resourceValues(entries)],
@@ -111952,7 +111645,7 @@ function buildMaterializedWorkspace(root, plan, { assetCatalog = null, writeSour
111952
111645
  if (module.kind !== "module" || !/\.[jt]sx?$/.test(path)) {
111953
111646
  continue;
111954
111647
  }
111955
- let entry = entriesByPath.get(path) ?? null;
111648
+ let entry = graphModules.get(path) ?? null;
111956
111649
  if (entry === null) {
111957
111650
  const source = readFileSync12(join16(root, path), "utf8");
111958
111651
  try {