@tailor-platform/sdk 1.60.3 → 1.63.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 (61) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/dist/{application-pusdxz35.mjs → application-BezXGbrU.mjs} +73 -509
  3. package/dist/application-BezXGbrU.mjs.map +1 -0
  4. package/dist/application-DSXntqnV.mjs +4 -0
  5. package/dist/assert-CKfwrmCV.mjs +10 -0
  6. package/dist/assert-CKfwrmCV.mjs.map +1 -0
  7. package/dist/cli/index.mjs +819 -239
  8. package/dist/cli/index.mjs.map +1 -1
  9. package/dist/cli/lib.d.mts +3 -1
  10. package/dist/cli/lib.mjs +13 -6
  11. package/dist/cli/lib.mjs.map +1 -1
  12. package/dist/{client-B-jRdlC_.mjs → client-C68VWo4g.mjs} +1 -1
  13. package/dist/{client-W5P4NYYX.mjs → client-CobIRHl-.mjs} +207 -2
  14. package/dist/{client-W5P4NYYX.mjs.map → client-CobIRHl-.mjs.map} +1 -1
  15. package/dist/configure/index.mjs +2 -2
  16. package/dist/{crashreport-D3DvAzdg.mjs → crashreport-BhD0y14F.mjs} +2 -2
  17. package/dist/{crashreport-D3DvAzdg.mjs.map → crashreport-BhD0y14F.mjs.map} +1 -1
  18. package/dist/{crashreport-lnVTnbB5.mjs → crashreport-D1wKBJ8N.mjs} +1 -1
  19. package/dist/{mock-Dpu__UeJ.mjs → mock-DMgIygjE.mjs} +3 -2
  20. package/dist/mock-DMgIygjE.mjs.map +1 -0
  21. package/dist/plugin/builtin/seed/index.mjs +1 -1
  22. package/dist/plugin/index.mjs +1 -1
  23. package/dist/plugin/index.mjs.map +1 -1
  24. package/dist/registry-D0uB0OrK.mjs.map +1 -1
  25. package/dist/{repl-editor-Y9QJDL0K.mjs → repl-editor-CJG3sz7A.mjs} +11 -9
  26. package/dist/repl-editor-CJG3sz7A.mjs.map +1 -0
  27. package/dist/{runtime-C0_FZWdE.mjs → runtime-CW3jcQCc.mjs} +979 -584
  28. package/dist/runtime-CW3jcQCc.mjs.map +1 -0
  29. package/dist/{schema-DYKNTu-n.mjs → schema-1msIhXwA.mjs} +12 -7
  30. package/dist/schema-1msIhXwA.mjs.map +1 -0
  31. package/dist/{seed-C0fE2sJB.mjs → seed-BH2FbrPV.mjs} +4 -3
  32. package/dist/seed-BH2FbrPV.mjs.map +1 -0
  33. package/dist/service-BHQIerYh.mjs +4 -0
  34. package/dist/{service-aPT0fx3y.mjs → service-DMohAx8a2.mjs} +3 -3
  35. package/dist/service-DMohAx8a2.mjs.map +1 -0
  36. package/dist/service-wI3Hvrgx.mjs +460 -0
  37. package/dist/service-wI3Hvrgx.mjs.map +1 -0
  38. package/dist/{types-Ccwchyj5.mjs → types-2Be3wSMc.mjs} +1 -1
  39. package/dist/{types-BwGth3a1.mjs → types-CmzfQP_m.mjs} +3 -3
  40. package/dist/types-CmzfQP_m.mjs.map +1 -0
  41. package/dist/utils/test/index.mjs +1 -1
  42. package/dist/utils/test/index.mjs.map +1 -1
  43. package/dist/vitest/index.mjs +7 -4
  44. package/dist/vitest/index.mjs.map +1 -1
  45. package/dist/vitest/setup.mjs +1 -1
  46. package/docs/cli/application.md +11 -10
  47. package/docs/cli/setup.md +18 -12
  48. package/docs/cli/tailordb.md +54 -0
  49. package/docs/cli-reference.md +4 -3
  50. package/docs/github-actions.md +337 -0
  51. package/docs/services/tailordb-migration.md +17 -1
  52. package/package.json +4 -3
  53. package/dist/application-D4tRNn90.mjs +0 -4
  54. package/dist/application-pusdxz35.mjs.map +0 -1
  55. package/dist/mock-Dpu__UeJ.mjs.map +0 -1
  56. package/dist/repl-editor-Y9QJDL0K.mjs.map +0 -1
  57. package/dist/runtime-C0_FZWdE.mjs.map +0 -1
  58. package/dist/schema-DYKNTu-n.mjs.map +0 -1
  59. package/dist/seed-C0fE2sJB.mjs.map +0 -1
  60. package/dist/service-aPT0fx3y.mjs.map +0 -1
  61. package/dist/types-BwGth3a1.mjs.map +0 -1
@@ -1,12 +1,14 @@
1
1
 
2
2
  import { n as isSdkBranded } from "./brand-DlnJ375c.mjs";
3
- import { a as fetchAll, d as initOAuth2Client } from "./client-W5P4NYYX.mjs";
3
+ import { a as fetchAll, d as initOAuth2Client } from "./client-CobIRHl-.mjs";
4
+ import { t as assertDefined } from "./assert-CKfwrmCV.mjs";
4
5
  import { a as parseBoolean, n as logger, r as styles } from "./logger-DpJyJvNz.mjs";
6
+ import { a as TailorFieldSchema, i as AuthInvokerSchema, n as ExecutorSchema, o as loadFilesWithIgnores, r as AuthConfigSchema, s as functionSchema, t as createExecutorService } from "./service-wI3Hvrgx.mjs";
5
7
  import { n as enumConstantsPlugin, t as EnumConstantsGeneratorID } from "./enum-constants-C7DaWeQo.mjs";
6
8
  import { t as multiline } from "./multiline-Cf9ODpr1.mjs";
7
9
  import { n as fileUtilsPlugin, t as FileUtilsGeneratorID } from "./file-utils-BHPxPXmn.mjs";
8
10
  import { n as kyselyTypePlugin, t as KyselyGeneratorID } from "./kysely-type-D1e0Vwkd.mjs";
9
- import { n as seedPlugin, r as isPluginGeneratedType, t as SeedGeneratorID } from "./seed-C0fE2sJB.mjs";
11
+ import { n as seedPlugin, r as isPluginGeneratedType, t as SeedGeneratorID } from "./seed-BH2FbrPV.mjs";
10
12
  import { t as readPackageJson } from "./package-json-DcQApfPQ.mjs";
11
13
  import { n as tightenSecretFilePermissions, r as writeSecretFile } from "./secret-file-CWzF8rry.mjs";
12
14
  import { builtinModules, createRequire } from "node:module";
@@ -120,10 +122,6 @@ const BaseGeneratorConfigSchema = z.union([
120
122
  CodeGeneratorSchema
121
123
  ]);
122
124
 
123
- //#endregion
124
- //#region src/parser/service/common.ts
125
- const functionSchema = z.custom((val) => typeof val === "function");
126
-
127
125
  //#endregion
128
126
  //#region src/parser/plugin-config/schema.ts
129
127
  const PluginConfigSchema = z.object({
@@ -457,7 +455,7 @@ async function loadAccessToken(opts) {
457
455
  }
458
456
  const pfConfig = await readPlatformConfig();
459
457
  let user;
460
- const profile = opts?.useProfile ? opts.profile || process.env.TAILOR_PLATFORM_PROFILE : void 0;
458
+ const profile = opts?.profile || process.env.TAILOR_PLATFORM_PROFILE;
461
459
  if (profile) {
462
460
  const u = pfConfig.profiles[profile]?.user;
463
461
  if (!u) throw new Error(`Profile "${profile}" not found`);
@@ -555,7 +553,7 @@ async function fetchLatestToken(config, user) {
555
553
  Please run 'tailor-sdk login' and try again.
556
554
  `);
557
555
  }
558
- const newExpiresAt = new Date(resp.expiresAt).toISOString();
556
+ const newExpiresAt = new Date(assertDefined(resp.expiresAt, "token refresh response missing expiresAt")).toISOString();
559
557
  await saveUserTokens(config, user, {
560
558
  accessToken: resp.accessToken,
561
559
  refreshToken: resp.refreshToken ?? void 0
@@ -988,7 +986,7 @@ function collectTypeImports(context, outputDir, pluginId, typeGenerationResult,
988
986
  let importPath;
989
987
  let isGeneratedType = false;
990
988
  if (typeGenerationResult?.typeFilePaths.has(typeName)) {
991
- const typeFilePath = typeGenerationResult.typeFilePaths.get(typeName);
989
+ const typeFilePath = assertDefined(typeGenerationResult.typeFilePaths.get(typeName), "type file path missing");
992
990
  const absoluteTypePath = path.join(outputDir, typeFilePath);
993
991
  importPath = path.relative(executorDir, absoluteTypePath).replace(/\.ts$/, "");
994
992
  if (!importPath.startsWith(".")) importPath = `./${importPath}`;
@@ -1150,7 +1148,7 @@ function resolveExecutorImportPath(resolve, pluginImportPath, executorOutputDir,
1150
1148
  function extractDynamicImportSpecifier(resolve) {
1151
1149
  const match = resolve.toString().match(/import\s*\(\s*["']([^"']+)["']\s*\)/);
1152
1150
  if (!match) throw new Error(`resolve() must return a dynamic import, e.g. \`async () => await import("./executors/on-create")\`.`);
1153
- return match[1];
1151
+ return assertDefined(match[1], "dynamic import specifier capture group missing");
1154
1152
  }
1155
1153
  /**
1156
1154
  * Resolve plugin base directory for relative imports.
@@ -1478,39 +1476,6 @@ const platformBundleDefinePlugin = {
1478
1476
  }
1479
1477
  };
1480
1478
 
1481
- //#endregion
1482
- //#region src/cli/services/file-loader.ts
1483
- const DEFAULT_IGNORE_PATTERNS = ["**/*.test.ts", "**/*.spec.ts"];
1484
- /**
1485
- * Load files matching the given patterns, excluding files that match ignore patterns.
1486
- * By default, test files (*.test.ts, *.spec.ts) are excluded unless ignores is explicitly specified.
1487
- * @param config - Configuration with files patterns and optional ignores patterns
1488
- * @returns Array of absolute file paths
1489
- */
1490
- function loadFilesWithIgnores(config) {
1491
- const ignorePatterns = config.ignores ?? DEFAULT_IGNORE_PATTERNS;
1492
- const ignoreFiles = /* @__PURE__ */ new Set();
1493
- for (const ignorePattern of ignorePatterns) {
1494
- const absoluteIgnorePattern = path.resolve(process.cwd(), ignorePattern);
1495
- try {
1496
- fs$1.globSync(absoluteIgnorePattern).forEach((file) => ignoreFiles.add(file));
1497
- } catch (error) {
1498
- logger.warn(`Failed to glob ignore pattern "${ignorePattern}": ${String(error)}`);
1499
- }
1500
- }
1501
- const files = [];
1502
- for (const pattern of config.files) {
1503
- const absolutePattern = path.resolve(process.cwd(), pattern);
1504
- try {
1505
- const filteredFiles = fs$1.globSync(absolutePattern).filter((file) => !ignoreFiles.has(file));
1506
- files.push(...filteredFiles);
1507
- } catch (error) {
1508
- logger.warn(`Failed to glob pattern "${pattern}": ${String(error)}`);
1509
- }
1510
- }
1511
- return files;
1512
- }
1513
-
1514
1479
  //#endregion
1515
1480
  //#region src/cli/services/workflow/ast-utils.ts
1516
1481
  /**
@@ -1640,33 +1605,32 @@ function collectSdkBindings(program, functionName) {
1640
1605
  const nodeType = node.type;
1641
1606
  if (nodeType === "ImportDeclaration") {
1642
1607
  const importDecl = node;
1643
- const source = importDecl.source?.value;
1608
+ const source = importDecl.source.value;
1644
1609
  if (typeof source === "string" && isTailorSdkSource(source)) {
1645
- for (const specifier of importDecl.specifiers || []) if (specifier.type === "ImportSpecifier") {
1610
+ for (const specifier of importDecl.specifiers) if (specifier.type === "ImportSpecifier") {
1646
1611
  const importSpec = specifier;
1647
- const imported = importSpec.imported.type === "Identifier" ? importSpec.imported.name : importSpec.imported.value;
1648
- if (imported === functionName) bindings.add(importSpec.local?.name || imported);
1612
+ if ((importSpec.imported.type === "Identifier" ? importSpec.imported.name : importSpec.imported.value) === functionName) bindings.add(importSpec.local.name);
1649
1613
  } else if (specifier.type === "ImportDefaultSpecifier" || specifier.type === "ImportNamespaceSpecifier") {
1650
1614
  const spec = specifier;
1651
- bindings.add(`__namespace__:${spec.local?.name}`);
1615
+ bindings.add(`__namespace__:${spec.local.name}`);
1652
1616
  }
1653
1617
  }
1654
1618
  }
1655
1619
  if (nodeType === "VariableDeclaration") {
1656
1620
  const varDecl = node;
1657
- for (const decl of varDecl.declarations || []) {
1621
+ for (const decl of varDecl.declarations) {
1658
1622
  const source = getImportSource(unwrapAwait(decl.init));
1659
1623
  if (source && isTailorSdkSource(source)) {
1660
1624
  const id = decl.id;
1661
- if (id?.type === "Identifier") bindings.add(`__namespace__:${id.name}`);
1662
- else if (id?.type === "ObjectPattern") {
1625
+ if (id.type === "Identifier") bindings.add(`__namespace__:${id.name}`);
1626
+ else if (id.type === "ObjectPattern") {
1663
1627
  const objPattern = id;
1664
- for (const prop of objPattern.properties || []) if (prop.type === "Property") {
1628
+ for (const prop of objPattern.properties) if (prop.type === "Property") {
1665
1629
  const bindingProp = prop;
1666
1630
  const keyName = bindingProp.key.type === "Identifier" ? bindingProp.key.name : bindingProp.key.value;
1667
1631
  if (keyName === functionName) {
1668
1632
  const localName = bindingProp.value.type === "Identifier" ? bindingProp.value.name : keyName;
1669
- bindings.add(localName ?? "");
1633
+ bindings.add(localName);
1670
1634
  }
1671
1635
  }
1672
1636
  }
@@ -1722,15 +1686,16 @@ function findAllJobs(program, _sourceText) {
1722
1686
  if (!node || typeof node !== "object") return;
1723
1687
  if (isSdkFunctionCall(node, bindings, "createWorkflowJob")) {
1724
1688
  const args = node.arguments;
1725
- if (args?.length >= 1 && args[0]?.type === "ObjectExpression") {
1726
- const configObj = args[0];
1689
+ const firstArg = args[0];
1690
+ if (args.length >= 1 && firstArg?.type === "ObjectExpression") {
1691
+ const configObj = assertDefined(firstArg, "createWorkflowJob first argument missing");
1727
1692
  const nameProp = findProperty(configObj.properties, "name");
1728
1693
  const bodyProp = findProperty(configObj.properties, "body");
1729
1694
  if (nameProp && isStringLiteral(nameProp.value) && bodyProp && isFunctionExpression(bodyProp.value)) {
1730
1695
  let statementRange;
1731
1696
  let exportName;
1732
1697
  for (let i = parents.length - 1; i >= 0; i--) {
1733
- const parent = parents[i];
1698
+ const parent = assertDefined(parents[i], `parent at index ${i} missing`);
1734
1699
  if (parent.type === "VariableDeclarator") {
1735
1700
  const declarator = parent;
1736
1701
  if (declarator.id?.type === "Identifier") exportName = declarator.id.name;
@@ -1835,14 +1800,14 @@ function findAllWorkflows(program, _sourceText) {
1835
1800
  if (!node || typeof node !== "object") return;
1836
1801
  if (isSdkFunctionCall(node, bindings, "createWorkflow")) {
1837
1802
  const args = node.arguments;
1838
- if (args?.length >= 1 && args[0]?.type === "ObjectExpression") {
1839
- const configObj = args[0];
1840
- const nameProp = findProperty(configObj.properties, "name");
1803
+ const firstArg = args[0];
1804
+ if (args.length >= 1 && firstArg?.type === "ObjectExpression") {
1805
+ const nameProp = findProperty(assertDefined(firstArg, "createWorkflow first argument missing").properties, "name");
1841
1806
  if (nameProp && isStringLiteral(nameProp.value)) {
1842
1807
  let exportName;
1843
1808
  let isDefaultExport = false;
1844
1809
  for (let i = parents.length - 1; i >= 0; i--) {
1845
- const parent = parents[i];
1810
+ const parent = assertDefined(parents[i], `parent at index ${i} missing`);
1846
1811
  if (parent.type === "VariableDeclarator") {
1847
1812
  const declarator = parent;
1848
1813
  if (declarator.id?.type === "Identifier") {
@@ -1891,11 +1856,11 @@ function detectDefaultImports(program) {
1891
1856
  if (!node || typeof node !== "object") return;
1892
1857
  if (node.type === "ImportDeclaration") {
1893
1858
  const importDecl = node;
1894
- const source = importDecl.source?.value;
1859
+ const source = importDecl.source.value;
1895
1860
  if (typeof source === "string") {
1896
- for (const specifier of importDecl.specifiers || []) if (specifier.type === "ImportDefaultSpecifier") {
1861
+ for (const specifier of importDecl.specifiers) if (specifier.type === "ImportDefaultSpecifier") {
1897
1862
  const spec = specifier;
1898
- if (spec.local?.name) imports.set(spec.local.name, source);
1863
+ if (spec.local.name) imports.set(spec.local.name, source);
1899
1864
  }
1900
1865
  }
1901
1866
  }
@@ -2048,11 +2013,11 @@ function findDefaultImportRemovalRange(program, localName, source) {
2048
2013
  for (const statement of program.body) {
2049
2014
  if (statement.type !== "ImportDeclaration") continue;
2050
2015
  const importDecl = statement;
2051
- const specifiers = importDecl.specifiers || [];
2016
+ const specifiers = importDecl.specifiers;
2052
2017
  for (const spec of specifiers) {
2053
2018
  if (spec.type !== "ImportDefaultSpecifier") continue;
2054
2019
  const defaultSpec = spec;
2055
- if (defaultSpec.local?.name !== localName) continue;
2020
+ if (defaultSpec.local.name !== localName) continue;
2056
2021
  if (specifiers.length === 1) return {
2057
2022
  start: importDecl.start,
2058
2023
  end: importDecl.end,
@@ -2752,7 +2717,7 @@ function parseTailorDBType(type, allTypeNames, rawTypes) {
2752
2717
  targetField: fieldName,
2753
2718
  sourceField: relationInfo.key,
2754
2719
  isArray: false,
2755
- description: targetType?.metadata?.description || ""
2720
+ description: targetType?.metadata.description || ""
2756
2721
  };
2757
2722
  }
2758
2723
  fields[fieldName] = parsedField;
@@ -2764,8 +2729,8 @@ function parseTailorDBType(type, allTypeNames, rawTypes) {
2764
2729
  fields,
2765
2730
  forwardRelationships,
2766
2731
  backwardRelationships: createRecord(),
2767
- settings: metadata.settings || {},
2768
- permissions: parsePermissions(metadata.permissions || {}),
2732
+ settings: metadata.settings ?? {},
2733
+ permissions: parsePermissions(metadata.permissions),
2769
2734
  indexes: metadata.indexes,
2770
2735
  files: metadata.files
2771
2736
  };
@@ -2786,8 +2751,12 @@ function buildBackwardRelationships(types, namespace, typeSourceInfo) {
2786
2751
  const lowerName = inflection.camelize(otherTypeName, true);
2787
2752
  backwardName = field.relation.unique ? inflection.singularize(lowerName) : inflection.pluralize(lowerName);
2788
2753
  }
2789
- if (!backwardNameSources[typeName][backwardName]) backwardNameSources[typeName][backwardName] = [];
2790
- backwardNameSources[typeName][backwardName].push({
2754
+ const typeBackwardNames = backwardNameSources[typeName];
2755
+ if (typeBackwardNames === void 0) throw new Error(`backward name sources not initialized for type: ${typeName}`);
2756
+ if (!typeBackwardNames[backwardName]) typeBackwardNames[backwardName] = [];
2757
+ const sources = typeBackwardNames[backwardName];
2758
+ if (sources === void 0) throw new Error(`backward name sources entry not initialized for: ${backwardName}`);
2759
+ sources.push({
2791
2760
  sourceType: otherTypeName,
2792
2761
  fieldName
2793
2762
  });
@@ -2803,6 +2772,7 @@ function buildBackwardRelationships(types, namespace, typeSourceInfo) {
2803
2772
  const errors = [];
2804
2773
  for (const [targetTypeName, backwardNames] of Object.entries(backwardNameSources)) {
2805
2774
  const targetType = types[targetTypeName];
2775
+ if (targetType === void 0) throw new Error(`type not found: ${targetTypeName}`);
2806
2776
  const targetTypeSourceInfo = getTypeSourceInfo(typeSourceInfo, targetTypeName);
2807
2777
  const targetLocation = targetTypeSourceInfo ? isPluginGeneratedType(targetTypeSourceInfo) ? ` (plugin: ${targetTypeSourceInfo.pluginId})` : ` (${targetTypeSourceInfo.filePath})` : "";
2808
2778
  for (const [backwardName, sources] of Object.entries(backwardNames)) {
@@ -2816,12 +2786,14 @@ function buildBackwardRelationships(types, namespace, typeSourceInfo) {
2816
2786
  }
2817
2787
  if (Object.hasOwn(targetType.fields, backwardName)) {
2818
2788
  const source = sources[0];
2789
+ if (source === void 0) throw new Error(`no source found for backward name: ${backwardName}`);
2819
2790
  const sourceInfo = getTypeSourceInfo(typeSourceInfo, source.sourceType);
2820
2791
  const sourceLocation = sourceInfo ? isPluginGeneratedType(sourceInfo) ? ` (plugin: ${sourceInfo.pluginId})` : ` (${sourceInfo.filePath})` : "";
2821
2792
  errors.push(`Backward relation name "${backwardName}" from ${source.sourceType}.${source.fieldName}${sourceLocation} conflicts with existing field "${backwardName}" on type "${targetTypeName}"${targetLocation}. Use the "backward" option in .relation() to specify a different name.`);
2822
2793
  }
2823
2794
  if (targetType.files && Object.hasOwn(targetType.files, backwardName)) {
2824
2795
  const source = sources[0];
2796
+ if (source === void 0) throw new Error(`no source found for backward name: ${backwardName}`);
2825
2797
  const sourceInfo = getTypeSourceInfo(typeSourceInfo, source.sourceType);
2826
2798
  const sourceLocation = sourceInfo ? isPluginGeneratedType(sourceInfo) ? ` (plugin: ${sourceInfo.pluginId})` : ` (${sourceInfo.filePath})` : "";
2827
2799
  errors.push(`Backward relation name "${backwardName}" from ${source.sourceType}.${source.fieldName}${sourceLocation} conflicts with files field "${backwardName}" on type "${targetTypeName}"${targetLocation}. Use the "backward" option in .relation() to specify a different name.`);
@@ -2913,7 +2885,7 @@ const GqlOperationsSchema = z.union([z.literal("query"), z.object({
2913
2885
  delete: z.boolean().optional().describe("Enable delete mutation (default: true)"),
2914
2886
  read: z.boolean().optional().describe("Enable read queries - get, list, aggregation (default: true)")
2915
2887
  })]).describe("Configuration for GraphQL operations on a TailorDB type.\nAll operations are enabled by default (undefined or true = enabled, false = disabled).").transform((val) => normalizeGqlOperations(val));
2916
- const TailorFieldTypeSchema$1 = z.enum([
2888
+ const TailorFieldTypeSchema = z.enum([
2917
2889
  "uuid",
2918
2890
  "string",
2919
2891
  "boolean",
@@ -2926,7 +2898,7 @@ const TailorFieldTypeSchema$1 = z.enum([
2926
2898
  "time",
2927
2899
  "nested"
2928
2900
  ]);
2929
- const AllowedValueSchema$1 = z.object({
2901
+ const AllowedValueSchema = z.object({
2930
2902
  value: z.string(),
2931
2903
  description: z.string().optional()
2932
2904
  });
@@ -2935,7 +2907,7 @@ const DBFieldMetadataSchema = z.object({
2935
2907
  array: z.boolean().optional().describe("Whether the field is an array"),
2936
2908
  description: z.string().optional().describe("Field description"),
2937
2909
  typeName: z.string().optional().describe("Type name for nested or enum fields"),
2938
- allowedValues: z.array(AllowedValueSchema$1).optional().describe("Allowed values for enum fields"),
2910
+ allowedValues: z.array(AllowedValueSchema).optional().describe("Allowed values for enum fields"),
2939
2911
  index: z.boolean().optional().describe("Whether the field is indexed for faster queries"),
2940
2912
  unique: z.boolean().optional().describe("Whether the field value must be unique"),
2941
2913
  vector: z.boolean().optional().describe("Whether the field is a vector field for similarity search"),
@@ -2965,7 +2937,7 @@ const RawRelationConfigSchema = z.object({
2965
2937
  backward: z.string().optional().describe("Backward relation name on the target type")
2966
2938
  });
2967
2939
  const TailorDBFieldSchema = z.lazy(() => z.object({
2968
- type: TailorFieldTypeSchema$1,
2940
+ type: TailorFieldTypeSchema,
2969
2941
  fields: z.record(z.string(), TailorDBFieldSchema).optional(),
2970
2942
  metadata: DBFieldMetadataSchema,
2971
2943
  rawRelation: RawRelationConfigSchema.optional()
@@ -3287,7 +3259,7 @@ function collectSourceBindings(sourceFilePath) {
3287
3259
  for (const stmt of program.body) if (stmt.type === "ImportDeclaration") {
3288
3260
  const importDecl = stmt;
3289
3261
  const text = source.slice(importDecl.start, importDecl.end);
3290
- if (importDecl.specifiers) for (const spec of importDecl.specifiers) bindings.set(spec.local.name, {
3262
+ for (const spec of importDecl.specifiers) bindings.set(spec.local.name, {
3291
3263
  name: spec.local.name,
3292
3264
  sourceText: text,
3293
3265
  kind: "import"
@@ -3452,8 +3424,8 @@ async function precompileTailorDBTypeScripts(type, sourceFilePath, tsconfig) {
3452
3424
  tsconfig
3453
3425
  })));
3454
3426
  const firstError = results.find((r) => r.status === "rejected");
3455
- if (firstError && firstError.status === "rejected") throw firstError.reason;
3456
- for (const [index, result] of results.entries()) if (result.status === "fulfilled") setPrecompiledScriptExpr(targets[index].fn, result.value);
3427
+ if (firstError) throw firstError.reason;
3428
+ for (const [index, result] of results.entries()) if (result.status === "fulfilled") setPrecompiledScriptExpr(assertDefined(targets[index], `bundle target at index ${index} missing`).fn, result.value);
3457
3429
  } finally {
3458
3430
  rmSync(tempDir, {
3459
3431
  recursive: true,
@@ -3588,7 +3560,7 @@ function createTailorDBService(params) {
3588
3560
  const secondSource = formatTailorDBTypeSourceInfo(sourceInfo) ?? "unknown source";
3589
3561
  throw new Error(`Duplicate TailorDB type name "${typeName}" detected in TailorDB service "${namespace}". First: ${firstSource}. Second: ${secondSource}. TailorDB type names must be unique across all TailorDB files in a service.`);
3590
3562
  }
3591
- rawTypes[rawTypesKey][typeName] = type;
3563
+ assertDefined(rawTypes[rawTypesKey], `raw types entry missing for key: ${rawTypesKey}`)[typeName] = type;
3592
3564
  typeSourceInfo[typeName] = sourceInfo;
3593
3565
  };
3594
3566
  const doParseTypes = () => {
@@ -3598,7 +3570,7 @@ function createTailorDBService(params) {
3598
3570
  };
3599
3571
  const warnOmittedPermit = () => {
3600
3572
  for (const fileTypes of Object.values(rawTypes)) for (const [typeName, type] of Object.entries(fileTypes)) {
3601
- const locations = findOmittedPermitRules(type.metadata.permissions ?? {});
3573
+ const locations = findOmittedPermitRules(type.metadata.permissions);
3602
3574
  if (locations.length > 0) logger.warn(`TailorDB type "${typeName}" has permission rule(s) ${locations.join(", ")} in object form without an explicit "permit"; they default to "deny". Set permit: true (allow) or permit: false (deny) to silence this warning.`);
3603
3575
  }
3604
3576
  };
@@ -3615,7 +3587,7 @@ function createTailorDBService(params) {
3615
3587
  attachments,
3616
3588
  namespace
3617
3589
  });
3618
- if (extendedType) rawTypes[sourceFilePath][rawType.name] = extendedType;
3590
+ if (extendedType) assertDefined(rawTypes[sourceFilePath], `raw types entry missing for file: ${sourceFilePath}`)[rawType.name] = extendedType;
3619
3591
  for (const gen of generatedTypes) {
3620
3592
  const sourceInfo = {
3621
3593
  exportName: gen.typeName,
@@ -3680,7 +3652,7 @@ function createTailorDBService(params) {
3680
3652
  },
3681
3653
  loadTypes: async () => {
3682
3654
  if (!loadPromise) loadPromise = (async () => {
3683
- if (!config.files || config.files.length === 0) return;
3655
+ if (config.files.length === 0) return;
3684
3656
  const typeFiles = [...new Set(loadFilesWithIgnores(config))];
3685
3657
  let tsconfig;
3686
3658
  try {
@@ -3713,9 +3685,11 @@ function createTailorDBService(params) {
3713
3685
  output: result.output
3714
3686
  };
3715
3687
  });
3688
+ const hasPreviousGeneratedTypes = Object.hasOwn(rawTypes, pluginGeneratedKey);
3716
3689
  const previousGeneratedTypes = rawTypes[pluginGeneratedKey];
3717
- const hadPreviousGeneratedTypes = previousGeneratedTypes !== void 0 && Object.keys(previousGeneratedTypes).length > 0;
3718
- if (previousGeneratedTypes) for (const typeName of Object.keys(previousGeneratedTypes)) delete typeSourceInfo[typeName];
3690
+ const previousGeneratedTypeKeys = previousGeneratedTypes ? Object.keys(previousGeneratedTypes) : [];
3691
+ const hadPreviousGeneratedTypes = previousGeneratedTypeKeys.length > 0;
3692
+ if (hasPreviousGeneratedTypes) for (const typeName of previousGeneratedTypeKeys) delete typeSourceInfo[typeName];
3719
3693
  rawTypes[pluginGeneratedKey] = createRawTypesByName();
3720
3694
  let hasGeneratedTypes = false;
3721
3695
  for (const { pluginId, config, output } of successfulResults) for (const [kind, generatedType] of Object.entries(output.types ?? {})) {
@@ -3738,251 +3712,6 @@ function createTailorDBService(params) {
3738
3712
  };
3739
3713
  }
3740
3714
 
3741
- //#endregion
3742
- //#region src/parser/service/auth-connection/schema.ts
3743
- const AuthConnectionOAuth2ConfigSchema = z.object({
3744
- providerUrl: z.string().describe("OAuth2 provider URL"),
3745
- issuerUrl: z.string().describe("OAuth2 issuer URL"),
3746
- clientId: z.string().describe("OAuth2 client ID"),
3747
- clientSecret: z.string().describe("OAuth2 client secret"),
3748
- authUrl: z.string().optional().describe("OAuth2 authorization endpoint override"),
3749
- tokenUrl: z.string().optional().describe("OAuth2 token endpoint override")
3750
- });
3751
- const AuthConnectionConfigSchema = z.object({ type: z.literal("oauth2").describe("Connection type") }).and(AuthConnectionOAuth2ConfigSchema);
3752
-
3753
- //#endregion
3754
- //#region src/parser/service/field/schema.ts
3755
- const TailorFieldTypeSchema = z.enum([
3756
- "uuid",
3757
- "string",
3758
- "boolean",
3759
- "integer",
3760
- "float",
3761
- "decimal",
3762
- "enum",
3763
- "date",
3764
- "datetime",
3765
- "time",
3766
- "nested"
3767
- ]);
3768
- const AllowedValueSchema = z.object({
3769
- value: z.string().describe("The allowed value"),
3770
- description: z.string().optional().describe("Description of the allowed value")
3771
- });
3772
- const FieldMetadataSchema = z.object({
3773
- required: z.boolean().optional().describe("Whether the field is required"),
3774
- array: z.boolean().optional().describe("Whether the field is an array"),
3775
- description: z.string().optional().describe("Field description"),
3776
- allowedValues: z.array(AllowedValueSchema).optional().describe("Allowed values for enum fields"),
3777
- hooks: z.object({
3778
- create: functionSchema.optional().describe("Hook function called on creation"),
3779
- update: functionSchema.optional().describe("Hook function called on update")
3780
- }).optional().describe("Lifecycle hooks"),
3781
- typeName: z.string().optional().describe("Type name for nested or enum fields")
3782
- });
3783
- const TailorFieldSchema = z.object({
3784
- type: TailorFieldTypeSchema.describe("Field data type"),
3785
- metadata: FieldMetadataSchema.describe("Field metadata configuration"),
3786
- get fields() {
3787
- return z.record(z.string(), TailorFieldSchema);
3788
- }
3789
- });
3790
-
3791
- //#endregion
3792
- //#region src/parser/service/auth/schema.ts
3793
- const AuthInvokerObjectSchema = z.object({
3794
- namespace: z.string().describe("Auth namespace"),
3795
- machineUserName: z.string().describe("Machine user name for authentication")
3796
- });
3797
- const AuthInvokerSchema = z.union([z.string().describe("Machine user name (namespace auto-resolved from auth service)"), AuthInvokerObjectSchema]);
3798
- const secretValueSchema = z.object({
3799
- vaultName: z.string().describe("Vault name containing the secret"),
3800
- secretKey: z.string().describe("Key of the secret in the vault")
3801
- });
3802
- const OIDCSchema = z.object({
3803
- name: z.string().describe("Identity provider name"),
3804
- kind: z.literal("OIDC"),
3805
- clientID: z.string().describe("OAuth2 client ID"),
3806
- clientSecret: secretValueSchema.describe("OAuth2 client secret"),
3807
- providerURL: z.string().describe("OIDC provider URL"),
3808
- issuerURL: z.string().optional().describe("OIDC issuer URL (defaults to providerURL)"),
3809
- usernameClaim: z.string().optional().describe("JWT claim to use as username")
3810
- });
3811
- const SAMLSchema = z.object({
3812
- name: z.string().describe("Identity provider name"),
3813
- kind: z.literal("SAML"),
3814
- enableSignRequest: z.boolean().default(false).describe("Enable signing of SAML requests"),
3815
- metadataURL: z.string().optional().describe("URL to fetch SAML metadata (mutually exclusive with rawMetadata)"),
3816
- rawMetadata: z.string().optional().describe("Raw SAML metadata XML (mutually exclusive with metadataURL)"),
3817
- defaultRedirectURL: z.string().optional().describe("URL to redirect to when SAML ACS receives a response with an empty RelayState.")
3818
- }).refine((value) => {
3819
- return value.metadataURL !== void 0 !== (value.rawMetadata !== void 0);
3820
- }, "Provide either metadataURL or rawMetadata");
3821
- const IDTokenSchema = z.object({
3822
- name: z.string().describe("Identity provider name"),
3823
- kind: z.literal("IDToken"),
3824
- providerURL: z.string().describe("ID token provider URL"),
3825
- issuerURL: z.string().optional().describe("ID token issuer URL"),
3826
- clientID: z.string().describe("Client ID for ID token validation"),
3827
- usernameClaim: z.string().optional().describe("JWT claim to use as username")
3828
- });
3829
- const BuiltinIdPSchema = z.object({
3830
- name: z.string().describe("Identity provider name"),
3831
- kind: z.literal("BuiltInIdP"),
3832
- namespace: z.string().describe("IdP namespace"),
3833
- clientName: z.string().describe("OAuth2 client name in the IdP")
3834
- });
3835
- const IdProviderSchema = z.discriminatedUnion("kind", [
3836
- OIDCSchema,
3837
- SAMLSchema,
3838
- IDTokenSchema,
3839
- BuiltinIdPSchema
3840
- ]);
3841
- const OAuth2ClientGrantTypeSchema = z.union([z.literal("authorization_code"), z.literal("refresh_token")]).describe("OAuth2 grant type");
3842
- const OAuth2ClientSchema = z.object({
3843
- description: z.string().optional().describe("Client description"),
3844
- grantTypes: z.array(OAuth2ClientGrantTypeSchema).default(["authorization_code", "refresh_token"]).describe("Allowed OAuth2 grant types"),
3845
- redirectURIs: z.array(z.union([
3846
- z.templateLiteral(["https://", z.string()]),
3847
- z.templateLiteral(["http://", z.string()]),
3848
- z.templateLiteral([z.string(), ":url"]),
3849
- z.templateLiteral([
3850
- z.string(),
3851
- ":url/",
3852
- z.string()
3853
- ])
3854
- ])).describe("Allowed redirect URIs"),
3855
- clientType: z.union([
3856
- z.literal("confidential"),
3857
- z.literal("public"),
3858
- z.literal("browser")
3859
- ]).optional().describe("OAuth2 client type"),
3860
- accessTokenLifetimeSeconds: z.number().int().min(60, "Minimum access token lifetime is 60 seconds").max(86400, "Maximum access token lifetime is 1 day (86400 seconds)").optional().describe("Access token lifetime in seconds (60-86400)").transform((val) => val ? {
3861
- seconds: BigInt(val),
3862
- nanos: 0
3863
- } : void 0),
3864
- refreshTokenLifetimeSeconds: z.number().int().min(60, "Minimum refresh token lifetime is 60 seconds").max(604800, "Maximum refresh token lifetime is 7 days (604800 seconds)").optional().describe("Refresh token lifetime in seconds (60-604800)").transform((val) => val ? {
3865
- seconds: BigInt(val),
3866
- nanos: 0
3867
- } : void 0),
3868
- requireDpop: z.boolean().optional().describe("Require DPoP (Demonstrating Proof-of-Possession) for token requests")
3869
- }).refine((data) => !(data.clientType === "browser" && data.requireDpop === true), {
3870
- message: "requireDpop cannot be set to true for browser clients as they don't support DPoP",
3871
- path: ["requireDpop"]
3872
- });
3873
- const SCIMAuthorizationSchema = z.object({
3874
- type: z.union([z.literal("oauth2"), z.literal("bearer")]).describe("SCIM authorization type"),
3875
- bearerSecret: secretValueSchema.optional().describe("Bearer token secret (required for bearer type)")
3876
- });
3877
- const SCIMAttributeTypeSchema = z.union([
3878
- z.literal("string"),
3879
- z.literal("number"),
3880
- z.literal("boolean"),
3881
- z.literal("datetime"),
3882
- z.literal("complex")
3883
- ]).describe("SCIM attribute data type");
3884
- const SCIMAttributeSchema = z.object({
3885
- type: SCIMAttributeTypeSchema.describe("Attribute data type"),
3886
- name: z.string().describe("Attribute name"),
3887
- description: z.string().optional().describe("Attribute description"),
3888
- mutability: z.union([
3889
- z.literal("readOnly"),
3890
- z.literal("readWrite"),
3891
- z.literal("writeOnly")
3892
- ]).optional().describe("Attribute mutability"),
3893
- required: z.boolean().optional().describe("Whether the attribute is required"),
3894
- multiValued: z.boolean().optional().describe("Whether the attribute can have multiple values"),
3895
- uniqueness: z.union([
3896
- z.literal("none"),
3897
- z.literal("server"),
3898
- z.literal("global")
3899
- ]).optional().describe("Uniqueness constraint"),
3900
- canonicalValues: z.array(z.string()).nullable().optional().describe("List of canonical values"),
3901
- get subAttributes() {
3902
- return z.array(SCIMAttributeSchema).nullable().optional();
3903
- }
3904
- });
3905
- const SCIMSchemaSchema = z.object({
3906
- name: z.string().describe("SCIM schema name"),
3907
- attributes: z.array(SCIMAttributeSchema).describe("Schema attributes")
3908
- });
3909
- const SCIMAttributeMappingSchema = z.object({
3910
- tailorDBField: z.string().describe("TailorDB field name to map to"),
3911
- scimPath: z.string().describe("SCIM attribute path")
3912
- });
3913
- const SCIMResourceSchema = z.object({
3914
- name: z.string().describe("SCIM resource name"),
3915
- tailorDBNamespace: z.string().describe("TailorDB namespace for the resource"),
3916
- tailorDBType: z.string().describe("TailorDB type name for the resource"),
3917
- coreSchema: SCIMSchemaSchema.describe("Core SCIM schema definition"),
3918
- attributeMapping: z.array(SCIMAttributeMappingSchema).describe("Attribute mapping configuration")
3919
- });
3920
- const SCIMSchema = z.object({
3921
- machineUserName: z.string().describe("Machine user name for SCIM operations"),
3922
- authorization: SCIMAuthorizationSchema.describe("SCIM authorization configuration"),
3923
- resources: z.array(SCIMResourceSchema).describe("SCIM resource definitions")
3924
- });
3925
- const TenantProviderSchema = z.object({
3926
- namespace: z.string().describe("TailorDB namespace for the tenant type"),
3927
- type: z.string().describe("TailorDB type name for tenants"),
3928
- signatureField: z.string().describe("Field used as the tenant signature")
3929
- });
3930
- const UserProfileSchema = z.object({
3931
- namespace: z.string().optional().describe("TailorDB namespace where the user type is defined"),
3932
- type: z.object({
3933
- name: z.string(),
3934
- fields: z.any(),
3935
- metadata: z.any(),
3936
- hooks: z.any(),
3937
- validate: z.any(),
3938
- features: z.any(),
3939
- indexes: z.any(),
3940
- files: z.any(),
3941
- permission: z.any(),
3942
- gqlPermission: z.any(),
3943
- _output: z.any()
3944
- }),
3945
- usernameField: z.string(),
3946
- attributes: z.record(z.string(), z.literal(true)).optional(),
3947
- attributeList: z.array(z.string()).optional()
3948
- });
3949
- const ValueOperandSchema = z.union([
3950
- z.string(),
3951
- z.boolean(),
3952
- z.array(z.string()),
3953
- z.array(z.boolean())
3954
- ]);
3955
- const MachineUserSchema = z.object({
3956
- attributes: z.record(z.string(), ValueOperandSchema).optional(),
3957
- attributeList: z.array(z.uuid()).optional()
3958
- });
3959
- const BeforeLoginHookSchema = z.object({
3960
- handler: z.function(),
3961
- invoker: z.string()
3962
- });
3963
- const AuthConfigBaseSchema = z.object({
3964
- name: z.string().describe("Auth service name"),
3965
- hooks: z.object({ beforeLogin: BeforeLoginHookSchema.optional().describe("Before login auth hook") }).optional().describe("Auth hooks"),
3966
- machineUsers: z.record(z.string(), MachineUserSchema).optional().describe("Machine user definitions"),
3967
- oauth2Clients: z.record(z.string(), OAuth2ClientSchema).optional().describe("OAuth2 client definitions"),
3968
- idProvider: IdProviderSchema.optional().describe("Identity provider configuration"),
3969
- scim: SCIMSchema.optional().describe("SCIM provisioning configuration"),
3970
- tenantProvider: TenantProviderSchema.optional().describe("Multi-tenant provider configuration"),
3971
- connections: z.record(z.string(), AuthConnectionConfigSchema).optional().describe("Auth connection definitions for external OAuth2 providers"),
3972
- publishSessionEvents: z.boolean().optional().describe("Enable publishing session events")
3973
- });
3974
- const AuthConfigSchema = z.xor([AuthConfigBaseSchema.extend({
3975
- userProfile: UserProfileSchema.optional().describe("User profile configuration"),
3976
- machineUserAttributes: z.undefined().optional()
3977
- }), AuthConfigBaseSchema.extend({
3978
- userProfile: z.undefined().optional(),
3979
- machineUserAttributes: z.record(z.string(), TailorFieldSchema).describe("Machine user attribute fields")
3980
- })], { error: (iss) => {
3981
- if (iss.code !== "invalid_union") return void 0;
3982
- if (iss.errors.length < 2) return void 0;
3983
- if (iss.errors.every((variantErrors) => variantErrors.every((e) => e.path.length === 1 && (e.path[0] === "userProfile" || e.path[0] === "machineUserAttributes")))) return "Specify either `userProfile` or `machineUserAttributes`, not both.";
3984
- } }).brand("AuthConfig");
3985
-
3986
3715
  //#endregion
3987
3716
  //#region src/cli/services/auth/service.ts
3988
3717
  /**
@@ -4014,7 +3743,7 @@ function createAuthService(config, tailorDBServices, externalTailorDBNamespaces)
4014
3743
  }
4015
3744
  const totalNamespaceCount = tailorDBServices.length + externalTailorDBNamespaces.length;
4016
3745
  let userProfileNamespace;
4017
- if (totalNamespaceCount === 1) userProfileNamespace = tailorDBServices[0]?.namespace ?? externalTailorDBNamespaces[0];
3746
+ if (totalNamespaceCount === 1) userProfileNamespace = tailorDBServices[0]?.namespace ?? assertDefined(externalTailorDBNamespaces[0], "external TailorDB namespace missing");
4018
3747
  else {
4019
3748
  await Promise.all(tailorDBServices.map((tailordb) => tailordb.loadTypes()));
4020
3749
  const userProfileTypeName = typeof config.userProfile.type === "object" && "name" in config.userProfile.type ? config.userProfile.type.name : void 0;
@@ -4143,109 +3872,6 @@ function buildResolverOperationHookExpr(env) {
4143
3872
  return `({ ...context.pipeline, input: context.args, user: ${tailorUserMap}, env: ${JSON.stringify(env)} });`;
4144
3873
  }
4145
3874
 
4146
- //#endregion
4147
- //#region src/parser/service/executor/schema.ts
4148
- const TailorDBTriggerSchema = z.object({
4149
- kind: z.literal("tailordb").describe("TailorDB record event trigger"),
4150
- events: z.array(z.enum([
4151
- "tailordb.type_record.created",
4152
- "tailordb.type_record.updated",
4153
- "tailordb.type_record.deleted"
4154
- ])).min(1).transform((arr) => [...new Set(arr)]).describe("TailorDB event types to trigger on"),
4155
- typeName: z.string().describe("TailorDB type name to watch for events"),
4156
- condition: functionSchema.optional().describe("Condition function to filter events")
4157
- });
4158
- const ResolverExecutedTriggerSchema = z.object({
4159
- kind: z.literal("resolverExecuted"),
4160
- resolverName: z.string().describe("Name of the resolver to trigger on"),
4161
- condition: functionSchema.optional().describe("Condition function to filter events")
4162
- });
4163
- const ScheduleTriggerSchema = z.object({
4164
- kind: z.literal("schedule"),
4165
- cron: z.string().describe("CRON expression for the schedule"),
4166
- timezone: z.string().optional().default("UTC").describe("Timezone for the CRON schedule (default: UTC)")
4167
- });
4168
- const IncomingWebhookTriggerResponseSchema = z.object({
4169
- body: functionSchema.optional().describe("Function returning the response body"),
4170
- statusCode: z.number().int().optional().describe("HTTP status code for the response")
4171
- });
4172
- const IncomingWebhookTriggerSchema = z.object({
4173
- kind: z.literal("incomingWebhook"),
4174
- response: IncomingWebhookTriggerResponseSchema.optional().describe("Response configuration")
4175
- });
4176
- const IdpUserTriggerSchema = z.object({
4177
- kind: z.literal("idpUser").describe("IdP user event trigger"),
4178
- events: z.array(z.enum([
4179
- "idp.user.created",
4180
- "idp.user.updated",
4181
- "idp.user.deleted"
4182
- ])).min(1).transform((arr) => [...new Set(arr)]).describe("IdP user event types to trigger on"),
4183
- idp: z.string().optional().describe("IdP namespace name to subscribe to. If omitted, the project's only IdP is used; throws when multiple IdPs exist.")
4184
- });
4185
- const AuthAccessTokenTriggerSchema = z.object({
4186
- kind: z.literal("authAccessToken").describe("Auth access token event trigger"),
4187
- events: z.array(z.enum([
4188
- "auth.access_token.issued",
4189
- "auth.access_token.refreshed",
4190
- "auth.access_token.revoked"
4191
- ])).min(1).transform((arr) => [...new Set(arr)]).describe("Auth access token event types to trigger on")
4192
- });
4193
- const TriggerSchema = z.discriminatedUnion("kind", [
4194
- TailorDBTriggerSchema,
4195
- ResolverExecutedTriggerSchema,
4196
- ScheduleTriggerSchema,
4197
- IncomingWebhookTriggerSchema,
4198
- IdpUserTriggerSchema,
4199
- AuthAccessTokenTriggerSchema
4200
- ]);
4201
- const FunctionOperationSchema = z.object({
4202
- kind: z.enum(["function", "jobFunction"]),
4203
- body: functionSchema.describe("Function implementation"),
4204
- authInvoker: AuthInvokerSchema.optional().describe("Auth invoker for the function execution")
4205
- });
4206
- const GqlOperationSchema = z.object({
4207
- kind: z.literal("graphql"),
4208
- appName: z.string().optional().describe("Target application name for the GraphQL query"),
4209
- query: z.preprocess((val) => String(val), z.string().describe("GraphQL query string")),
4210
- variables: functionSchema.optional().describe("Function to compute GraphQL variables"),
4211
- authInvoker: AuthInvokerSchema.optional().describe("Auth invoker for the GraphQL execution")
4212
- });
4213
- const WebhookOperationSchema = z.object({
4214
- kind: z.literal("webhook"),
4215
- url: functionSchema.describe("Function returning the webhook URL"),
4216
- requestBody: functionSchema.optional().describe("Function to compute the request body"),
4217
- headers: z.record(z.string(), z.union([z.string(), z.object({
4218
- vault: z.string(),
4219
- key: z.string()
4220
- })])).optional().describe("HTTP headers for the webhook request")
4221
- });
4222
- const WorkflowOperationSchema = z.preprocess((val) => {
4223
- if (val == null || typeof val !== "object" || !("workflow" in val) || typeof val.workflow !== "object" || val.workflow === null) return val;
4224
- const { workflow, ...rest } = val;
4225
- return {
4226
- ...rest,
4227
- workflowName: workflow.name
4228
- };
4229
- }, z.object({
4230
- kind: z.literal("workflow"),
4231
- workflowName: z.string().describe("Name of the workflow to execute"),
4232
- args: z.union([z.record(z.string(), z.unknown()), functionSchema]).optional().describe("Arguments to pass to the workflow"),
4233
- authInvoker: AuthInvokerSchema.optional().describe("Auth invoker for the workflow execution")
4234
- }));
4235
- const OperationSchema = z.union([
4236
- FunctionOperationSchema,
4237
- GqlOperationSchema,
4238
- WebhookOperationSchema,
4239
- WorkflowOperationSchema
4240
- ]);
4241
- const ExecutorSchema = z.object({
4242
- name: z.string().describe("Executor name"),
4243
- description: z.string().optional().describe("Executor description"),
4244
- disabled: z.boolean().optional().default(false).describe("Whether the executor is disabled"),
4245
- trigger: TriggerSchema.describe("Event trigger configuration"),
4246
- operation: OperationSchema.describe("Operation to execute when triggered")
4247
- });
4248
-
4249
3875
  //#endregion
4250
3876
  //#region src/cli/services/executor/loader.ts
4251
3877
  /**
@@ -4276,7 +3902,7 @@ async function bundleExecutors(options) {
4276
3902
  const { config, triggerContext, additionalFiles = [], cache, inlineSourcemap, bundleLogLevel = "DEBUG" } = options;
4277
3903
  const files = [...loadFilesWithIgnores(config), ...additionalFiles];
4278
3904
  if (files.length === 0) {
4279
- logger.warn(`No executor files found for patterns: ${config.files?.join(", ") ?? "(none)"}`);
3905
+ logger.warn(`No executor files found for patterns: ${config.files.join(", ")}`);
4280
3906
  return bundledCode;
4281
3907
  }
4282
3908
  logger.newline();
@@ -4365,71 +3991,6 @@ async function bundleSingleExecutor(executor, outputDir, tsconfig, triggerContex
4365
3991
  return [executor.name, code];
4366
3992
  }
4367
3993
 
4368
- //#endregion
4369
- //#region src/cli/services/executor/service.ts
4370
- /**
4371
- * Creates a new ExecutorService instance.
4372
- * @param params - Parameters for creating the service
4373
- * @returns A new ExecutorService instance
4374
- */
4375
- function createExecutorService(params) {
4376
- const { config } = params;
4377
- const executors = {};
4378
- const pluginExecutors = [];
4379
- let loadPromise;
4380
- const loadExecutorForFile = async (executorFile) => {
4381
- try {
4382
- const executorModule = await import(pathToFileURL(executorFile).href);
4383
- const result = ExecutorSchema.safeParse(executorModule.default);
4384
- if (result.success) {
4385
- const relativePath = path.relative(process.cwd(), executorFile);
4386
- logger.log(`Executor: ${styles.successBright(`"${result.data.name}"`)} loaded from ${styles.path(relativePath)}`);
4387
- executors[executorFile] = result.data;
4388
- return result.data;
4389
- }
4390
- if (isSdkBranded(executorModule.default, "executor")) throw result.error;
4391
- } catch (error) {
4392
- const relativePath = path.relative(process.cwd(), executorFile);
4393
- logger.error(`Failed to load executor from ${styles.bold(relativePath)}`);
4394
- logger.error(String(error));
4395
- throw error;
4396
- }
4397
- };
4398
- return {
4399
- config,
4400
- get executors() {
4401
- return executors;
4402
- },
4403
- get pluginExecutors() {
4404
- return pluginExecutors;
4405
- },
4406
- loadExecutors: async () => {
4407
- if (!loadPromise) loadPromise = (async () => {
4408
- if (!config.files || config.files.length === 0) return;
4409
- const executorFiles = loadFilesWithIgnores(config);
4410
- logger.newline();
4411
- logger.log(`Found ${styles.highlight(executorFiles.length.toString())} executor files`);
4412
- await Promise.all(executorFiles.map((executorFile) => loadExecutorForFile(executorFile)));
4413
- return executors;
4414
- })();
4415
- return loadPromise;
4416
- },
4417
- loadPluginExecutorFiles: async (filePaths) => {
4418
- if (filePaths.length === 0) return;
4419
- logger.newline();
4420
- logger.log(`Loading ${styles.highlight(filePaths.length.toString())} plugin-generated executor files`);
4421
- for (const filePath of filePaths) {
4422
- const executor = await loadExecutorForFile(filePath);
4423
- if (executor) pluginExecutors.push({
4424
- executor,
4425
- pluginId: "plugin-generated",
4426
- sourceTypeName: void 0
4427
- });
4428
- }
4429
- }
4430
- };
4431
- }
4432
-
4433
3994
  //#endregion
4434
3995
  //#region src/cli/services/http-adapter/node-builtins.ts
4435
3996
  const NODE_BUILTINS = new Set(builtinModules.filter((m) => !m.startsWith("_")));
@@ -4678,7 +4239,7 @@ function createHttpAdapterService(params) {
4678
4239
  };
4679
4240
  }
4680
4241
  async function loadAdapterFiles(config) {
4681
- if (!config.files || config.files.length === 0) return {
4242
+ if (config.files.length === 0) return {
4682
4243
  adapters: [],
4683
4244
  fileCount: 0
4684
4245
  };
@@ -4734,7 +4295,7 @@ function rejectAsyncHandlers(adapter, methods, sourceFile) {
4734
4295
  if (adapter.output !== void 0 && isAsyncFunction(adapter.output)) throw new Error(`HTTP adapter "${adapter.name}" in ${sourceFile} has an async \`output\` function. Handlers must be synchronous; async/await is not supported.`);
4735
4296
  }
4736
4297
  function isAsyncFunction(fn) {
4737
- return typeof fn === "function" && fn.constructor?.name === "AsyncFunction";
4298
+ return typeof fn === "function" && fn.constructor.name === "AsyncFunction";
4738
4299
  }
4739
4300
 
4740
4301
  //#endregion
@@ -4786,7 +4347,7 @@ async function bundleResolvers(namespace, config, triggerContext, cache, inlineS
4786
4347
  const bundledCode = /* @__PURE__ */ new Map();
4787
4348
  const files = loadFilesWithIgnores(config);
4788
4349
  if (files.length === 0) {
4789
- logger.warn(`No resolver files found for patterns: ${config.files?.join(", ") ?? "(none)"}`);
4350
+ logger.warn(`No resolver files found for patterns: ${config.files.join(", ")}`);
4790
4351
  return bundledCode;
4791
4352
  }
4792
4353
  logger.newline();
@@ -4919,7 +4480,7 @@ function createResolverService(namespace, config) {
4919
4480
  },
4920
4481
  loadResolvers: async () => {
4921
4482
  if (Object.keys(resolvers).length > 0) return;
4922
- if (!config.files || config.files.length === 0) return;
4483
+ if (config.files.length === 0) return;
4923
4484
  const resolverFiles = loadFilesWithIgnores(config);
4924
4485
  logger.log(`Found ${styles.highlight(resolverFiles.length.toString())} resolver files for service ${styles.highlight(`"${namespace}"`)}`);
4925
4486
  await Promise.all(resolverFiles.map((resolverFile) => loadResolverForFile(resolverFile)));
@@ -4942,7 +4503,7 @@ function findVariableDeclarationsByName(program) {
4942
4503
  const nodeType = node.type;
4943
4504
  if (nodeType === "VariableDeclaration") {
4944
4505
  const varDecl = node;
4945
- for (const decl of varDecl.declarations || []) if (decl.id?.type === "Identifier" && decl.id.name) {
4506
+ for (const decl of varDecl.declarations) if (decl.id.type === "Identifier" && decl.id.name) {
4946
4507
  if (!declarations.has(decl.id.name)) declarations.set(decl.id.name, {
4947
4508
  start: varDecl.start,
4948
4509
  end: varDecl.end
@@ -4954,7 +4515,7 @@ function findVariableDeclarationsByName(program) {
4954
4515
  const declaration = exportDecl.declaration;
4955
4516
  if (declaration?.type === "VariableDeclaration") {
4956
4517
  const varDecl = declaration;
4957
- for (const decl of varDecl.declarations || []) if (decl.id?.type === "Identifier" && decl.id.name) declarations.set(decl.id.name, {
4518
+ for (const decl of varDecl.declarations) if (decl.id.type === "Identifier" && decl.id.name) declarations.set(decl.id.name, {
4958
4519
  start: exportDecl.start,
4959
4520
  end: exportDecl.end
4960
4521
  });
@@ -5181,7 +4742,7 @@ async function filterUsedJobs(allJobs, mainJobNames) {
5181
4742
  const detectedJob = detectedJobs.find((d) => d.name === job.name);
5182
4743
  if (!detectedJob) continue;
5183
4744
  const jobDeps = /* @__PURE__ */ new Set();
5184
- for (const call of triggerCalls) if (detectedJob.bodyValueRange && call.callRange.start >= detectedJob.bodyValueRange.start && call.callRange.end <= detectedJob.bodyValueRange.end) {
4745
+ for (const call of triggerCalls) if (call.callRange.start >= detectedJob.bodyValueRange.start && call.callRange.end <= detectedJob.bodyValueRange.end) {
5185
4746
  const triggeredJobName = localExportNameToJobName.get(call.identifierName) || exportNameToJobName.get(call.identifierName);
5186
4747
  if (triggeredJobName) jobDeps.add(triggeredJobName);
5187
4748
  }
@@ -5306,7 +4867,10 @@ const unitToSeconds = {
5306
4867
  function durationToSeconds(duration) {
5307
4868
  const match = duration.match(/^(\d+)(ms|s|m)$/);
5308
4869
  if (!match) return 0;
5309
- return parseInt(match[1], 10) * unitToSeconds[match[2]];
4870
+ const value = match[1];
4871
+ const unit = match[2];
4872
+ if (value === void 0 || unit === void 0) return 0;
4873
+ return parseInt(value, 10) * unitToSeconds[unit];
5310
4874
  }
5311
4875
  const baseDurationSchema = z.templateLiteral([z.number().int().positive(), z.enum(durationUnits)]);
5312
4876
  const durationSchema = (maxSeconds) => baseDurationSchema.refine((val) => durationToSeconds(val) <= maxSeconds, { message: `Duration must be at most ${maxSeconds} seconds` });
@@ -5388,7 +4952,7 @@ async function loadAndCollectJobs(config) {
5388
4952
  const workflows = {};
5389
4953
  const workflowSources = [];
5390
4954
  const collectedJobs = [];
5391
- if (!config.files || config.files.length === 0) return {
4955
+ if (config.files.length === 0) return {
5392
4956
  workflows,
5393
4957
  workflowSources,
5394
4958
  jobs: collectedJobs,
@@ -5989,5 +5553,5 @@ async function loadApplication(params) {
5989
5553
  }
5990
5554
 
5991
5555
  //#endregion
5992
- export { loadConfigPath as A, getDistDir as C, deleteUserTokens as D, loadConfig as E, writePlatformConfig as F, readPlatformConfig as M, resolveTokens as N, fetchLatestToken as O, saveUserTokens as P, createBundleCache as S, hashFile as T, loadFilesWithIgnores as _, WorkflowJobSchema as a, createLogLevelTreeshakeOptions as b, createExecutorService as c, buildExecutorArgsExpr as d, buildResolverOperationHookExpr as f, stringifyFunction as g, TailorDBTypeSchema as h, resolveInlineSourcemap as i, loadWorkspaceId as j, loadAccessToken as k, ExecutorSchema as l, assertUniqueTailorDBTypeNamesWithExternal as m, generatePluginFilesIfNeeded as n, ResolverSchema as o, assertUniqueLocalTailorDBTypeNames as p, loadApplication as r, HTTP_METHODS as s, defineApplication as t, INVOKER_EXPR as u, platformBundleDefinePlugin as v, hashContent as w, resolveBundleLogLevel as x, composeFunctionTreeshakeOptions as y };
5993
- //# sourceMappingURL=application-pusdxz35.mjs.map
5556
+ export { resolveTokens as A, loadConfig as C, loadConfigPath as D, loadAccessToken as E, writePlatformConfig as M, loadWorkspaceId as O, hashFile as S, fetchLatestToken as T, createLogLevelTreeshakeOptions as _, WorkflowJobSchema as a, getDistDir as b, INVOKER_EXPR as c, assertUniqueLocalTailorDBTypeNames as d, assertUniqueTailorDBTypeNamesWithExternal as f, composeFunctionTreeshakeOptions as g, platformBundleDefinePlugin as h, resolveInlineSourcemap as i, saveUserTokens as j, readPlatformConfig as k, buildExecutorArgsExpr as l, stringifyFunction as m, generatePluginFilesIfNeeded as n, ResolverSchema as o, TailorDBTypeSchema as p, loadApplication as r, HTTP_METHODS as s, defineApplication as t, buildResolverOperationHookExpr as u, resolveBundleLogLevel as v, deleteUserTokens as w, hashContent as x, createBundleCache as y };
5557
+ //# sourceMappingURL=application-BezXGbrU.mjs.map