@uipath/function-tool 1.202.0-preview.156 → 1.202.0-preview.158

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.
@@ -1,40 +1,44 @@
1
1
  // ../../node_modules/@uipath/coded-functions-js-cli/dist/cliRunner.js
2
2
  import { createRequire } from "node:module";
3
3
  import { fileURLToPath as fileURLToPath3 } from "node:url";
4
- import { dirname as dirname5, join as join21 } from "node:path";
5
- import { readFileSync as readFileSync15 } from "node:fs";
4
+ import { dirname as dirname6, join as join22 } from "node:path";
5
+ import { readFileSync as readFileSync17 } from "node:fs";
6
6
  import { execSync } from "node:child_process";
7
7
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { homedir } from "node:os";
10
- import { spawnSync as spawnSync2 } from "node:child_process";
11
- import { existsSync as existsSync2, writeFileSync as writeFileSync3 } from "node:fs";
12
- import { join as join3, resolve } from "node:path";
10
+ import { existsSync as existsSync3, writeFileSync as writeFileSync4 } from "node:fs";
11
+ import { join as join4, resolve } from "node:path";
13
12
  import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
14
13
  import { join as join2 } from "node:path";
15
14
  import { spawnSync } from "node:child_process";
16
- import { existsSync as existsSync6, readFileSync as readFileSync5, writeFileSync as writeFileSync7 } from "node:fs";
17
- import { basename, join as join8, resolve as resolve3 } from "node:path";
15
+ import { copyFileSync, existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "node:fs";
16
+ import { basename, extname, isAbsolute, join as join3 } from "node:path";
17
+ import { existsSync as existsSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync8 } from "node:fs";
18
+ import { basename as basename3, join as join9, resolve as resolve3 } from "node:path";
18
19
  import { spawn } from "node:child_process";
19
- import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync3 } from "node:fs";
20
- import { extname, join as join4 } from "node:path";
21
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
22
- import { join as join5 } from "node:path";
20
+ import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync3 } from "node:fs";
21
+ import { extname as extname2, join as join5 } from "node:path";
22
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "node:fs";
23
+ import { join as join6 } from "node:path";
23
24
  import ts2 from "typescript";
24
25
  import { dirname, resolve as resolve2 } from "node:path";
25
26
  import ts from "typescript";
26
- import { copyFileSync, existsSync as existsSync4, lstatSync, mkdirSync as mkdirSync4, readFileSync as readFileSync3, readdirSync, symlinkSync, writeFileSync as writeFileSync5, cpSync } from "node:fs";
27
+ import { basename as basename2, dirname as dirname2 } from "node:path";
28
+ import ts3 from "typescript";
29
+ import { existsSync as existsSync5, lstatSync, mkdirSync as mkdirSync4, readFileSync as readFileSync4, readdirSync, symlinkSync, writeFileSync as writeFileSync6, cpSync } from "node:fs";
30
+ import { spawnSync as spawnSync2 } from "node:child_process";
27
31
  import { createRequire as createRequire2 } from "node:module";
28
- import { join as join6 } from "node:path";
29
- import { spawnSync as spawnSync3 } from "node:child_process";
32
+ import { join as join7 } from "node:path";
33
+ import { pathToFileURL } from "node:url";
30
34
  import { execSync as execSync2 } from "node:child_process";
31
- import { existsSync as existsSync5, readFileSync as readFileSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync6 } from "node:fs";
32
- import { extname as extname2, join as join7 } from "node:path";
33
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync8, readdirSync as readdirSync3, rmSync, statSync, writeFileSync as writeFileSync9 } from "node:fs";
34
- import { join as join12, resolve as resolve5 } from "node:path";
35
+ import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync as readdirSync2, writeFileSync as writeFileSync7 } from "node:fs";
36
+ import { extname as extname3, join as join8 } from "node:path";
37
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync9, readdirSync as readdirSync3, rmSync, statSync, writeFileSync as writeFileSync10 } from "node:fs";
38
+ import { join as join13, resolve as resolve5 } from "node:path";
35
39
  import { randomUUID } from "node:crypto";
36
40
  import { createRequire as createRequire3 } from "module";
37
- import { existsSync as existsSync7 } from "node:fs";
41
+ import { existsSync as existsSync8 } from "node:fs";
38
42
  import * as fs6 from "node:fs/promises";
39
43
  import * as os2 from "node:os";
40
44
  import * as path2 from "node:path";
@@ -67,35 +71,33 @@ import { execFile as execFile4, execFileSync } from "node:child_process";
67
71
  import { promisify as promisify5 } from "node:util";
68
72
  import { execFile as execFile5 } from "node:child_process";
69
73
  import process7 from "node:process";
70
- import { existsSync as existsSync9, readFileSync as readFileSync7 } from "node:fs";
71
- import { join as join11 } from "node:path";
72
- import ts3 from "typescript";
74
+ import { existsSync as existsSync10, readFileSync as readFileSync8 } from "node:fs";
75
+ import { join as join12 } from "node:path";
73
76
  import { createRequire as createRequire4 } from "node:module";
74
77
  import { register } from "node:module";
75
- import { existsSync as existsSync8, readFileSync as readFileSync6, writeFileSync as writeFileSync8 } from "node:fs";
76
- import { join as join10 } from "node:path";
77
- import { pathToFileURL } from "node:url";
78
- import { existsSync as existsSync10, readdirSync as readdirSync4, readFileSync as readFileSync9, statSync as statSync2 } from "node:fs";
78
+ import { existsSync as existsSync9, readFileSync as readFileSync7, writeFileSync as writeFileSync9 } from "node:fs";
79
+ import { join as join11 } from "node:path";
80
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
81
+ import { existsSync as existsSync11, readdirSync as readdirSync4, readFileSync as readFileSync10, statSync as statSync2 } from "node:fs";
79
82
  import { emitKeypressEvents } from "node:readline";
80
- import { join as join13, resolve as resolve6 } from "node:path";
81
- import { existsSync as existsSync13, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "node:fs";
82
- import { join as join16, resolve as resolve7 } from "node:path";
83
+ import { join as join14, resolve as resolve6 } from "node:path";
84
+ import { existsSync as existsSync14, readFileSync as readFileSync13, writeFileSync as writeFileSync12 } from "node:fs";
85
+ import { join as join17, resolve as resolve7 } from "node:path";
83
86
  import { createHash } from "node:crypto";
84
- import { existsSync as existsSync12, readFileSync as readFileSync11, readdirSync as readdirSync5, statSync as statSync3 } from "node:fs";
85
- import { join as join15, relative as relative2 } from "node:path";
86
- import { existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync10, writeFileSync as writeFileSync10 } from "node:fs";
87
- import { dirname as dirname3, join as join14 } from "node:path";
88
- import { existsSync as existsSync15, mkdirSync as mkdirSync8, renameSync, writeFileSync as writeFileSync13 } from "node:fs";
89
- import { join as join18, resolve as resolve9 } from "node:path";
87
+ import { existsSync as existsSync13, readFileSync as readFileSync12, readdirSync as readdirSync5, statSync as statSync3 } from "node:fs";
88
+ import { join as join16, relative as relative2 } from "node:path";
89
+ import { existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync11, writeFileSync as writeFileSync11 } from "node:fs";
90
+ import { dirname as dirname4, join as join15 } from "node:path";
91
+ import { existsSync as existsSync16, mkdirSync as mkdirSync8, readFileSync as readFileSync15, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync14 } from "node:fs";
92
+ import { join as join19, resolve as resolve9 } from "node:path";
90
93
  import { spawn as spawn2 } from "node:child_process";
91
- import { existsSync as existsSync14, mkdirSync as mkdirSync7, readFileSync as readFileSync13, writeFileSync as writeFileSync12 } from "node:fs";
92
- import { isAbsolute as isAbsolute2, join as join17, relative as relative3, resolve as resolve8 } from "node:path";
93
- import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync14 } from "node:fs";
94
- import { join as join19, resolve as resolve10 } from "node:path";
95
- import { spawnSync as spawnSync4 } from "node:child_process";
94
+ import { existsSync as existsSync15, mkdirSync as mkdirSync7, readFileSync as readFileSync14, writeFileSync as writeFileSync13 } from "node:fs";
95
+ import { isAbsolute as isAbsolute3, join as join18, relative as relative3, resolve as resolve8 } from "node:path";
96
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync15 } from "node:fs";
97
+ import { join as join20, resolve as resolve10 } from "node:path";
96
98
  import { resolve as resolve11 } from "node:path";
97
- import { existsSync as existsSync16, mkdirSync as mkdirSync10, readFileSync as readFileSync14, readdirSync as readdirSync6, writeFileSync as writeFileSync15 } from "node:fs";
98
- import { dirname as dirname4, join as join20, resolve as resolve12 } from "node:path";
99
+ import { existsSync as existsSync17, mkdirSync as mkdirSync10, readFileSync as readFileSync16, readdirSync as readdirSync6, writeFileSync as writeFileSync16 } from "node:fs";
100
+ import { dirname as dirname5, join as join21, resolve as resolve12 } from "node:path";
99
101
  import { fileURLToPath as fileURLToPath2 } from "node:url";
100
102
  import { spawn as spawn3 } from "node:child_process";
101
103
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -1971,7 +1973,8 @@ var {
1971
1973
  Option,
1972
1974
  Help
1973
1975
  } = import__.default;
1974
- var CACHE_FILE = join(homedir(), ".uipcli", "functions-cache.json");
1976
+ var CACHE_DIR = join(homedir(), ".uipath");
1977
+ var CACHE_FILE = join(CACHE_DIR, "functions-runtime-cache.json");
1975
1978
  function registerSetupCommand(program2) {
1976
1979
  program2.command("setup", { hidden: true }).description("Verify and cache Node.js (and optionally Deno) for JS Functions development.").option("--runtime <runtime>", "Runtime to set up: node, deno, or both", "node").action((opts) => {
1977
1980
  const runtimes = opts.runtime === "both" ? ["node", "deno"] : [opts.runtime];
@@ -2013,13 +2016,6 @@ function setupNode(cache) {
2013
2016
  }).trim();
2014
2017
  cache.node = { path: path3, version };
2015
2018
  console.log(`Node.js ${version} ✓`);
2016
- try {
2017
- execSync("npx --yes tsx --version", { encoding: "utf-8", stdio: "pipe" });
2018
- console.log("tsx ✓");
2019
- } catch {
2020
- console.log("tsx not found — installing globally...");
2021
- execSync("npm install -g tsx", { stdio: "inherit" });
2022
- }
2023
2019
  } catch {
2024
2020
  console.error("Node.js not found. Install from https://nodejs.org (v20+).");
2025
2021
  process.exit(1);
@@ -2050,103 +2046,25 @@ function readCache() {
2050
2046
  return {};
2051
2047
  }
2052
2048
  function writeCache(cache) {
2053
- mkdirSync(join(homedir(), ".uipcli"), { recursive: true });
2049
+ mkdirSync(CACHE_DIR, { recursive: true });
2054
2050
  writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2), "utf-8");
2055
2051
  }
2056
- var SERVER_RUNNER_DIR = ".uipath/server-runner";
2057
- var DESIGN_TIME_ENV = "DESIGN_TIME";
2058
- var SDK_VERSION = "^0.6.0";
2059
- var RUNTIME_VERSION = "^0.8.0";
2060
- var HONO_NODE_VERSION = "^1.0.0";
2061
- var TSX_VERSION = "^4.0.0";
2062
- var COREIPC_VERSION = "2.5.1-20260324-07";
2063
- var SIGNALR_VERSION = "8.0.7";
2064
- var TRACE_MAPPING_VERSION = "0.3.25";
2065
- var NPM_RC = `@uipath:registry=https://npm.pkg.github.com
2066
- //npm.pkg.github.com/:_authToken=\${GITHUB_TOKEN}`;
2067
- function scaffoldProject(opts) {
2068
- const { projectDir, name, lang, functions } = opts;
2069
- mkdirSync2(projectDir, { recursive: true });
2070
- mkdirSync2(join2(projectDir, "functions"), { recursive: true });
2071
- writeFileSync2(join2(projectDir, "uipath.json"), JSON.stringify({
2072
- $schema: "https://cloud.uipath.com/draft/2024-12/uipath",
2073
- packOptions: {
2074
- fileExtensionsIncluded: [],
2075
- filesIncluded: [],
2076
- filesExcluded: [],
2077
- directoriesExcluded: [],
2078
- includeLockFile: true
2079
- },
2080
- functions
2081
- }, null, 2) + `
2082
- `, "utf-8");
2083
- writeFileSync2(join2(projectDir, "package.json"), JSON.stringify({
2084
- name,
2085
- version: "1.0.0",
2086
- type: "module",
2087
- devDependencies: {
2088
- "@uipath/coded-functions-js-sdk": SDK_VERSION,
2089
- ...lang === "ts" ? { typescript: "^5.7.0" } : {}
2090
- }
2091
- }, null, 2) + `
2092
- `, "utf-8");
2093
- if (lang === "ts") {
2094
- writeFileSync2(join2(projectDir, "tsconfig.json"), JSON.stringify({
2095
- compilerOptions: {
2096
- target: "ESNext",
2097
- module: "ESNext",
2098
- moduleResolution: "bundler",
2099
- strict: true,
2100
- allowImportingTsExtensions: true,
2101
- noEmit: true
2102
- },
2103
- include: ["**/*.ts"],
2104
- exclude: ["node_modules", "dist"]
2105
- }, null, 2) + `
2106
- `, "utf-8");
2107
- }
2108
- writeFileSync2(join2(projectDir, ".env.example"), [
2109
- "UIPATH_URL=",
2110
- "UIPATH_ORGANIZATION_NAME=",
2111
- "UIPATH_TENANT_NAME=",
2112
- "UIPATH_ACCESS_TOKEN=",
2113
- "",
2114
- "# push: Studio Web project ID (create the project in Studio Web to get this)",
2115
- "UIPATH_PROJECT_ID="
2116
- ].join(`
2117
- `) + `
2118
- `, "utf-8");
2119
- writeFileSync2(join2(projectDir, ".gitignore"), `node_modules/
2120
- dist/
2121
- .env
2122
- *.nupkg
2123
- .uipath/
2124
- `, "utf-8");
2125
- }
2126
- var bunAvailableCache;
2127
- function hasBun() {
2128
- if (bunAvailableCache !== undefined)
2129
- return bunAvailableCache;
2130
- const result = spawnSync("bun", ["--version"], {
2131
- stdio: "ignore",
2132
- shell: process.platform === "win32"
2133
- });
2134
- bunAvailableCache = result.status === 0;
2135
- return bunAvailableCache;
2136
- }
2137
- function getInstallCommand(onlyProd, extraArgs = []) {
2138
- if (hasBun()) {
2139
- if (onlyProd) {
2140
- return { cmd: "bun", args: ["install", "--production", ...extraArgs] };
2141
- }
2142
- return { cmd: "bun", args: ["install", ...extraArgs] };
2143
- }
2144
- if (onlyProd) {
2145
- return { cmd: "npm", args: ["install", "--omit=dev", ...extraArgs] };
2146
- }
2147
- return { cmd: "npm", args: ["install", ...extraArgs] };
2148
- }
2149
- var HELLO_TS = `import { defineFunction, defineSchema } from "@uipath/coded-functions-js-sdk";
2052
+ var SDK_VERSION = "0.6.2";
2053
+ var SDK_RANGE = `^${SDK_VERSION}`;
2054
+ var SDK_PACKAGE_NAME = "@uipath/coded-functions-js-sdk";
2055
+ var TYPESCRIPT_RANGE = "^5.7.0";
2056
+ var SAMPLE_FUNCTION = {
2057
+ name: "hello",
2058
+ description: "Returns a greeting message.",
2059
+ method: "POST",
2060
+ path: "/hello",
2061
+ entryExport: "default"
2062
+ };
2063
+ var httpSemantics = ` method: "${SAMPLE_FUNCTION.method}",
2064
+ path: "${SAMPLE_FUNCTION.path}",
2065
+ `;
2066
+ var semanticsFor = (variant) => variant === "http" ? httpSemantics : "";
2067
+ var buildHelloTs = (variant) => `import { defineFunction, defineSchema, type FunctionContext } from "@uipath/coded-functions-js-sdk";
2150
2068
 
2151
2069
  interface HelloInput {
2152
2070
  /**
@@ -2160,27 +2078,28 @@ interface HelloOutput {
2160
2078
  message: string;
2161
2079
  }
2162
2080
 
2081
+ function main(input: HelloInput, ctx: FunctionContext): HelloOutput {
2082
+ const output: HelloOutput = {
2083
+ message: \`Hello, \${input.name}!\`,
2084
+ };
2085
+ return output;
2086
+ }
2087
+
2163
2088
  export default defineFunction({
2164
- name: "hello",
2165
- description: "Returns a greeting message.",
2166
- method: "POST",
2167
- path: "/hello",
2168
- input: defineSchema<HelloInput>(),
2089
+ name: "${SAMPLE_FUNCTION.name}",
2090
+ description: "${SAMPLE_FUNCTION.description}",
2091
+ ${semanticsFor(variant)} input: defineSchema<HelloInput>(),
2169
2092
  output: defineSchema<HelloOutput>(),
2170
- handler: async (input, ctx) => ({
2171
- message: \`Hello, \${input.name}!\`,
2172
- }),
2093
+ handler: main,
2173
2094
  });
2174
2095
  `;
2175
- var HELLO_JS = `// @ts-check
2096
+ var buildHelloJs = (variant) => `// @ts-check
2176
2097
  import { defineFunction } from "@uipath/coded-functions-js-sdk";
2177
2098
 
2178
2099
  export default defineFunction({
2179
- name: "hello",
2180
- description: "Returns a greeting message.",
2181
- method: "POST",
2182
- path: "/hello",
2183
- input: {
2100
+ name: "${SAMPLE_FUNCTION.name}",
2101
+ description: "${SAMPLE_FUNCTION.description}",
2102
+ ${semanticsFor(variant)} input: {
2184
2103
  type: "object",
2185
2104
  properties: {
2186
2105
  name: { type: "string", default: "World" },
@@ -2200,141 +2119,682 @@ export default defineFunction({
2200
2119
  }),
2201
2120
  });
2202
2121
  `;
2203
- function registerNewCommand(program2) {
2204
- program2.command("new [name]").description("Scaffold a new JS/TS Functions project. Includes a hello world function by default; pass --empty to skip it.").option("--name <name>", "Project name / directory (alias for positional arg)").option("-l, --language <lang>", "Language: ts (default) or js", "ts").option("--empty", "Skip the hello world function — create an empty project").action((nameArg, opts) => {
2205
- const projectName = opts.name ?? nameArg ?? "my-functions";
2206
- const lang = opts.language === "js" ? "js" : "ts";
2207
- const projectDir = resolve(projectName);
2208
- if (existsSync2(projectDir)) {
2209
- console.error(`Directory already exists: ${projectDir}`);
2210
- process.exit(1);
2211
- }
2212
- ensureSetup();
2213
- const withSample = !opts.empty;
2214
- scaffoldProject({
2215
- projectDir,
2216
- name: projectName,
2217
- type: "module",
2218
- lang,
2219
- functions: withSample ? { hello: `functions/hello.${lang}:default` } : {}
2220
- });
2221
- if (withSample) {
2222
- writeFileSync3(join3(projectDir, "functions", `hello.${lang}`), lang === "ts" ? HELLO_TS : HELLO_JS, "utf-8");
2223
- }
2224
- if (process.env["GITHUB_TOKEN"]) {
2225
- writeFileSync3(join3(projectDir, ".npmrc"), NPM_RC, "utf-8");
2226
- }
2227
- console.log(`
2228
- Created ${projectName}/`);
2229
- console.log("Installing dependencies...");
2230
- const { cmd, args } = getInstallCommand(false);
2231
- const installResult = spawnSync2(cmd, args, {
2232
- cwd: projectDir,
2233
- stdio: "inherit",
2234
- shell: process.platform === "win32"
2235
- });
2236
- if (installResult.status !== 0) {
2237
- console.error(`${cmd} install failed in ${projectDir}.`);
2238
- process.exit(1);
2239
- }
2240
- console.log(`
2241
- Ready. Next steps:`);
2242
- console.log(` cd ${projectName}`);
2243
- if (withSample) {
2244
- console.log(` uip functions serve`);
2245
- } else {
2246
- console.log(` # Add your function entry points to ${projectName}/functions/`);
2247
- console.log(` uip functions serve`);
2248
- }
2249
- });
2250
- }
2251
- function generateAggregator(functionsMap, cwd, variant, derivedByPath = {}) {
2252
- const lang = detectLanguage(functionsMap);
2253
- const ext = lang === "javascript" ? "js" : "ts";
2254
- const fileToFunctions = new Map;
2255
- for (const [name, entry] of Object.entries(functionsMap)) {
2256
- const file = entry.split(":")[0];
2257
- const existing = fileToFunctions.get(file);
2258
- if (existing) {
2259
- existing.push(name);
2260
- } else {
2261
- fileToFunctions.set(file, [name]);
2122
+ var HELLO_TS = buildHelloTs("http");
2123
+ var HELLO_TS_JOB = buildHelloTs("job");
2124
+ var HELLO_JS = buildHelloJs("http");
2125
+ var HELLO_JS_JOB = buildHelloJs("job");
2126
+ var sanitizeNpmPackageName = (projectName) => projectName.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-._]/g, "").replace(/^[-._]+/, "") || "function-project";
2127
+ var sampleDevDependencies = (language) => ({
2128
+ [SDK_PACKAGE_NAME]: SDK_RANGE,
2129
+ ...language === "ts" ? { typescript: TYPESCRIPT_RANGE } : {}
2130
+ });
2131
+ var getSamplePackageJson = (projectName, language) => JSON.stringify({
2132
+ name: sanitizeNpmPackageName(projectName),
2133
+ version: "1.0.0",
2134
+ type: "module",
2135
+ devDependencies: sampleDevDependencies(language)
2136
+ }, null, 2) + `
2137
+ `;
2138
+ var SAMPLE_TSCONFIG = JSON.stringify({
2139
+ compilerOptions: {
2140
+ target: "ESNext",
2141
+ module: "ESNext",
2142
+ moduleResolution: "bundler",
2143
+ strict: true,
2144
+ allowImportingTsExtensions: true,
2145
+ noEmit: true
2146
+ },
2147
+ include: ["**/*.ts"],
2148
+ exclude: ["node_modules", "dist"]
2149
+ }, null, 2) + `
2150
+ `;
2151
+ var SAMPLE_LOCK_PACKAGES = {
2152
+ "node_modules/@babel/runtime": {
2153
+ version: "7.29.7",
2154
+ resolved: "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
2155
+ integrity: "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
2156
+ dev: true,
2157
+ license: "MIT",
2158
+ engines: { node: ">=6.9.0" }
2159
+ },
2160
+ "node_modules/@standard-schema/spec": {
2161
+ version: "1.1.0",
2162
+ resolved: "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
2163
+ integrity: "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
2164
+ dev: true,
2165
+ license: "MIT"
2166
+ },
2167
+ [`node_modules/${SDK_PACKAGE_NAME}`]: {
2168
+ version: SDK_VERSION,
2169
+ dev: true,
2170
+ dependencies: {
2171
+ "@standard-schema/spec": "^1.1.0",
2172
+ "json-schema-to-ts": "^3.1.1"
2262
2173
  }
2174
+ },
2175
+ "node_modules/json-schema-to-ts": {
2176
+ version: "3.1.1",
2177
+ resolved: "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
2178
+ integrity: "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
2179
+ dev: true,
2180
+ license: "MIT",
2181
+ dependencies: {
2182
+ "@babel/runtime": "^7.18.3",
2183
+ "ts-algebra": "^2.0.0"
2184
+ },
2185
+ engines: { node: ">=16" }
2186
+ },
2187
+ "node_modules/ts-algebra": {
2188
+ version: "2.0.0",
2189
+ resolved: "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
2190
+ integrity: "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
2191
+ dev: true,
2192
+ license: "MIT"
2193
+ },
2194
+ "node_modules/typescript": {
2195
+ version: "5.9.3",
2196
+ resolved: "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
2197
+ integrity: "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
2198
+ dev: true,
2199
+ license: "Apache-2.0",
2200
+ bin: { tsc: "bin/tsc", tsserver: "bin/tsserver" },
2201
+ engines: { node: ">=14.17" }
2263
2202
  }
2264
- for (const [file, names] of fileToFunctions) {
2265
- if (names.length > 1) {
2266
- throw new Error(`Multiple function definitions in the same file are not allowed.
2267
- ` + `File "${file}" is used by: ${names.join(", ")}.
2268
- ` + `Each function must be defined in its own file.`);
2269
- }
2203
+ };
2204
+ function scaffoldProject(opts) {
2205
+ const { projectDir, name, lang, functions } = opts;
2206
+ mkdirSync2(projectDir, { recursive: true });
2207
+ mkdirSync2(join2(projectDir, "functions"), { recursive: true });
2208
+ writeFileSync2(join2(projectDir, "uipath.json"), JSON.stringify({
2209
+ $schema: "https://cloud.uipath.com/draft/2024-12/uipath",
2210
+ packOptions: {
2211
+ fileExtensionsIncluded: [],
2212
+ filesIncluded: [],
2213
+ filesExcluded: [],
2214
+ directoriesExcluded: []
2215
+ },
2216
+ functions
2217
+ }, null, 2) + `
2218
+ `, "utf-8");
2219
+ writeFileSync2(join2(projectDir, "package.json"), getSamplePackageJson(name, lang), "utf-8");
2220
+ if (lang === "ts") {
2221
+ writeFileSync2(join2(projectDir, "tsconfig.json"), SAMPLE_TSCONFIG, "utf-8");
2270
2222
  }
2271
- const files = [...fileToFunctions.keys()];
2272
- let outputFile;
2273
- let importPrefix;
2274
- if (variant === "serve") {
2275
- const dbgDir = join4(cwd, SERVER_RUNNER_DIR);
2276
- mkdirSync3(dbgDir, { recursive: true });
2277
- outputFile = join4(dbgDir, `function-main.${ext}`);
2278
- importPrefix = "../../";
2279
- } else {
2280
- outputFile = join4(cwd, `function-main.${ext}`);
2281
- importPrefix = "./";
2223
+ writeFileSync2(join2(projectDir, ".env.example"), [
2224
+ "UIPATH_URL=",
2225
+ "UIPATH_ORGANIZATION_NAME=",
2226
+ "UIPATH_TENANT_NAME=",
2227
+ "UIPATH_ACCESS_TOKEN=",
2228
+ "",
2229
+ "# push: Studio Web project ID (create the project in Studio Web to get this)",
2230
+ "UIPATH_PROJECT_ID="
2231
+ ].join(`
2232
+ `) + `
2233
+ `, "utf-8");
2234
+ writeFileSync2(join2(projectDir, ".gitignore"), `node_modules/
2235
+ dist/
2236
+ .env
2237
+ *.nupkg
2238
+ .uipath/
2239
+ `, "utf-8");
2240
+ }
2241
+ var npm = { name: "npm", lockFile: "package-lock.json", installHint: "npm install" };
2242
+ var bun = { name: "bun", lockFile: "bun.lock", installHint: "bun install" };
2243
+ var SUPPORTED_MANAGERS = [npm, bun];
2244
+ var RECOGNIZED_UNSUPPORTED_LOCK_FILES = ["yarn.lock", "pnpm-lock.yaml", "bun.lockb"];
2245
+ function detectPackageManager(present) {
2246
+ const supported = SUPPORTED_MANAGERS.filter((manager) => present.has(manager.lockFile));
2247
+ if (supported.length > 1)
2248
+ return { kind: "ambiguous", managers: supported };
2249
+ if (supported.length === 1)
2250
+ return { kind: "found", manager: supported[0] };
2251
+ const unsupported = RECOGNIZED_UNSUPPORTED_LOCK_FILES.filter((name) => present.has(name));
2252
+ return unsupported.length > 0 ? { kind: "unsupported", fileNames: unsupported } : { kind: "none" };
2253
+ }
2254
+ var CANDIDATE_LOCK_FILES = [
2255
+ ...SUPPORTED_MANAGERS.map((manager) => manager.lockFile),
2256
+ ...RECOGNIZED_UNSUPPORTED_LOCK_FILES
2257
+ ];
2258
+ async function probeLockFiles(reader) {
2259
+ const present = new Set;
2260
+ for (const fileName of CANDIDATE_LOCK_FILES) {
2261
+ if (await reader.fileExists(fileName))
2262
+ present.add(fileName);
2282
2263
  }
2283
- const imports = files.map((file, i) => `import f${i} from "${importPrefix}${file}";`).join(`
2284
- `);
2285
- const relevantDerived = {};
2286
- for (const file of files) {
2287
- const d = derivedByPath[file];
2288
- if (!d)
2289
- continue;
2290
- const entry = {};
2291
- if (d.input !== undefined)
2292
- entry.input = d.input;
2293
- if (d.output !== undefined)
2294
- entry.output = d.output;
2295
- if (entry.input !== undefined || entry.output !== undefined)
2296
- relevantDerived[file] = entry;
2264
+ return present;
2265
+ }
2266
+ function supportedLockFilesLabel() {
2267
+ return SUPPORTED_MANAGERS.map((manager) => `${manager.lockFile} (${manager.name})`).join(" or ");
2268
+ }
2269
+ function describeDependencyProblem(detection) {
2270
+ const defaultHint = SUPPORTED_MANAGERS[0].installHint;
2271
+ switch (detection.kind) {
2272
+ case "none":
2273
+ return {
2274
+ problem: `No dependency lock file found; expected ${supportedLockFilesLabel()}.`,
2275
+ remedyCommand: defaultHint
2276
+ };
2277
+ case "unsupported": {
2278
+ const names = detection.fileNames.join(" and ");
2279
+ return {
2280
+ problem: `Found ${names}, which cannot be installed from; expected ${supportedLockFilesLabel()}. ` + `Create a supported lock file, then delete ${names}.`,
2281
+ remedyCommand: defaultHint
2282
+ };
2283
+ }
2284
+ case "ambiguous":
2285
+ return {
2286
+ problem: `Found ${detection.managers.map((manager) => manager.lockFile).join(" and ")}. Keep exactly one: ` + `with two lock files the installer that runs on the pod picks one and the other's resolution ` + `is silently ignored.`,
2287
+ remedyCommand: null
2288
+ };
2297
2289
  }
2298
- const hasDerived = Object.keys(relevantDerived).length > 0;
2299
- const entries = files.map((file, i) => {
2300
- const def = hasDerived ? `__lower(f${i}, "${file}")` : `f${i}`;
2301
- return `{ functionDef: ${def}, functionPath: "${file}" }`;
2302
- }).join(", ");
2303
- const header = lang === "javascript" ? `// @ts-check
2304
- ` : "";
2305
- const loweringBlock = hasDerived ? `const __derived = ${JSON.stringify(relevantDerived, null, 2)};
2306
- ` + `function __lower(def, path) {
2307
- ` + ` const d = __derived[path];
2308
- ` + ` if (!d) return def;
2309
- ` + ` const out = { ...def };
2310
- ` + ` if (d.input !== undefined) out.input = d.input;
2311
- ` + ` if (d.output !== undefined) out.output = d.output;
2312
- ` + ` return out;
2313
- ` + `}
2314
-
2315
- ` : "";
2316
- const content = `${header}` + `// Generated by uipath-functions — do not edit
2317
- ` + `import { createApp } from "@uipath/coded-functions-js-runtime";
2318
- ` + `${imports}
2319
-
2320
- ` + `${loweringBlock}` + `export default createApp([${entries}]);
2321
- `;
2322
- writeFileSync4(outputFile, content, "utf-8");
2323
- return outputFile;
2324
2290
  }
2325
- function detectLanguage(functionsMap) {
2326
- const first = Object.values(functionsMap)[0]?.split(":")[0] ?? "";
2327
- return extname(first) === ".js" ? "javascript" : "typescript";
2291
+ var REGISTRY_CONFIG_FILE = ".npmrc";
2292
+ function isRegistryConfigFile(fileName) {
2293
+ return fileName === REGISTRY_CONFIG_FILE;
2328
2294
  }
2329
- var SegmentTier = {
2330
- Literal: 0,
2331
- RegexParam: 1,
2332
- RequiredParam: 2,
2333
- OptionalParam: 3,
2334
- Wildcard: 4
2335
- };
2336
- function trimSlashes(slug) {
2337
- return slug.replace(/^\/+|\/+$/g, "");
2295
+ var CREDENTIAL_KEYS = ["_authtoken", "_auth", "_password"];
2296
+ function isComment(line) {
2297
+ return line === "" || line.startsWith("#") || line.startsWith(";");
2298
+ }
2299
+ function settingKey(line) {
2300
+ const trimmed = line.trim();
2301
+ if (isComment(trimmed))
2302
+ return null;
2303
+ return (trimmed.split("=")[0] ?? "").trim().toLowerCase();
2304
+ }
2305
+ function sanitizeRegistryConfig(content, stripScopes) {
2306
+ const stripped = stripScopes.map((scope) => `${scope.replace(/:$/, "")}:`.toLowerCase());
2307
+ const kept = content.split(/\r?\n/).filter((line) => {
2308
+ const key = settingKey(line);
2309
+ if (key === null)
2310
+ return true;
2311
+ if (stripped.some((scope) => key.startsWith(scope)))
2312
+ return false;
2313
+ return !CREDENTIAL_KEYS.some((credential) => key.endsWith(credential));
2314
+ });
2315
+ return kept.some((line) => !isComment(line.trim())) ? kept.join(`
2316
+ `) : null;
2317
+ }
2318
+ function ifsProjectFileReader(fs7, projectPath) {
2319
+ return {
2320
+ async fileExists(fileName) {
2321
+ try {
2322
+ return await fs7.exists(fs7.path.join(projectPath, fileName));
2323
+ } catch {
2324
+ return false;
2325
+ }
2326
+ },
2327
+ async readFile(fileName) {
2328
+ const content = await fs7.readFile(fs7.path.join(projectPath, fileName), "utf-8");
2329
+ if (content === null)
2330
+ throw new Error(`${fileName} not found in ${projectPath}.`);
2331
+ return content;
2332
+ }
2333
+ };
2334
+ }
2335
+ var EXCLUDED_NAMES = new Set([
2336
+ "node_modules",
2337
+ ".git",
2338
+ ".env",
2339
+ ".deno",
2340
+ "dist",
2341
+ ".uipath"
2342
+ ]);
2343
+ var EXCLUDED_EXTENSIONS = [".nupkg"];
2344
+ var SCOPES_NOT_PACKAGED = ["@uipath"];
2345
+ async function buildFunctionsPackage(fs7, options) {
2346
+ const { projectPath, outputPath, projectStorageId } = options;
2347
+ const contentPath = fs7.path.join(outputPath, "content");
2348
+ await fs7.mkdir(outputPath);
2349
+ await fs7.mkdir(contentPath);
2350
+ const uipathJsonRaw = await fs7.readFile(fs7.path.join(projectPath, "uipath.json"), "utf-8");
2351
+ if (!uipathJsonRaw) {
2352
+ throw new Error("uipath.json not found. Run 'uipath-functions init' first.");
2353
+ }
2354
+ const uipathJson = JSON.parse(uipathJsonRaw);
2355
+ const entryPointsRaw = await fs7.readFile(fs7.path.join(projectPath, "entry-points.json"), "utf-8");
2356
+ if (!entryPointsRaw) {
2357
+ throw new Error("entry-points.json not found. Run 'uipath-functions pack' to generate it.");
2358
+ }
2359
+ const entryPoints = JSON.parse(entryPointsRaw);
2360
+ const bindingsRaw = await fs7.readFile(fs7.path.join(projectPath, "bindings_v2.json"), "utf-8");
2361
+ if (!bindingsRaw) {
2362
+ throw new Error("bindings_v2.json not found. Run 'uipath-functions pack' to generate it.");
2363
+ }
2364
+ const bindings = JSON.parse(bindingsRaw);
2365
+ const packageJsonRaw = await fs7.readFile(fs7.path.join(projectPath, "package.json"), "utf-8");
2366
+ const packageDependencies = packageJsonRaw ? JSON.parse(packageJsonRaw).dependencies ?? {} : {};
2367
+ const targetRuntime = detectRuntime(uipathJson.functions);
2368
+ const detection = detectPackageManager(await probeLockFiles(ifsProjectFileReader(fs7, projectPath)));
2369
+ if (detection.kind !== "found") {
2370
+ const { problem, remedyCommand } = describeDependencyProblem(detection);
2371
+ throw new Error(remedyCommand !== null ? `${problem} Run '${remedyCommand}' in the project, then pack again.` : `${problem} Then pack again.`);
2372
+ }
2373
+ const lockFile = detection.manager.lockFile;
2374
+ if (uipathJson.packOptions?.includeLockFile === false) {
2375
+ console.warn(`uipath.json packOptions.includeLockFile is ignored: ${lockFile} is always packaged.`);
2376
+ }
2377
+ await copyProjectFiles(fs7, projectPath, contentPath, lockFile, uipathJson.packOptions);
2378
+ const operateJson = {
2379
+ $schema: "https://cloud.uipath.com/draft/2024-12/operate",
2380
+ projectId: projectStorageId,
2381
+ contentType: "function",
2382
+ targetFramework: "Portable",
2383
+ targetRuntime,
2384
+ runtimeOptions: {
2385
+ requiresUserInteraction: false,
2386
+ isAttended: false
2387
+ },
2388
+ deploymentOptions: {
2389
+ generateSlug: true
2390
+ },
2391
+ dependencies: packageDependencies
2392
+ };
2393
+ await fs7.writeFile(fs7.path.join(contentPath, "operate.json"), JSON.stringify(operateJson, null, 2));
2394
+ await fs7.writeFile(fs7.path.join(contentPath, "entry-points.json"), JSON.stringify(entryPoints, null, 2));
2395
+ await fs7.writeFile(fs7.path.join(contentPath, "bindings_v2.json"), JSON.stringify(bindings, null, 2));
2396
+ const packageDescriptor = {
2397
+ $schema: "https://cloud.uipath.com/draft/2024-12/package-descriptor",
2398
+ files: {
2399
+ "operate.json": "content/operate.json",
2400
+ "entry-points.json": "content/entry-points.json",
2401
+ "bindings.json": "content/bindings_v2.json"
2402
+ }
2403
+ };
2404
+ for (const ep of entryPoints.entryPoints) {
2405
+ const fnEntry = uipathJson.functions?.[ep.filePath];
2406
+ const filePath = fnEntry ? fnEntry.split(":")[0] ?? ep.filePath : ep.filePath;
2407
+ packageDescriptor.files[ep.filePath] = `${filePath}`;
2408
+ }
2409
+ await fs7.writeFile(fs7.path.join(contentPath, "package-descriptor.json"), JSON.stringify(packageDescriptor, null, 2));
2410
+ }
2411
+ function detectRuntime(functions) {
2412
+ if (!functions)
2413
+ return "javascript";
2414
+ const first = Object.values(functions)[0];
2415
+ if (!first)
2416
+ return "javascript";
2417
+ const filePath = first.split(":")[0] ?? "";
2418
+ const ext = filePath.slice(filePath.lastIndexOf("."));
2419
+ if (ext === ".py")
2420
+ return "python";
2421
+ return "javascript";
2422
+ }
2423
+ async function copyProjectFiles(fs7, sourcePath, destPath, lockFile, packOptions) {
2424
+ const extraExcludedDirs = new Set(packOptions?.directoriesExcluded ?? []);
2425
+ const extraExcludedFiles = new Set(packOptions?.filesExcluded ?? []);
2426
+ const otherLockFiles = new Set(CANDIDATE_LOCK_FILES.filter((name) => name !== lockFile));
2427
+ async function walk(src, dest) {
2428
+ await fs7.mkdir(dest);
2429
+ const entries = await fs7.readdir(src);
2430
+ for (const name of entries) {
2431
+ if (EXCLUDED_NAMES.has(name))
2432
+ continue;
2433
+ if (extraExcludedDirs.has(name))
2434
+ continue;
2435
+ if (extraExcludedFiles.has(name))
2436
+ continue;
2437
+ if (EXCLUDED_EXTENSIONS.some((ext) => name.endsWith(ext)))
2438
+ continue;
2439
+ if (otherLockFiles.has(name))
2440
+ continue;
2441
+ const srcEntry = fs7.path.join(src, name);
2442
+ const destEntry = fs7.path.join(dest, name);
2443
+ const stat2 = await fs7.stat(srcEntry);
2444
+ if (stat2?.isDirectory()) {
2445
+ await walk(srcEntry, destEntry);
2446
+ } else if (isRegistryConfigFile(name)) {
2447
+ const raw = await fs7.readFile(srcEntry, "utf-8") ?? "";
2448
+ const sanitized = sanitizeRegistryConfig(raw, SCOPES_NOT_PACKAGED);
2449
+ if (sanitized !== null)
2450
+ await fs7.writeFile(destEntry, sanitized);
2451
+ } else if (stat2?.isFile()) {
2452
+ const content = await fs7.readFile(srcEntry);
2453
+ if (content)
2454
+ await fs7.writeFile(destEntry, content);
2455
+ }
2456
+ }
2457
+ }
2458
+ await walk(sourcePath, destPath);
2459
+ }
2460
+ var COMMANDS = {
2461
+ npm: {
2462
+ bin: "npm",
2463
+ args: ({ production, preferOffline }) => [
2464
+ "install",
2465
+ ...production === true ? ["--omit=dev"] : [],
2466
+ ...preferOffline === true ? ["--prefer-offline"] : []
2467
+ ],
2468
+ verifyArgs: ["ci", "--dry-run", "--no-audit", "--no-fund"],
2469
+ saysLockDiffers: (output) => output.includes("EUSAGE")
2470
+ },
2471
+ bun: {
2472
+ bin: "bun",
2473
+ args: ({ production, preferOffline }) => [
2474
+ "install",
2475
+ ...production === true ? ["--production"] : [],
2476
+ ...preferOffline === true ? ["--prefer-offline"] : []
2477
+ ],
2478
+ verifyArgs: ["install", "--frozen-lockfile", "--dry-run"],
2479
+ saysLockDiffers: (output) => output.includes("lockfile had changes")
2480
+ }
2481
+ };
2482
+ var FALLBACK_ORDER = ["npm", "bun"];
2483
+ var PACKAGE_MANAGER_NAMES = Object.keys(COMMANDS);
2484
+ var RUNNER_REGISTRY_CONFIG = `@uipath:registry=https://npm.pkg.github.com
2485
+ //npm.pkg.github.com/:_authToken=\${GITHUB_TOKEN}`;
2486
+ function writeRunnerRegistryConfig(dir) {
2487
+ if (process.env["GITHUB_TOKEN"] === undefined || process.env["GITHUB_TOKEN"] === "")
2488
+ return;
2489
+ writeFileSync3(join3(dir, REGISTRY_CONFIG_FILE), RUNNER_REGISTRY_CONFIG, "utf-8");
2490
+ }
2491
+ function shareRegistryConfig(fromDir, toDir) {
2492
+ if (fromDir === toDir)
2493
+ return;
2494
+ const source = join3(fromDir, REGISTRY_CONFIG_FILE);
2495
+ if (existsSync2(source))
2496
+ copyFileSync(source, join3(toDir, REGISTRY_CONFIG_FILE));
2497
+ }
2498
+ var onPathCache = new Map;
2499
+ function isOnPath(name) {
2500
+ const cached = onPathCache.get(name);
2501
+ if (cached !== undefined)
2502
+ return cached;
2503
+ const result = spawnSync(COMMANDS[name].bin, ["--version"], {
2504
+ stdio: "ignore",
2505
+ shell: process.platform === "win32"
2506
+ });
2507
+ const available = result.status === 0;
2508
+ onPathCache.set(name, available);
2509
+ return available;
2510
+ }
2511
+ function detectAvailableManagers() {
2512
+ return FALLBACK_ORDER.filter((name) => isOnPath(name));
2513
+ }
2514
+ function declaredManager(cwd) {
2515
+ let declared;
2516
+ try {
2517
+ declared = JSON.parse(readFileSync2(join3(cwd, "package.json"), "utf-8")).packageManager;
2518
+ } catch {
2519
+ return null;
2520
+ }
2521
+ if (typeof declared !== "string")
2522
+ return null;
2523
+ const name = declared.split("@")[0];
2524
+ return Object.keys(COMMANDS).find((known) => known === name) ?? null;
2525
+ }
2526
+ function presentLockFiles(cwd) {
2527
+ return new Set(CANDIDATE_LOCK_FILES.filter((fileName) => existsSync2(join3(cwd, fileName))));
2528
+ }
2529
+ function lockedManager(cwd) {
2530
+ const detection = detectPackageManager(presentLockFiles(cwd));
2531
+ return detection.kind === "found" ? detection.manager.name : null;
2532
+ }
2533
+ function firstComplaint(output) {
2534
+ const lines = output.split(`
2535
+ `).map((line) => line.replace(/^npm (error|warn)/, "").trim()).filter((line) => line !== "");
2536
+ const end = lines.findIndex((line) => line.startsWith("Usage:") || line.startsWith("Options:"));
2537
+ return (end === -1 ? lines : lines.slice(0, end)).slice(0, 3).join(" ");
2538
+ }
2539
+ function detectProjectManager(cwd) {
2540
+ return lockedManager(cwd) ?? declaredManager(cwd);
2541
+ }
2542
+ function resolvePackageManager(cwd, required) {
2543
+ const { name, bin, shell } = required === undefined ? chosenInvocation(cwd) : requiredInvocation(required);
2544
+ const { args, verifyArgs, saysLockDiffers } = COMMANDS[name];
2545
+ return {
2546
+ name,
2547
+ verifyLock(dir) {
2548
+ const result = spawnSync(bin, [...verifyArgs], {
2549
+ cwd: dir,
2550
+ encoding: "utf-8",
2551
+ shell
2552
+ });
2553
+ const output = `${result.stdout ?? ""}
2554
+ ${result.stderr ?? ""}`;
2555
+ const detail = firstComplaint(output);
2556
+ if (result.status === 0)
2557
+ return { verdict: "current", detail };
2558
+ return { verdict: saysLockDiffers(output) ? "differs" : "unknown", detail };
2559
+ },
2560
+ runInstall(dir, options = {}) {
2561
+ shareRegistryConfig(cwd, dir);
2562
+ const argv = args(options);
2563
+ console.log(`Running: ${bin} ${argv.join(" ")}`);
2564
+ const result = spawnSync(bin, argv, {
2565
+ cwd: dir,
2566
+ stdio: "inherit",
2567
+ shell
2568
+ });
2569
+ if (result.status !== 0) {
2570
+ throw new Error(`'${bin} ${argv.join(" ")}' failed in ${dir}.`);
2571
+ }
2572
+ }
2573
+ };
2574
+ }
2575
+ function chooseManager(cwd) {
2576
+ const available = detectAvailableManagers();
2577
+ const desired = detectProjectManager(cwd);
2578
+ if (desired !== null && !available.includes(desired)) {
2579
+ const found = available.length > 0 ? ` (found ${available.join(", ")})` : "";
2580
+ throw new Error(`This project must be installed with ${desired}, which is not on PATH${found}.`);
2581
+ }
2582
+ const name = desired ?? available[0];
2583
+ if (name === undefined) {
2584
+ throw new Error(`No supported package manager is on PATH (looked for ${FALLBACK_ORDER.join(", ")}).`);
2585
+ }
2586
+ return name;
2587
+ }
2588
+ function chosenInvocation(cwd) {
2589
+ const name = chooseManager(cwd);
2590
+ return { name, bin: COMMANDS[name].bin, shell: process.platform === "win32" };
2591
+ }
2592
+ function requiredInvocation(required) {
2593
+ if (isManagerName(required)) {
2594
+ if (!isOnPath(required)) {
2595
+ throw new Error(`Cannot install with ${required}: it is not on PATH.`);
2596
+ }
2597
+ return { name: required, bin: COMMANDS[required].bin, shell: process.platform === "win32" };
2598
+ }
2599
+ const name = basename(required, extname(required)).toLowerCase();
2600
+ if (!isManagerName(name)) {
2601
+ throw new Error(`Cannot tell which package manager '${required}' is. Pass ${PACKAGE_MANAGER_NAMES.join(" or ")}, ` + "or the path to a binary named after one.");
2602
+ }
2603
+ if (!isAbsolute(required)) {
2604
+ throw new Error(`Cannot install with '${required}': a package manager path must be absolute.`);
2605
+ }
2606
+ if (!existsSync2(required)) {
2607
+ throw new Error(`Cannot install with '${required}': there is no such file.`);
2608
+ }
2609
+ return { name, bin: required, shell: needsShell(required) };
2610
+ }
2611
+ function isManagerName(value) {
2612
+ return PACKAGE_MANAGER_NAMES.includes(value);
2613
+ }
2614
+ function needsShell(managerPath) {
2615
+ return process.platform === "win32" && extname(managerPath).toLowerCase() !== ".exe";
2616
+ }
2617
+ function checkDependenciesInstalled(cwd) {
2618
+ if (existsSync2(join3(cwd, "node_modules")))
2619
+ return { ready: true, problem: null, remedyCommand: null };
2620
+ return {
2621
+ ready: false,
2622
+ problem: "node_modules not found.",
2623
+ remedyCommand: describeInstallCommand(cwd)
2624
+ };
2625
+ }
2626
+ function checkLockCurrent(cwd) {
2627
+ const detection = detectPackageManager(presentLockFiles(cwd));
2628
+ if (detection.kind !== "found") {
2629
+ const { problem, remedyCommand } = describeDependencyProblem(detection);
2630
+ return { ready: false, problem, remedyCommand };
2631
+ }
2632
+ const { lockFile, installHint } = detection.manager;
2633
+ const { verdict, detail } = resolvePackageManager(cwd).verifyLock(cwd);
2634
+ if (verdict === "current")
2635
+ return { ready: true, problem: null, remedyCommand: null };
2636
+ if (verdict === "unknown") {
2637
+ return {
2638
+ ready: false,
2639
+ problem: `Could not check whether ${lockFile} is up to date${detail === "" ? "." : `: ${detail}`}`,
2640
+ remedyCommand: null
2641
+ };
2642
+ }
2643
+ return {
2644
+ ready: false,
2645
+ problem: detail === "" ? `${lockFile} is out of date.` : `${lockFile} is out of date: ${detail}`,
2646
+ remedyCommand: installHint
2647
+ };
2648
+ }
2649
+ function describeInstallCommand(cwd) {
2650
+ const name = detectProjectManager(cwd) ?? FALLBACK_ORDER[0];
2651
+ const { bin, args } = COMMANDS[name];
2652
+ return `${bin} ${args({}).join(" ")}`;
2653
+ }
2654
+ function affectsDependencyInstall(fileName) {
2655
+ return CANDIDATE_LOCK_FILES.includes(fileName);
2656
+ }
2657
+ function describePackagedInstallProblem(installInputs) {
2658
+ const detection = detectPackageManager(new Set(installInputs));
2659
+ if (detection.kind === "found")
2660
+ return null;
2661
+ return `cannot be installed: ${describeDependencyProblem(detection).problem}`;
2662
+ }
2663
+ function registerNewCommand(program2) {
2664
+ program2.command("new [name]").description("Scaffold a new JS/TS Functions project. Includes a hello world function by default; pass --empty to skip it.").option("--name <name>", "Project name / directory (alias for positional arg)").option("-l, --language <lang>", "Language: ts (default) or js", "ts").option("--empty", "Skip the hello world function — create an empty project").action((nameArg, opts) => {
2665
+ const projectName = opts.name ?? nameArg ?? "my-functions";
2666
+ const lang = opts.language === "js" ? "js" : "ts";
2667
+ const projectDir = resolve(projectName);
2668
+ if (existsSync3(projectDir)) {
2669
+ console.error(`Directory already exists: ${projectDir}`);
2670
+ process.exit(1);
2671
+ }
2672
+ ensureSetup();
2673
+ const withSample = !opts.empty;
2674
+ const sampleFile = `functions/${SAMPLE_FUNCTION.name}.${lang}`;
2675
+ scaffoldProject({
2676
+ projectDir,
2677
+ name: projectName,
2678
+ lang,
2679
+ functions: withSample ? { [SAMPLE_FUNCTION.name]: `${sampleFile}:${SAMPLE_FUNCTION.entryExport}` } : {}
2680
+ });
2681
+ if (withSample) {
2682
+ writeFileSync4(join4(projectDir, sampleFile), lang === "ts" ? HELLO_TS : HELLO_JS, "utf-8");
2683
+ }
2684
+ console.log(`
2685
+ Created ${projectName}/`);
2686
+ console.log("Installing dependencies...");
2687
+ try {
2688
+ resolvePackageManager(projectDir).runInstall(projectDir);
2689
+ } catch (err) {
2690
+ console.error(err instanceof Error ? err.message : String(err));
2691
+ process.exit(1);
2692
+ }
2693
+ console.log(`
2694
+ Ready. Next steps:`);
2695
+ console.log(` cd ${projectName}`);
2696
+ if (withSample) {
2697
+ console.log(` uip functions serve`);
2698
+ } else {
2699
+ console.log(` # Add your function entry points to ${projectName}/functions/`);
2700
+ console.log(` uip functions serve`);
2701
+ }
2702
+ });
2703
+ }
2704
+ var SERVER_RUNNER_DIR = ".uipath/server-runner";
2705
+ var DESIGN_TIME_ENV = "DESIGN_TIME";
2706
+ var RUNTIME_VERSION = "^0.9.0";
2707
+ var TSX_VERSION = "^4.0.0";
2708
+ var COREIPC_VERSION = "2.5.3";
2709
+ var SIGNALR_VERSION = "8.0.7";
2710
+ var TRACE_MAPPING_VERSION = "0.3.25";
2711
+ function generateAggregator(functionsMap, cwd, variant, derivedByPath = {}) {
2712
+ const lang = detectLanguage(functionsMap);
2713
+ const ext = lang === "javascript" ? "js" : "ts";
2714
+ const fileToFunctions = new Map;
2715
+ for (const [name, entry] of Object.entries(functionsMap)) {
2716
+ const file = entry.split(":")[0];
2717
+ const existing = fileToFunctions.get(file);
2718
+ if (existing) {
2719
+ existing.push(name);
2720
+ } else {
2721
+ fileToFunctions.set(file, [name]);
2722
+ }
2723
+ }
2724
+ for (const [file, names] of fileToFunctions) {
2725
+ if (names.length > 1) {
2726
+ throw new Error(`Multiple function definitions in the same file are not allowed.
2727
+ ` + `File "${file}" is used by: ${names.join(", ")}.
2728
+ ` + `Each function must be defined in its own file.`);
2729
+ }
2730
+ }
2731
+ const files = [...fileToFunctions.keys()];
2732
+ let outputFile;
2733
+ let importPrefix;
2734
+ if (variant === "serve") {
2735
+ const dbgDir = join5(cwd, SERVER_RUNNER_DIR);
2736
+ mkdirSync3(dbgDir, { recursive: true });
2737
+ outputFile = join5(dbgDir, `function-main.${ext}`);
2738
+ importPrefix = "../../";
2739
+ } else {
2740
+ outputFile = join5(cwd, `function-main.${ext}`);
2741
+ importPrefix = "./";
2742
+ }
2743
+ const imports = files.map((file, i) => `import f${i} from "${importPrefix}${file}";`).join(`
2744
+ `);
2745
+ const relevantDerived = {};
2746
+ for (const file of files) {
2747
+ const d = derivedByPath[file];
2748
+ if (!d)
2749
+ continue;
2750
+ const entry = {};
2751
+ if (d.input !== undefined)
2752
+ entry.input = d.input;
2753
+ if (d.output !== undefined)
2754
+ entry.output = d.output;
2755
+ if (entry.input !== undefined || entry.output !== undefined)
2756
+ relevantDerived[file] = entry;
2757
+ }
2758
+ const hasDerived = Object.keys(relevantDerived).length > 0;
2759
+ const entries = files.map((file, i) => {
2760
+ const def = hasDerived ? `__lower(f${i}, "${file}")` : `f${i}`;
2761
+ return `{ functionDef: ${def}, functionPath: "${file}" }`;
2762
+ }).join(", ");
2763
+ const header = lang === "javascript" ? `// @ts-check
2764
+ ` : "";
2765
+ const loweringBlock = hasDerived ? `const __derived = ${JSON.stringify(relevantDerived, null, 2)};
2766
+ ` + `function __lower(def, path) {
2767
+ ` + ` const d = __derived[path];
2768
+ ` + ` if (!d) return def;
2769
+ ` + ` const out = { ...def };
2770
+ ` + ` if (d.input !== undefined) out.input = d.input;
2771
+ ` + ` if (d.output !== undefined) out.output = d.output;
2772
+ ` + ` return out;
2773
+ ` + `}
2774
+
2775
+ ` : "";
2776
+ const content = `${header}` + `// Generated by uipath-functions — do not edit
2777
+ ` + `import { createApp } from "@uipath/coded-functions-js-runtime";
2778
+ ` + `${imports}
2779
+
2780
+ ` + `${loweringBlock}` + `export default createApp([${entries}]);
2781
+ `;
2782
+ writeFileSync5(outputFile, content, "utf-8");
2783
+ return outputFile;
2784
+ }
2785
+ function detectLanguage(functionsMap) {
2786
+ const first = Object.values(functionsMap)[0]?.split(":")[0] ?? "";
2787
+ return extname2(first) === ".js" ? "javascript" : "typescript";
2788
+ }
2789
+ var SegmentTier = {
2790
+ Literal: 0,
2791
+ RegexParam: 1,
2792
+ RequiredParam: 2,
2793
+ OptionalParam: 3,
2794
+ Wildcard: 4
2795
+ };
2796
+ function trimSlashes(slug) {
2797
+ return slug.replace(/^\/+|\/+$/g, "");
2338
2798
  }
2339
2799
  function classifySegment(segment) {
2340
2800
  if (segment === "*") {
@@ -2589,10 +3049,13 @@ var DIAGNOSTIC_CODES = {
2589
3049
  UNSUPPORTED_VALIDATOR: "unsupported-validator",
2590
3050
  UNSUPPORTED_TYPE: "unsupported-type",
2591
3051
  NON_STATIC_LITERAL: "non-static-literal",
3052
+ UNREADABLE_PROPERTY: "unreadable-property",
2592
3053
  MISSING_TYPE_ARGUMENT: "missing-type-argument",
2593
3054
  AMBIGUOUS_ROUTE: "ambiguous-route",
2594
3055
  MULTIPLE_FUNCTIONS_PER_FILE: "multiple-functions-per-file",
2595
- DEPRECATED_MARKER: "deprecated-marker"
3056
+ DEPRECATED_MARKER: "deprecated-marker",
3057
+ NO_FUNCTION_DEFINITION: "no-function-definition",
3058
+ UNRESOLVED_SOURCE_FILE: "unresolved-source-file"
2596
3059
  };
2597
3060
  function extractFunctionContracts(sourceFile, checker) {
2598
3061
  const bindings = sdkImportBindings(sourceFile);
@@ -2610,6 +3073,21 @@ function extractFunctionContracts(sourceFile, checker) {
2610
3073
  if (diagnostic)
2611
3074
  diagnostics.push({ ...diagnostic, functionName: fn.name, field });
2612
3075
  }
3076
+ const unreadable = isNestedInFunction(node) ? { fields: [], anyField: false } : unreadableProperties(arg);
3077
+ if (unreadable.anyField) {
3078
+ diagnostics.push({
3079
+ ...diag(DIAGNOSTIC_CODES.UNREADABLE_PROPERTY, "the definition spreads another object or uses a computed key, so which " + "contract fields it carries is not statically known", "warning"),
3080
+ functionName: fn.name
3081
+ });
3082
+ } else {
3083
+ for (const field of unreadable.fields) {
3084
+ diagnostics.push({
3085
+ ...diag(DIAGNOSTIC_CODES.UNREADABLE_PROPERTY, METADATA_FIELDS.has(field) ? `${field} cannot be read statically: a shorthand property, a method, an ` + `accessor and a reference to a variable all read as absent. Write it at ` + `the defineFunction call as a string literal.` : `${field} is declared as a shorthand property, a method or an accessor, ` + `which reads as absent. Write it as \`${field}: <value>\`.`, "warning"),
3086
+ functionName: fn.name,
3087
+ ...field === "input" || field === "output" ? { field } : {}
3088
+ });
3089
+ }
3090
+ }
2613
3091
  functions.push(fn);
2614
3092
  }
2615
3093
  }
@@ -2623,13 +3101,28 @@ function extractFromFiles(files, checker, limits) {
2623
3101
  const diagnostics = [];
2624
3102
  const maxPerFile = limits?.maxDefineFunctionsPerFile;
2625
3103
  for (const { functionPath, sourceFile } of files) {
2626
- if (!sourceFile)
3104
+ if (!sourceFile) {
3105
+ diagnostics.push({
3106
+ code: DIAGNOSTIC_CODES.UNRESOLVED_SOURCE_FILE,
3107
+ severity: "error",
3108
+ message: `could not be loaded — the file is missing, unreadable, or excluded from the ` + `TypeScript program.`,
3109
+ file: functionPath
3110
+ });
2627
3111
  continue;
3112
+ }
2628
3113
  const result = extractFunctionContracts(sourceFile, checker);
2629
3114
  for (const fn of result.functions)
2630
3115
  functions.push({ ...fn, functionPath });
2631
3116
  for (const d of result.diagnostics)
2632
3117
  diagnostics.push({ ...d, file: functionPath });
3118
+ if (limits?.requireFunctionPerFile && result.functions.length === 0 && !hasDefaultExport(sourceFile, checker)) {
3119
+ diagnostics.push({
3120
+ code: DIAGNOSTIC_CODES.NO_FUNCTION_DEFINITION,
3121
+ severity: "error",
3122
+ message: `no default export — an entry point must default-export its function definition.`,
3123
+ file: functionPath
3124
+ });
3125
+ }
2633
3126
  if (maxPerFile !== undefined && result.functions.length > maxPerFile) {
2634
3127
  diagnostics.push({
2635
3128
  code: DIAGNOSTIC_CODES.MULTIPLE_FUNCTIONS_PER_FILE,
@@ -2651,6 +3144,12 @@ function extractFromFiles(files, checker, limits) {
2651
3144
  return { functions, diagnostics };
2652
3145
  }
2653
3146
  var SDK_MODULE = "@uipath/coded-functions-js-sdk";
3147
+ function hasDefaultExport(sourceFile, checker) {
3148
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
3149
+ if (!moduleSymbol)
3150
+ return false;
3151
+ return checker.getExportsOfModule(moduleSymbol).some((s) => s.escapedName === "default");
3152
+ }
2654
3153
  var MARKER_EXPORTS = ["defineSchema", "type"];
2655
3154
  function sdkImportBindings(sourceFile) {
2656
3155
  const map = new Map;
@@ -2679,7 +3178,7 @@ function resolveField(obj, field, checker, bindings) {
2679
3178
  const prop = findProp(obj, field);
2680
3179
  if (!prop)
2681
3180
  return {};
2682
- const value = prop.initializer;
3181
+ const value = unwrap(prop.initializer);
2683
3182
  const callee = ts.isCallExpression(value) && ts.isIdentifier(value.expression) ? value.expression.text : undefined;
2684
3183
  if (ts.isCallExpression(value) && callee !== undefined && MARKER_EXPORTS.some((name) => matchesSdkExport(callee, name, bindings))) {
2685
3184
  const typeArg = value.typeArguments?.[0];
@@ -2710,15 +3209,50 @@ function resolveField(obj, field, checker, bindings) {
2710
3209
  };
2711
3210
  }
2712
3211
  function propertyName(name) {
2713
- if (ts.isIdentifier(name) || ts.isStringLiteral(name))
3212
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
2714
3213
  return name.text;
3214
+ }
2715
3215
  return;
2716
3216
  }
3217
+ var CONTRACT_FIELDS = new Set(["name", "method", "path", "description", "input", "output"]);
3218
+ var METADATA_FIELDS = new Set(["name", "method", "path", "description"]);
3219
+ function isNestedInFunction(node) {
3220
+ for (let current = node.parent;current && !ts.isSourceFile(current); current = current.parent) {
3221
+ if (ts.isFunctionLike(current) || ts.isClassStaticBlockDeclaration(current))
3222
+ return true;
3223
+ }
3224
+ return false;
3225
+ }
3226
+ function unreadableProperties(obj) {
3227
+ const fields = new Set;
3228
+ for (const property of obj.properties) {
3229
+ if (ts.isPropertyAssignment(property)) {
3230
+ const name2 = propertyName(property.name);
3231
+ if (name2 === undefined)
3232
+ return { fields: [], anyField: true };
3233
+ if (METADATA_FIELDS.has(name2) && !isReadableMetadataValue(property.initializer)) {
3234
+ fields.add(name2);
3235
+ }
3236
+ continue;
3237
+ }
3238
+ if (ts.isSpreadAssignment(property))
3239
+ return { fields: [], anyField: true };
3240
+ const name = property.name && propertyName(property.name);
3241
+ if (name === undefined)
3242
+ return { fields: [], anyField: true };
3243
+ if (CONTRACT_FIELDS.has(name))
3244
+ fields.add(name);
3245
+ }
3246
+ return { fields: [...fields], anyField: false };
3247
+ }
3248
+ function isReadableMetadataValue(value) {
3249
+ return ts.isStringLiteralLike(unwrap(value));
3250
+ }
2717
3251
  function findProp(obj, field) {
2718
3252
  return obj.properties.find((p) => ts.isPropertyAssignment(p) && propertyName(p.name) === field);
2719
3253
  }
2720
- function diag(code, message) {
2721
- return { code, severity: "error", message };
3254
+ function diag(code, message, severity = "error") {
3255
+ return { code, severity, message };
2722
3256
  }
2723
3257
  function readMetadata(obj) {
2724
3258
  const meta = {};
@@ -2739,26 +3273,41 @@ function readMetadata(obj) {
2739
3273
  meta.tags = tags;
2740
3274
  return meta;
2741
3275
  }
3276
+ function unwrap(value) {
3277
+ let current = value;
3278
+ while (ts.isAsExpression(current) || ts.isParenthesizedExpression(current) || ts.isSatisfiesExpression(current)) {
3279
+ current = current.expression;
3280
+ }
3281
+ return current;
3282
+ }
2742
3283
  function stringProp(obj, field) {
2743
3284
  const prop = findProp(obj, field);
2744
- return prop && ts.isStringLiteralLike(prop.initializer) ? prop.initializer.text : undefined;
3285
+ if (!prop)
3286
+ return;
3287
+ const value = unwrap(prop.initializer);
3288
+ return ts.isStringLiteralLike(value) ? value.text : undefined;
2745
3289
  }
2746
3290
  function stringArrayProp(obj, field) {
2747
3291
  const prop = findProp(obj, field);
2748
- if (!prop || !ts.isArrayLiteralExpression(prop.initializer))
3292
+ if (!prop)
3293
+ return;
3294
+ const array = unwrap(prop.initializer);
3295
+ if (!ts.isArrayLiteralExpression(array))
2749
3296
  return;
2750
3297
  const values = [];
2751
- for (const el of prop.initializer.elements) {
2752
- if (!ts.isStringLiteralLike(el))
3298
+ for (const el of array.elements) {
3299
+ const value = unwrap(el);
3300
+ if (!ts.isStringLiteralLike(value))
2753
3301
  return;
2754
- values.push(el.text);
3302
+ values.push(value.text);
2755
3303
  }
2756
3304
  return values;
2757
3305
  }
2758
3306
  function literalToSchema(node) {
2759
3307
  return foldLiteral(node);
2760
3308
  }
2761
- function foldLiteral(node) {
3309
+ function foldLiteral(expression) {
3310
+ const node = unwrap(expression);
2762
3311
  if (ts.isStringLiteralLike(node))
2763
3312
  return node.text;
2764
3313
  if (ts.isNumericLiteral(node))
@@ -2786,176 +3335,618 @@ function foldLiteral(node) {
2786
3335
  throw new Error("object has a computed/non-static property key");
2787
3336
  obj[key] = foldLiteral(p.initializer);
2788
3337
  }
2789
- return obj;
3338
+ return obj;
3339
+ }
3340
+ throw new Error(`not a static literal (${ts.SyntaxKind[node.kind]})`);
3341
+ }
3342
+ function extractDisk(opts) {
3343
+ const { cwd, files } = opts;
3344
+ const diskFs = {
3345
+ readFile: () => {
3346
+ return;
3347
+ },
3348
+ fileExists: () => false,
3349
+ directoryExists: () => false,
3350
+ currentDirectory: cwd
3351
+ };
3352
+ const rootNames = files.map((f) => resolve2(cwd, f));
3353
+ const { program: program2, checker } = createProgram(diskFs, rootNames, readCompilerOptions(cwd));
3354
+ const useCase = ts2.sys.useCaseSensitiveFileNames;
3355
+ const canonical = (p) => {
3356
+ const s = p.replace(/\\/g, "/");
3357
+ return useCase ? s : s.toLowerCase();
3358
+ };
3359
+ const byPath = new Map(program2.getSourceFiles().map((sf) => [canonical(sf.fileName), sf]));
3360
+ return extractFromFiles(files.map((file) => ({ functionPath: file, sourceFile: byPath.get(canonical(resolve2(cwd, file))) })), checker, opts.limits);
3361
+ }
3362
+ function readCompilerOptions(cwd) {
3363
+ const configPath = ts2.findConfigFile(cwd, ts2.sys.fileExists, "tsconfig.json");
3364
+ if (!configPath)
3365
+ return CONSUMER_COMPILER_OPTIONS;
3366
+ const read = ts2.readConfigFile(configPath, ts2.sys.readFile);
3367
+ if (read.error || !read.config)
3368
+ return CONSUMER_COMPILER_OPTIONS;
3369
+ const parsed = ts2.parseJsonConfigFileContent(read.config, ts2.sys, dirname(configPath));
3370
+ return { ...parsed.options, noEmit: true, allowJs: true };
3371
+ }
3372
+ function extractProject(functionsMap, cwd) {
3373
+ const files = [...new Set(Object.values(functionsMap).map((v) => v.split(":")[0]))];
3374
+ return extractDisk({
3375
+ cwd,
3376
+ files,
3377
+ limits: { requireFunctionPerFile: true }
3378
+ });
3379
+ }
3380
+ function toDerivedContracts(functions) {
3381
+ const derived = {};
3382
+ for (const fn of functions) {
3383
+ if (fn.functionPath && (fn.input !== undefined || fn.output !== undefined)) {
3384
+ derived[fn.functionPath] = fn;
3385
+ }
3386
+ }
3387
+ return derived;
3388
+ }
3389
+ function deriveRunContract(relFile, cwd) {
3390
+ const { functions } = extractDisk({ cwd, files: [relFile] });
3391
+ const fn = functions.find((f) => f.input !== undefined || f.output !== undefined);
3392
+ if (!fn)
3393
+ return null;
3394
+ const derived = {};
3395
+ if (fn.input !== undefined)
3396
+ derived.input = fn.input;
3397
+ if (fn.output !== undefined)
3398
+ derived.output = fn.output;
3399
+ return derived;
3400
+ }
3401
+ function readBakedContract(relFile, cwd) {
3402
+ const doc = readJsonIfExists(join6(cwd, "entry-points.json"));
3403
+ const entryPoints = doc?.entryPoints;
3404
+ if (!Array.isArray(entryPoints))
3405
+ return null;
3406
+ const target = stripContentPrefix(relFile);
3407
+ const ep = entryPoints.find((e) => e?.type === "function" && typeof e.filePath === "string" && stripContentPrefix(e.filePath) === target);
3408
+ if (!ep)
3409
+ return null;
3410
+ const derived = {};
3411
+ if (ep.input !== undefined)
3412
+ derived.input = ep.input;
3413
+ if (ep.output !== undefined)
3414
+ derived.output = ep.output;
3415
+ return derived.input !== undefined || derived.output !== undefined ? derived : null;
3416
+ }
3417
+ function stripContentPrefix(p) {
3418
+ const s = p.replace(/\\/g, "/");
3419
+ return s.startsWith("content/") ? s.slice("content/".length) : s;
3420
+ }
3421
+ function readJsonIfExists(path3) {
3422
+ if (!existsSync4(path3))
3423
+ return null;
3424
+ try {
3425
+ return JSON.parse(readFileSync3(path3, "utf-8"));
3426
+ } catch {
3427
+ return null;
3428
+ }
3429
+ }
3430
+ var SDK_VERSION2 = "0.6.2";
3431
+ var SDK_RANGE2 = `^${SDK_VERSION2}`;
3432
+ var SDK_PACKAGE_NAME2 = "@uipath/coded-functions-js-sdk";
3433
+ var SAMPLE_FUNCTION2 = {
3434
+ name: "hello",
3435
+ description: "Returns a greeting message.",
3436
+ method: "POST",
3437
+ path: "/hello",
3438
+ entryExport: "default"
3439
+ };
3440
+ var httpSemantics2 = ` method: "${SAMPLE_FUNCTION2.method}",
3441
+ path: "${SAMPLE_FUNCTION2.path}",
3442
+ `;
3443
+ var semanticsFor2 = (variant) => variant === "http" ? httpSemantics2 : "";
3444
+ var buildHelloTs2 = (variant) => `import { defineFunction, defineSchema, type FunctionContext } from "@uipath/coded-functions-js-sdk";
3445
+
3446
+ interface HelloInput {
3447
+ /**
3448
+ * Name to greet — filled in by the runtime when omitted.
3449
+ * @default "World"
3450
+ */
3451
+ name?: string;
3452
+ }
3453
+
3454
+ interface HelloOutput {
3455
+ message: string;
3456
+ }
3457
+
3458
+ function main(input: HelloInput, ctx: FunctionContext): HelloOutput {
3459
+ const output: HelloOutput = {
3460
+ message: \`Hello, \${input.name}!\`,
3461
+ };
3462
+ return output;
3463
+ }
3464
+
3465
+ export default defineFunction({
3466
+ name: "${SAMPLE_FUNCTION2.name}",
3467
+ description: "${SAMPLE_FUNCTION2.description}",
3468
+ ${semanticsFor2(variant)} input: defineSchema<HelloInput>(),
3469
+ output: defineSchema<HelloOutput>(),
3470
+ handler: main,
3471
+ });
3472
+ `;
3473
+ var buildHelloJs2 = (variant) => `// @ts-check
3474
+ import { defineFunction } from "@uipath/coded-functions-js-sdk";
3475
+
3476
+ export default defineFunction({
3477
+ name: "${SAMPLE_FUNCTION2.name}",
3478
+ description: "${SAMPLE_FUNCTION2.description}",
3479
+ ${semanticsFor2(variant)} input: {
3480
+ type: "object",
3481
+ properties: {
3482
+ name: { type: "string", default: "World" },
3483
+ },
3484
+ additionalProperties: false,
3485
+ },
3486
+ output: {
3487
+ type: "object",
3488
+ properties: {
3489
+ message: { type: "string" },
3490
+ },
3491
+ required: ["message"],
3492
+ additionalProperties: false,
3493
+ },
3494
+ handler: async (input, ctx) => ({
3495
+ message: \`Hello, \${input.name}!\`,
3496
+ }),
3497
+ });
3498
+ `;
3499
+ var HELLO_TS2 = buildHelloTs2("http");
3500
+ var HELLO_TS_JOB2 = buildHelloTs2("job");
3501
+ var HELLO_JS2 = buildHelloJs2("http");
3502
+ var HELLO_JS_JOB2 = buildHelloJs2("job");
3503
+ var SAMPLE_TSCONFIG2 = JSON.stringify({
3504
+ compilerOptions: {
3505
+ target: "ESNext",
3506
+ module: "ESNext",
3507
+ moduleResolution: "bundler",
3508
+ strict: true,
3509
+ allowImportingTsExtensions: true,
3510
+ noEmit: true
3511
+ },
3512
+ include: ["**/*.ts"],
3513
+ exclude: ["node_modules", "dist"]
3514
+ }, null, 2) + `
3515
+ `;
3516
+ var SAMPLE_LOCK_PACKAGES2 = {
3517
+ "node_modules/@babel/runtime": {
3518
+ version: "7.29.7",
3519
+ resolved: "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
3520
+ integrity: "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
3521
+ dev: true,
3522
+ license: "MIT",
3523
+ engines: { node: ">=6.9.0" }
3524
+ },
3525
+ "node_modules/@standard-schema/spec": {
3526
+ version: "1.1.0",
3527
+ resolved: "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
3528
+ integrity: "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
3529
+ dev: true,
3530
+ license: "MIT"
3531
+ },
3532
+ [`node_modules/${SDK_PACKAGE_NAME2}`]: {
3533
+ version: SDK_VERSION2,
3534
+ dev: true,
3535
+ dependencies: {
3536
+ "@standard-schema/spec": "^1.1.0",
3537
+ "json-schema-to-ts": "^3.1.1"
3538
+ }
3539
+ },
3540
+ "node_modules/json-schema-to-ts": {
3541
+ version: "3.1.1",
3542
+ resolved: "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
3543
+ integrity: "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
3544
+ dev: true,
3545
+ license: "MIT",
3546
+ dependencies: {
3547
+ "@babel/runtime": "^7.18.3",
3548
+ "ts-algebra": "^2.0.0"
3549
+ },
3550
+ engines: { node: ">=16" }
3551
+ },
3552
+ "node_modules/ts-algebra": {
3553
+ version: "2.0.0",
3554
+ resolved: "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
3555
+ integrity: "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
3556
+ dev: true,
3557
+ license: "MIT"
3558
+ },
3559
+ "node_modules/typescript": {
3560
+ version: "5.9.3",
3561
+ resolved: "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
3562
+ integrity: "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
3563
+ dev: true,
3564
+ license: "Apache-2.0",
3565
+ bin: { tsc: "bin/tsc", tsserver: "bin/tsserver" },
3566
+ engines: { node: ">=14.17" }
3567
+ }
3568
+ };
3569
+ var CONSUMER_COMPILER_OPTIONS2 = {
3570
+ target: ts3.ScriptTarget.ES2020,
3571
+ module: ts3.ModuleKind.ESNext,
3572
+ moduleResolution: ts3.ModuleResolutionKind.Bundler,
3573
+ allowImportingTsExtensions: true,
3574
+ allowJs: true,
3575
+ strict: true,
3576
+ skipLibCheck: true,
3577
+ noEmit: true
3578
+ };
3579
+ var DIAGNOSTIC_CODES2 = {
3580
+ UNSUPPORTED_VALIDATOR: "unsupported-validator",
3581
+ UNSUPPORTED_TYPE: "unsupported-type",
3582
+ NON_STATIC_LITERAL: "non-static-literal",
3583
+ UNREADABLE_PROPERTY: "unreadable-property",
3584
+ MISSING_TYPE_ARGUMENT: "missing-type-argument",
3585
+ AMBIGUOUS_ROUTE: "ambiguous-route",
3586
+ MULTIPLE_FUNCTIONS_PER_FILE: "multiple-functions-per-file",
3587
+ DEPRECATED_MARKER: "deprecated-marker",
3588
+ NO_FUNCTION_DEFINITION: "no-function-definition",
3589
+ UNRESOLVED_SOURCE_FILE: "unresolved-source-file"
3590
+ };
3591
+ var CONTRACT_FIELDS2 = new Set(["name", "method", "path", "description", "input", "output"]);
3592
+ var METADATA_FIELDS2 = new Set(["name", "method", "path", "description"]);
3593
+ var JOB_ATTACHMENT_REF = "#/definitions/job-attachment";
3594
+ var JOB_ATTACHMENT_DEFINITION_KEY = "job-attachment";
3595
+ var JOB_ATTACHMENT_DEFINITION = {
3596
+ type: "object",
3597
+ required: ["ID"],
3598
+ "x-uipath-resource-kind": "JobAttachment",
3599
+ properties: {
3600
+ ID: { type: "string", description: "Orchestrator attachment key" },
3601
+ FullName: { type: "string", description: "File name" },
3602
+ MimeType: {
3603
+ type: "string",
3604
+ description: 'The MIME type of the content, such as "application/json" or "image/png"'
3605
+ },
3606
+ Metadata: {
3607
+ type: "object",
3608
+ description: "Dictionary<string, string> of metadata",
3609
+ additionalProperties: { type: "string" }
3610
+ }
2790
3611
  }
2791
- throw new Error(`not a static literal (${ts.SyntaxKind[node.kind]})`);
2792
- }
2793
- function extractDisk(opts) {
2794
- const { cwd, files } = opts;
2795
- const diskFs = {
2796
- readFile: () => {
2797
- return;
2798
- },
2799
- fileExists: () => false,
2800
- directoryExists: () => false,
2801
- currentDirectory: cwd
2802
- };
2803
- const rootNames = files.map((f) => resolve2(cwd, f));
2804
- const { program: program2, checker } = createProgram(diskFs, rootNames, readCompilerOptions(cwd));
2805
- const useCase = ts2.sys.useCaseSensitiveFileNames;
2806
- const canonical = (p) => {
2807
- const s = p.replace(/\\/g, "/");
2808
- return useCase ? s : s.toLowerCase();
2809
- };
2810
- const byPath = new Map(program2.getSourceFiles().map((sf) => [canonical(sf.fileName), sf]));
2811
- return extractFromFiles(files.map((file) => ({ functionPath: file, sourceFile: byPath.get(canonical(resolve2(cwd, file))) })), checker, opts.limits);
3612
+ };
3613
+ var ANNOTATION_KEYS = ["title", "description", "default"];
3614
+ var STRUCTURAL_KEYS = new Set(["type", "properties", "required", "additionalProperties"]);
3615
+ var STRING_PROPERTIES = ["ID", "FullName", "MimeType"];
3616
+ function stripAnnotations(node) {
3617
+ const out = { ...node };
3618
+ for (const key of ANNOTATION_KEYS)
3619
+ delete out[key];
3620
+ return out;
2812
3621
  }
2813
- function readCompilerOptions(cwd) {
2814
- const configPath = ts2.findConfigFile(cwd, ts2.sys.fileExists, "tsconfig.json");
2815
- if (!configPath)
2816
- return CONSUMER_COMPILER_OPTIONS;
2817
- const read = ts2.readConfigFile(configPath, ts2.sys.readFile);
2818
- if (read.error || !read.config)
2819
- return CONSUMER_COMPILER_OPTIONS;
2820
- const parsed = ts2.parseJsonConfigFileContent(read.config, ts2.sys, dirname(configPath));
2821
- return { ...parsed.options, noEmit: true, allowJs: true };
3622
+ function isPlainString(node) {
3623
+ if (!node)
3624
+ return false;
3625
+ const shape = stripAnnotations(node);
3626
+ return Object.keys(shape).length === 1 && shape.type === "string";
2822
3627
  }
2823
- function extractProject(functionsMap, cwd) {
2824
- const files = [...new Set(Object.values(functionsMap).map((v) => v.split(":")[0]))];
2825
- return extractDisk({ cwd, files });
3628
+ function isOpenObject(node) {
3629
+ if (!node)
3630
+ return false;
3631
+ const shape = stripAnnotations(node);
3632
+ if (shape.type !== "object")
3633
+ return false;
3634
+ return Object.keys(shape).every((key) => key === "type" || key === "additionalProperties");
2826
3635
  }
2827
- function toDerivedContracts(functions) {
2828
- const derived = {};
2829
- for (const fn of functions) {
2830
- if (fn.functionPath && (fn.input !== undefined || fn.output !== undefined)) {
2831
- derived[fn.functionPath] = fn;
2832
- }
3636
+ function matchesJobAttachment(node) {
3637
+ if (node.type !== "object")
3638
+ return false;
3639
+ if (node.additionalProperties !== false && node.additionalProperties !== undefined)
3640
+ return false;
3641
+ for (const key of Object.keys(node)) {
3642
+ if (!STRUCTURAL_KEYS.has(key) && !ANNOTATION_KEYS.includes(key))
3643
+ return false;
2833
3644
  }
2834
- return derived;
2835
- }
2836
- function deriveMarkerContracts(functionsMap, cwd) {
2837
- return toDerivedContracts(extractProject(functionsMap, cwd).functions);
2838
- }
2839
- function deriveRunContract(relFile, cwd) {
2840
- const { functions } = extractDisk({ cwd, files: [relFile] });
2841
- const fn = functions.find((f) => f.input !== undefined || f.output !== undefined);
2842
- if (!fn)
2843
- return null;
2844
- const derived = {};
2845
- if (fn.input !== undefined)
2846
- derived.input = fn.input;
2847
- if (fn.output !== undefined)
2848
- derived.output = fn.output;
2849
- return derived;
3645
+ const props = node.properties;
3646
+ if (!props)
3647
+ return false;
3648
+ if (Object.keys(props).length !== ("Metadata" in props ? 4 : 3))
3649
+ return false;
3650
+ if (!STRING_PROPERTIES.every((p) => isPlainString(props[p])))
3651
+ return false;
3652
+ if ("Metadata" in props && !isOpenObject(props.Metadata))
3653
+ return false;
3654
+ const required = node.required ?? [];
3655
+ return required.includes("ID") && required.every((p) => STRING_PROPERTIES.includes(p));
3656
+ }
3657
+ function rewrite(node) {
3658
+ if (matchesJobAttachment(node)) {
3659
+ const ref = {};
3660
+ for (const key of ANNOTATION_KEYS) {
3661
+ if (key in node)
3662
+ ref[key] = node[key];
3663
+ }
3664
+ ref.$ref = JOB_ATTACHMENT_REF;
3665
+ return { node: ref, found: true };
3666
+ }
3667
+ let found = false;
3668
+ const out = { ...node };
3669
+ if (node.properties) {
3670
+ const properties = {};
3671
+ for (const [key, value] of Object.entries(node.properties)) {
3672
+ const result = rewrite(value);
3673
+ properties[key] = result.node;
3674
+ found = found || result.found;
3675
+ }
3676
+ out.properties = properties;
3677
+ }
3678
+ if (node.items) {
3679
+ const result = rewrite(node.items);
3680
+ out.items = result.node;
3681
+ found = found || result.found;
3682
+ }
3683
+ if (typeof node.additionalProperties === "object") {
3684
+ const result = rewrite(node.additionalProperties);
3685
+ out.additionalProperties = result.node;
3686
+ found = found || result.found;
3687
+ }
3688
+ for (const key of ["anyOf", "oneOf", "allOf"]) {
3689
+ const members = node[key];
3690
+ if (members) {
3691
+ const results = members.map(rewrite);
3692
+ out[key] = results.map((r) => r.node);
3693
+ found = found || results.some((r) => r.found);
3694
+ }
3695
+ }
3696
+ return { node: out, found };
3697
+ }
3698
+ function transformAttachments(schema) {
3699
+ const { node, found } = rewrite(schema);
3700
+ if (found)
3701
+ node.definitions = { [JOB_ATTACHMENT_DEFINITION_KEY]: JOB_ATTACHMENT_DEFINITION };
3702
+ return node;
2850
3703
  }
2851
- function readBakedContract(relFile, cwd) {
2852
- const doc = readJsonIfExists(join5(cwd, "entry-points.json"));
2853
- const entryPoints = doc?.entryPoints;
2854
- if (!Array.isArray(entryPoints))
2855
- return null;
2856
- const target = stripContentPrefix(relFile);
2857
- const ep = entryPoints.find((e) => e?.type === "function" && typeof e.filePath === "string" && stripContentPrefix(e.filePath) === target);
2858
- if (!ep)
2859
- return null;
2860
- const derived = {};
2861
- if (ep.input !== undefined)
2862
- derived.input = ep.input;
2863
- if (ep.output !== undefined)
2864
- derived.output = ep.output;
2865
- return derived.input !== undefined || derived.output !== undefined ? derived : null;
3704
+ function newId() {
3705
+ return globalThis.crypto.randomUUID();
2866
3706
  }
2867
- function stripContentPrefix(p) {
2868
- const s = p.replace(/\\/g, "/");
2869
- return s.startsWith("content/") ? s.slice("content/".length) : s;
3707
+ function buildEntryPointsDoc(functions, existing, filePathPrefix = "content/") {
3708
+ const functionIds = new Map;
3709
+ const transactionRoots = new Set;
3710
+ const preserved = [];
3711
+ for (const ep of existing?.entryPoints ?? []) {
3712
+ if (ep.type === "function") {
3713
+ functionIds.set(ep.filePath, ep.uniqueId);
3714
+ if (ep.isTransactionRoot === true) {
3715
+ transactionRoots.add(ep.filePath);
3716
+ }
3717
+ } else {
3718
+ preserved.push(ep);
3719
+ }
3720
+ }
3721
+ const functionEntries = functions.map((fn) => {
3722
+ const filePath = filePathPrefix + (fn.functionPath ?? "");
3723
+ return {
3724
+ filePath,
3725
+ uniqueId: functionIds.get(filePath) ?? newId(),
3726
+ type: "function",
3727
+ input: transformAttachments(fn.input ?? { type: "object" }),
3728
+ output: transformAttachments(fn.output ?? { type: "object" }),
3729
+ ...transactionRoots.has(filePath) ? { isTransactionRoot: true } : {}
3730
+ };
3731
+ });
3732
+ return {
3733
+ $schema: "https://cloud.uipath.com/draft/2024-12/entry-point",
3734
+ $id: "entry-points.json",
3735
+ entryPoints: [...preserved, ...functionEntries]
3736
+ };
2870
3737
  }
2871
- function readJsonIfExists(path3) {
2872
- if (!existsSync3(path3))
2873
- return null;
2874
- try {
2875
- return JSON.parse(readFileSync2(path3, "utf-8"));
2876
- } catch {
2877
- return null;
3738
+ function buildBindingsDoc(functions, entryPointIdByPath, existingBindings, filePathPrefix = "content/") {
3739
+ const httpExisting = new Map;
3740
+ const preserved = [];
3741
+ for (const r of existingBindings?.resources ?? []) {
3742
+ if (r.resource === "HttpTrigger") {
3743
+ const meta = r.metadata;
3744
+ if (meta?.Method && meta?.Slug) {
3745
+ httpExisting.set(`${meta.Method}:${meta.Slug}`, { key: r.key, id: r.id });
3746
+ }
3747
+ } else {
3748
+ preserved.push(r);
3749
+ }
2878
3750
  }
3751
+ const httpTriggers = functions.filter((fn) => fn.method && fn.path).map((fn) => {
3752
+ const existing = httpExisting.get(`${fn.method}:${fn.path}`);
3753
+ const bindingKey = existing?.key ?? newId();
3754
+ const bindingId = existing?.id ?? newId();
3755
+ const entryPointUniqueId = entryPointIdByPath.get(filePathPrefix + (fn.functionPath ?? ""));
3756
+ if (!entryPointUniqueId) {
3757
+ throw new Error(`Internal error: binding for "${fn.method} ${fn.path}" references entry point "${filePathPrefix}${fn.functionPath}", which is missing from entry-points.json.`);
3758
+ }
3759
+ return {
3760
+ resource: "HttpTrigger",
3761
+ key: bindingKey,
3762
+ id: bindingId,
3763
+ value: {
3764
+ EntryPointUniqueId: {
3765
+ DefaultValue: entryPointUniqueId,
3766
+ IsExpression: false
3767
+ }
3768
+ },
3769
+ metadata: {
3770
+ BindingsVersion: "2.1",
3771
+ Name: fn.name ?? "",
3772
+ Method: fn.method,
3773
+ Slug: fn.path,
3774
+ CallingMode: "LongPolling",
3775
+ Description: fn.description ?? ""
3776
+ }
3777
+ };
3778
+ });
3779
+ return {
3780
+ $schema: "https://cloud.uipath.com/draft/2024-12/bindings",
3781
+ version: "2.0",
3782
+ resources: [...preserved, ...httpTriggers]
3783
+ };
3784
+ }
3785
+ var BLOCKING_CODES = new Set([
3786
+ DIAGNOSTIC_CODES2.NO_FUNCTION_DEFINITION,
3787
+ DIAGNOSTIC_CODES2.UNRESOLVED_SOURCE_FILE
3788
+ ]);
3789
+ var SILENT_CODES = new Set([DIAGNOSTIC_CODES2.UNSUPPORTED_VALIDATOR]);
3790
+ function isSilentSchemaSignal(d) {
3791
+ return d.code === DIAGNOSTIC_CODES2.UNREADABLE_PROPERTY && d.field !== undefined;
2879
3792
  }
2880
- function setupRunDependencies(cwd, serverRunnerTemplatePath = "") {
2881
- const serverRunnerDir = join6(cwd, SERVER_RUNNER_DIR);
3793
+ var REMEDIATION = {
3794
+ [DIAGNOSTIC_CODES2.NO_FUNCTION_DEFINITION]: (d) => `Every file in functions/ is served as a function. If this file is a helper, move it out ` + `of functions/ or rename it to ${underscored(d.file)} so discovery skips it.`,
3795
+ [DIAGNOSTIC_CODES2.UNRESOLVED_SOURCE_FILE]: () => `Check the path exists and that tsconfig.json does not exclude it.`
3796
+ };
3797
+ function reportDiagnostics(diagnostics) {
3798
+ const blocking = diagnostics.filter((d) => BLOCKING_CODES.has(d.code));
3799
+ const rest = diagnostics.filter((d) => !BLOCKING_CODES.has(d.code) && !SILENT_CODES.has(d.code) && !isSilentSchemaSignal(d));
3800
+ for (const d of blocking)
3801
+ console.error(` Error: ${format(d)}`);
3802
+ for (const d of rest)
3803
+ console.warn(` Warning: ${format(d)}`);
3804
+ return blocking.length;
3805
+ }
3806
+ function reportDiagnosticsOrExit(diagnostics) {
3807
+ const blocking = reportDiagnostics(diagnostics);
3808
+ if (blocking === 0)
3809
+ return;
3810
+ console.error(`
3811
+ ${blocking} error(s) in the project's function files — nothing was written. ` + `Fix them and re-run.`);
3812
+ process.exit(1);
3813
+ }
3814
+ function format(d) {
3815
+ const where = [d.functionName, d.field].filter(Boolean).join(".");
3816
+ const location = [d.file, where ? `(${where})` : ""].filter(Boolean).join(" ");
3817
+ const hint = REMEDIATION[d.code]?.(d);
3818
+ return [location ? `${location}: ` : "", d.message, hint ? ` ${hint}` : ""].join("");
3819
+ }
3820
+ function underscored(file) {
3821
+ if (!file)
3822
+ return "_<name>.ts";
3823
+ const dir = dirname2(file);
3824
+ const renamed = `_${basename2(file)}`;
3825
+ return dir === "." ? renamed : `${dir}/${renamed}`;
3826
+ }
3827
+ function installServerRunner(cwd, serverRunnerTemplatePath = "", packageManager) {
3828
+ const serverRunnerDir = join7(cwd, SERVER_RUNNER_DIR);
2882
3829
  mkdirSync4(serverRunnerDir, { recursive: true });
2883
- if (serverRunnerTemplatePath !== "" && existsSync4(serverRunnerTemplatePath)) {
3830
+ if (serverRunnerTemplatePath !== "" && existsSync5(serverRunnerTemplatePath)) {
2884
3831
  console.log("Copying server-runner ...");
2885
3832
  for (const entry of readdirSync(serverRunnerTemplatePath)) {
2886
- cpSync(join6(serverRunnerTemplatePath, entry), join6(serverRunnerDir, entry), { recursive: true });
3833
+ cpSync(join7(serverRunnerTemplatePath, entry), join7(serverRunnerDir, entry), { recursive: true });
2887
3834
  }
2888
3835
  console.log("server-runner copied in " + serverRunnerDir + ".");
2889
- } else {
2890
- let runtimeVersion = "no-version";
2891
- let honoVersion = "no-version";
2892
- let tsxVersion = "no-version";
2893
- const pkgJson = JSON.parse(readFileSync3(join6(cwd, "package.json"), "utf-8"));
2894
- try {
2895
- const allDeps = { ...pkgJson.dependencies ?? {}, ...pkgJson.devDependencies ?? {} };
2896
- runtimeVersion = allDeps["@uipath/coded-functions-js-runtime"] ?? RUNTIME_VERSION;
2897
- honoVersion = allDeps["@hono/node-server"] ?? HONO_NODE_VERSION;
2898
- tsxVersion = allDeps["tsx"] ?? TSX_VERSION;
2899
- } catch {}
2900
- pkgJson.dependencies = {
2901
- "@uipath/coded-functions-js-runtime": runtimeVersion,
2902
- "@uipath/coreipc": COREIPC_VERSION,
2903
- "@hono/node-server": HONO_NODE_VERSION,
2904
- tsx: tsxVersion,
2905
- "@microsoft/signalr": SIGNALR_VERSION,
2906
- "@jridgewell/trace-mapping": TRACE_MAPPING_VERSION
2907
- };
2908
- writeFileSync5(join6(serverRunnerDir, "package.json"), JSON.stringify(pkgJson, null, 2), "utf-8");
2909
- const npmrc = join6(cwd, ".npmrc");
2910
- if (existsSync4(npmrc)) {
2911
- copyFileSync(npmrc, join6(serverRunnerDir, ".npmrc"));
2912
- }
2913
- console.log("Installing runtime dependencies ...");
2914
- const install = getInstallCommand(false, ["--prefer-offline"]);
2915
- const result = spawnSync3(install.cmd, install.args, {
2916
- cwd: serverRunnerDir,
2917
- stdio: "inherit",
2918
- shell: process.platform === "win32"
2919
- });
2920
- if (result.status !== 0) {
2921
- throw new Error("Failed to install .uipath/server-runner/ dependencies.");
2922
- } else {
2923
- console.log("Runtime dependencies installed.");
2924
- }
3836
+ return;
2925
3837
  }
2926
- if (!existsSync4(join6(cwd, "node_modules"))) {
2927
- console.log("Preparing node_modules in package working folder.");
2928
- let packagesToCopy = ["@uipath/coded-functions-js-sdk"];
2929
- for (let i = 0;i < packagesToCopy.length; i++) {
2930
- const packageName = packagesToCopy[i];
2931
- mkdirSync4(join6(cwd, "node_modules", packageName), { recursive: true });
2932
- for (const entry of readdirSync(join6(serverRunnerDir, "node_modules", packageName))) {
2933
- cpSync(join6(serverRunnerDir, "node_modules", packageName, entry), join6(cwd, "node_modules", packageName, entry), { recursive: true });
2934
- }
3838
+ const pkgJson = JSON.parse(readFileSync4(join7(cwd, "package.json"), "utf-8"));
3839
+ pkgJson.dependencies = buildRunnerDependencies(cwd);
3840
+ writeFileSync6(join7(serverRunnerDir, "package.json"), JSON.stringify(pkgJson, null, 2), "utf-8");
3841
+ console.log("Installing runtime dependencies ...");
3842
+ resolvePackageManager(cwd, packageManager).runInstall(serverRunnerDir, { preferOffline: true });
3843
+ console.log("Runtime dependencies installed.");
3844
+ }
3845
+ function declaresProductionDependency(cwd, packageName) {
3846
+ let parsed;
3847
+ try {
3848
+ parsed = JSON.parse(readFileSync4(join7(cwd, "package.json"), "utf-8"));
3849
+ } catch {
3850
+ return false;
3851
+ }
3852
+ if (typeof parsed !== "object" || parsed === null || !("dependencies" in parsed)) {
3853
+ return false;
3854
+ }
3855
+ const { dependencies } = parsed;
3856
+ if (typeof dependencies !== "object" || dependencies === null) {
3857
+ return false;
3858
+ }
3859
+ return Object.hasOwn(dependencies, packageName);
3860
+ }
3861
+ function installProjectProductionDependencies(cwd, manager = resolvePackageManager(cwd)) {
3862
+ const serverRunnerDir = join7(cwd, SERVER_RUNNER_DIR);
3863
+ console.log("Installing dependencies in package working folder.");
3864
+ manager.runInstall(cwd, { production: true, preferOffline: true });
3865
+ console.log("Preparing node_modules in package working folder.");
3866
+ const packagesToCopy = ["@uipath/coded-functions-js-sdk"];
3867
+ for (const packageName of packagesToCopy) {
3868
+ if (declaresProductionDependency(cwd, packageName)) {
3869
+ continue;
2935
3870
  }
2936
- console.log("Installing dependencies in package working folder.");
2937
- const install = getInstallCommand(true, ["--prefer-offline"]);
2938
- const result = spawnSync3(install.cmd, install.args, {
2939
- cwd,
2940
- stdio: "inherit",
2941
- shell: process.platform === "win32"
2942
- });
2943
- if (result.status !== 0) {
2944
- throw new Error("Failed to install package working folder dependencies.");
2945
- } else {
2946
- console.log("Package working folder dependencies installed.");
3871
+ mkdirSync4(join7(cwd, "node_modules", packageName), { recursive: true });
3872
+ for (const entry of readdirSync(join7(serverRunnerDir, "node_modules", packageName))) {
3873
+ cpSync(join7(serverRunnerDir, "node_modules", packageName, entry), join7(cwd, "node_modules", packageName, entry), { recursive: true });
2947
3874
  }
2948
3875
  }
3876
+ console.log("Package working folder dependencies installed.");
3877
+ }
3878
+ function provisionPackage(cwd, serverRunnerTemplatePath = "", packageManager) {
3879
+ installServerRunner(cwd, serverRunnerTemplatePath, packageManager);
3880
+ if (!existsSync5(join7(cwd, "node_modules"))) {
3881
+ installProjectProductionDependencies(cwd, resolvePackageManager(cwd, packageManager));
3882
+ }
3883
+ }
3884
+ function buildRunnerDependencies(cwd) {
3885
+ let runtimeVersion = RUNTIME_VERSION;
3886
+ let tsxVersion = TSX_VERSION;
3887
+ try {
3888
+ const pkgJson = JSON.parse(readFileSync4(join7(cwd, "package.json"), "utf-8"));
3889
+ const allDeps = { ...pkgJson.dependencies ?? {}, ...pkgJson.devDependencies ?? {} };
3890
+ runtimeVersion = allDeps["@uipath/coded-functions-js-runtime"] ?? RUNTIME_VERSION;
3891
+ tsxVersion = allDeps["tsx"] ?? TSX_VERSION;
3892
+ } catch {}
3893
+ return {
3894
+ "@uipath/coded-functions-js-runtime": runtimeVersion,
3895
+ "@uipath/coreipc": COREIPC_VERSION,
3896
+ tsx: tsxVersion,
3897
+ "@microsoft/signalr": SIGNALR_VERSION,
3898
+ "@jridgewell/trace-mapping": TRACE_MAPPING_VERSION
3899
+ };
2949
3900
  }
2950
3901
  function resolveTsx(cwd) {
2951
- const dbgPkg = join6(cwd, SERVER_RUNNER_DIR, "package.json");
3902
+ const dbgPkg = join7(cwd, SERVER_RUNNER_DIR, "package.json");
2952
3903
  try {
2953
3904
  const tsxPath = createRequire2(dbgPkg).resolve("tsx/cli");
2954
3905
  return ["node", [tsxPath]];
2955
3906
  } catch {
2956
- return ["npx", ["--yes", "tsx"]];
3907
+ throw new Error(`tsx not found in ${SERVER_RUNNER_DIR}. Run 'uipath-functions install-server' and retry.`);
3908
+ }
3909
+ }
3910
+ function resolveTsxLoader(cwd) {
3911
+ const dbgPkg = join7(cwd, SERVER_RUNNER_DIR, "package.json");
3912
+ try {
3913
+ return ["--import", pathToFileURL(createRequire2(dbgPkg).resolve("tsx")).href];
3914
+ } catch {
3915
+ return;
3916
+ }
3917
+ }
3918
+ function resolveDeno() {
3919
+ return process.env.DENO_BINARY ?? (process.platform === "win32" ? "deno.exe" : "deno");
3920
+ }
3921
+ var denoOnPath;
3922
+ function denoAvailable() {
3923
+ denoOnPath ??= spawnSync2(resolveDeno(), ["--version"], {
3924
+ stdio: "ignore",
3925
+ shell: process.platform === "win32"
3926
+ }).status === 0;
3927
+ return denoOnPath;
3928
+ }
3929
+
3930
+ class ProjectNotInstalledError extends Error {
3931
+ constructor(problem, remedyCommand, cwd) {
3932
+ super(remedyCommand !== null ? `${problem}
3933
+ Run '${remedyCommand}' in ${cwd}, then retry.` : `${problem}
3934
+ Then retry in ${cwd}.`);
3935
+ this.name = "ProjectNotInstalledError";
2957
3936
  }
2958
3937
  }
3938
+ function assert(check, cwd) {
3939
+ if (!check.ready) {
3940
+ throw new ProjectNotInstalledError(check.problem ?? "Project is not installed.", check.remedyCommand, cwd);
3941
+ }
3942
+ }
3943
+ function assertDependenciesInstalled(cwd) {
3944
+ assert(checkDependenciesInstalled(cwd), cwd);
3945
+ }
3946
+ function assertReadyToPackage(cwd) {
3947
+ assert(checkDependenciesInstalled(cwd), cwd);
3948
+ assert(checkLockCurrent(cwd), cwd);
3949
+ }
2959
3950
  function freePort(port) {
2960
3951
  try {
2961
3952
  let pid = null;
@@ -3058,17 +4049,17 @@ var SIGNAL_READY_DENO = `async function signalReady() {
3058
4049
  var FUNCTIONS_DIR = "functions";
3059
4050
  var SUPPORTED_EXTS = new Set([".ts", ".js"]);
3060
4051
  function syncFunctionsMap(cwd) {
3061
- const uipathJsonPath = join7(cwd, "uipath.json");
3062
- const functionsDir = join7(cwd, FUNCTIONS_DIR);
3063
- if (!existsSync5(uipathJsonPath) || !existsSync5(functionsDir))
4052
+ const uipathJsonPath = join8(cwd, "uipath.json");
4053
+ const functionsDir = join8(cwd, FUNCTIONS_DIR);
4054
+ if (!existsSync6(uipathJsonPath) || !existsSync6(functionsDir))
3064
4055
  return false;
3065
4056
  const discovered = discoverFunctions(functionsDir);
3066
- const uipathJson = JSON.parse(readFileSync4(uipathJsonPath, "utf-8"));
4057
+ const uipathJson = JSON.parse(readFileSync5(uipathJsonPath, "utf-8"));
3067
4058
  const existing = uipathJson.functions ?? {};
3068
4059
  if (mapsEqual(existing, discovered))
3069
4060
  return false;
3070
4061
  uipathJson.functions = Object.fromEntries(Object.keys(discovered).sort().map((k) => [k, discovered[k]]));
3071
- writeFileSync6(uipathJsonPath, JSON.stringify(uipathJson, null, 2) + `
4062
+ writeFileSync7(uipathJsonPath, JSON.stringify(uipathJson, null, 2) + `
3072
4063
  `, "utf-8");
3073
4064
  return true;
3074
4065
  }
@@ -3077,7 +4068,7 @@ function discoverFunctions(functionsDir) {
3077
4068
  for (const entry of readdirSync2(functionsDir, { withFileTypes: true })) {
3078
4069
  if (!isFunctionFile(entry))
3079
4070
  continue;
3080
- const ext = extname2(entry.name);
4071
+ const ext = extname3(entry.name);
3081
4072
  const key = entry.name.slice(0, -ext.length);
3082
4073
  discovered[key] = `${FUNCTIONS_DIR}/${entry.name}:default`;
3083
4074
  }
@@ -3087,7 +4078,7 @@ function isFunctionFile(entry) {
3087
4078
  if (!entry.isFile() || entry.name.startsWith("_") || entry.name.endsWith(".d.ts")) {
3088
4079
  return false;
3089
4080
  }
3090
- return SUPPORTED_EXTS.has(extname2(entry.name));
4081
+ return SUPPORTED_EXTS.has(extname3(entry.name));
3091
4082
  }
3092
4083
  function mapsEqual(a, b) {
3093
4084
  const ak = Object.keys(a);
@@ -3098,29 +4089,40 @@ function registerServeCommand(program2) {
3098
4089
  program2.command("serve").description("Start local function server with hot reload.").option("--runtime <runtime>", "Runtime: node (default) or deno", "node").option("--port <port>", "Port to listen on", String(DEFAULT_PORT)).option("--production", "Run under production context and skip .uipath/server-runner install if already exists; also skip freePort check.").action(async (opts) => {
3099
4090
  const cwd = resolve3(".");
3100
4091
  const port = parseInt(opts.port, 10) || DEFAULT_PORT;
3101
- const uipathJsonPath = join8(cwd, "uipath.json");
3102
- if (!existsSync6(uipathJsonPath)) {
4092
+ const uipathJsonPath = join9(cwd, "uipath.json");
4093
+ if (!existsSync7(uipathJsonPath)) {
3103
4094
  console.error("No uipath.json found. Run 'uipath-functions init' first.");
3104
4095
  process.exit(1);
3105
4096
  }
3106
4097
  if (syncFunctionsMap(cwd)) {
3107
4098
  console.log("Updated functions map in uipath.json.");
3108
4099
  }
3109
- const uipathJson = JSON.parse(readFileSync5(uipathJsonPath, "utf-8"));
4100
+ const uipathJson = JSON.parse(readFileSync6(uipathJsonPath, "utf-8"));
3110
4101
  if (!uipathJson.functions || Object.keys(uipathJson.functions).length === 0) {
3111
4102
  console.error("No functions defined in uipath.json. Add at least one function.");
3112
4103
  process.exit(1);
3113
4104
  }
3114
- const skipInstall = opts.production === true && existsSync6(join8(cwd, SERVER_RUNNER_DIR));
4105
+ if (opts.production !== true) {
4106
+ try {
4107
+ assertDependenciesInstalled(cwd);
4108
+ } catch (err) {
4109
+ console.error(err instanceof Error ? err.message : String(err));
4110
+ process.exit(1);
4111
+ }
4112
+ }
4113
+ const extraction = extractProject(uipathJson.functions, cwd);
4114
+ if (opts.production !== true)
4115
+ reportDiagnosticsOrExit(extraction.diagnostics);
4116
+ const skipInstall = opts.production === true && existsSync7(join9(cwd, SERVER_RUNNER_DIR));
3115
4117
  if (!skipInstall) {
3116
4118
  try {
3117
- setupRunDependencies(cwd);
4119
+ installServerRunner(cwd);
3118
4120
  } catch (err) {
3119
4121
  console.error(err instanceof Error ? err.message : String(err));
3120
4122
  process.exit(1);
3121
4123
  }
3122
4124
  }
3123
- const derived = deriveMarkerContracts(uipathJson.functions, cwd);
4125
+ const derived = toDerivedContracts(extraction.functions);
3124
4126
  const aggregatorPath = generateAggregator(uipathJson.functions, cwd, "serve", derived);
3125
4127
  if (opts.production !== true) {
3126
4128
  freePort(port);
@@ -3129,42 +4131,67 @@ function registerServeCommand(program2) {
3129
4131
  if (opts.production !== true) {
3130
4132
  process.env[DESIGN_TIME_ENV] = "1";
3131
4133
  }
4134
+ const production = opts.production === true;
3132
4135
  if (opts.runtime === "deno") {
3133
- serveDeno(cwd, port, aggregatorPath);
4136
+ serveDeno(cwd, port, aggregatorPath, production);
3134
4137
  } else {
3135
- serveNode(cwd, port, aggregatorPath);
4138
+ serveNode(cwd, port, aggregatorPath, production);
3136
4139
  }
3137
4140
  });
3138
4141
  }
3139
- function serveNode(cwd, port, aggregatorPath) {
3140
- const nodeEntryPath = join8(cwd, SERVER_RUNNER_DIR, "serve-node.ts");
3141
- const aggregatorFile = basename(aggregatorPath);
3142
- writeFileSync7(nodeEntryPath, `import { serve } from "@hono/node-server";
4142
+ function tsxServeArgs(entryPath, opts) {
4143
+ return [
4144
+ ...opts.production ? [] : ["watch"],
4145
+ ...opts.envFile ? [`--env-file=${opts.envFile}`] : [],
4146
+ entryPath
4147
+ ];
4148
+ }
4149
+ function denoServeArgs(entryPath, opts) {
4150
+ return [
4151
+ "run",
4152
+ "--allow-env",
4153
+ "--allow-net",
4154
+ "--allow-read",
4155
+ "--allow-write",
4156
+ ...opts.production ? [] : ["--watch"],
4157
+ ...opts.envFile ? [`--env-file=${opts.envFile}`] : [],
4158
+ entryPath
4159
+ ];
4160
+ }
4161
+ function serveNode(cwd, port, aggregatorPath, production) {
4162
+ const nodeEntryPath = join9(cwd, SERVER_RUNNER_DIR, "serve-node.ts");
4163
+ const aggregatorFile = basename3(aggregatorPath);
4164
+ writeFileSync8(nodeEntryPath, `import { serveNode } from "@uipath/coded-functions-js-runtime/node";
3143
4165
  ` + `import app from "./${aggregatorFile}";
3144
4166
  ` + `const port = Number(process.env.HTTP_SERVER_LISTEN_PORT ?? ${port});
3145
4167
  ` + `console.log("http://localhost:" + port);
3146
4168
  ` + `${SIGNAL_READY_NODE}
3147
- ` + `serve(
3148
- {
3149
- fetch: app.fetch,
3150
- port,
3151
- },
3152
- (info) => {
3153
- console.log(\`JS function node server listening on http://127.0.0.1:\${info.port}\`);
3154
- signalReady();
3155
- });
4169
+ ` + `serveNode(app, port, (port) => {
4170
+ console.log(\`JS function node server listening on http://127.0.0.1:\${port}\`);
4171
+ signalReady();
4172
+ });
3156
4173
  `, "utf-8");
3157
- const envFile = join8(cwd, ".env");
3158
- const envFileArgs = existsSync6(envFile) ? [`--env-file=${envFile}`] : [];
3159
- const [bin, tsxPrefix] = resolveTsx(cwd);
3160
- const proc = spawn(bin, [...tsxPrefix, "watch", ...envFileArgs, nodeEntryPath], {
4174
+ const envFile = join9(cwd, ".env");
4175
+ let bin;
4176
+ let tsxPrefix;
4177
+ try {
4178
+ [bin, tsxPrefix] = resolveTsx(cwd);
4179
+ } catch (err) {
4180
+ console.error(err instanceof Error ? err.message : String(err));
4181
+ process.exit(1);
4182
+ }
4183
+ const tsxArgs = tsxServeArgs(nodeEntryPath, {
4184
+ production,
4185
+ envFile: existsSync7(envFile) ? envFile : undefined
4186
+ });
4187
+ const proc = spawn(bin, [...tsxPrefix, ...tsxArgs], {
3161
4188
  cwd,
3162
4189
  env: { ...process.env, HTTP_SERVER_LISTEN_PORT: String(port) },
3163
4190
  stdio: "inherit"
3164
4191
  });
3165
4192
  proc.on("error", (err) => {
3166
4193
  if (err.code === "ENOENT")
3167
- console.error("npx/tsx not found. Run 'uipath-functions setup'.");
4194
+ console.error("node not found. Run 'uipath-functions setup'.");
3168
4195
  else
3169
4196
  console.error(err);
3170
4197
  process.exit(1);
@@ -3172,9 +4199,9 @@ function serveNode(cwd, port, aggregatorPath) {
3172
4199
  proc.on("exit", (code) => process.exit(code ?? 0));
3173
4200
  }
3174
4201
  function writeDenoServeEntry(cwd, port, aggregatorPath) {
3175
- const denoEntryPath = join8(cwd, SERVER_RUNNER_DIR, "serve-deno.ts");
3176
- const aggregatorFile = basename(aggregatorPath);
3177
- writeFileSync7(denoEntryPath, `import app from "./${aggregatorFile}";
4202
+ const denoEntryPath = join9(cwd, SERVER_RUNNER_DIR, "serve-deno.ts");
4203
+ const aggregatorFile = basename3(aggregatorPath);
4204
+ writeFileSync8(denoEntryPath, `import app from "./${aggregatorFile}";
3178
4205
  ` + `const port = Number(Deno.env.get("HTTP_SERVER_LISTEN_PORT") ?? ${port});
3179
4206
  ` + `console.log("http://localhost:" + port);
3180
4207
  ` + `${SIGNAL_READY_DENO}
@@ -3184,24 +4211,18 @@ function writeDenoServeEntry(cwd, port, aggregatorPath) {
3184
4211
  onListen: () => {
3185
4212
  console.log(\`JS function deno server listening on http://127.0.0.1:\${port}\`);
3186
4213
  signalReady();
3187
- }
3188
- }, app.fetch);
3189
- `, "utf-8");
3190
- return denoEntryPath;
3191
- }
3192
- function serveDeno(cwd, port, aggregatorPath) {
3193
- const denoEntryPath = writeDenoServeEntry(cwd, port, aggregatorPath);
3194
- const denoArgs = [
3195
- "run",
3196
- "--allow-env",
3197
- "--allow-net",
3198
- "--allow-read",
3199
- "--allow-write",
3200
- "--watch",
3201
- ...existsSync6(join8(cwd, ".env")) ? ["--env-file=.env"] : [],
3202
- denoEntryPath
3203
- ];
3204
- const deno = process.env.DENO_BINARY ?? (process.platform === "win32" ? "deno.exe" : "deno");
4214
+ }
4215
+ }, app.fetch);
4216
+ `, "utf-8");
4217
+ return denoEntryPath;
4218
+ }
4219
+ function serveDeno(cwd, port, aggregatorPath, production) {
4220
+ const denoEntryPath = writeDenoServeEntry(cwd, port, aggregatorPath);
4221
+ const denoArgs = denoServeArgs(denoEntryPath, {
4222
+ production,
4223
+ envFile: existsSync7(join9(cwd, ".env")) ? ".env" : undefined
4224
+ });
4225
+ const deno = resolveDeno();
3205
4226
  const proc = spawn(deno, denoArgs, {
3206
4227
  cwd,
3207
4228
  env: { ...process.env, HTTP_SERVER_LISTEN_PORT: String(port) },
@@ -3312,7 +4333,25 @@ for (i = 0;i < 32; ++i)
3312
4333
  fdt[i] = 5;
3313
4334
  var i;
3314
4335
  var flm = /* @__PURE__ */ hMap(flt, 9, 0);
4336
+ var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
3315
4337
  var fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
4338
+ var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
4339
+ var max = function(a) {
4340
+ var m = a[0];
4341
+ for (var i2 = 1;i2 < a.length; ++i2) {
4342
+ if (a[i2] > m)
4343
+ m = a[i2];
4344
+ }
4345
+ return m;
4346
+ };
4347
+ var bits = function(d, p, m) {
4348
+ var o = p / 8 | 0;
4349
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
4350
+ };
4351
+ var bits16 = function(d, p) {
4352
+ var o = p / 8 | 0;
4353
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
4354
+ };
3316
4355
  var shft = function(p) {
3317
4356
  return (p + 7) / 8 | 0;
3318
4357
  };
@@ -3348,6 +4387,147 @@ var err = function(ind, msg, nt) {
3348
4387
  throw e;
3349
4388
  return e;
3350
4389
  };
4390
+ var inflt = function(dat, st, buf, dict) {
4391
+ var sl = dat.length, dl = dict ? dict.length : 0;
4392
+ if (!sl || st.f && !st.l)
4393
+ return buf || new u8(0);
4394
+ var noBuf = !buf;
4395
+ var resize = noBuf || st.i != 2;
4396
+ var noSt = st.i;
4397
+ if (noBuf)
4398
+ buf = new u8(sl * 3);
4399
+ var cbuf = function(l2) {
4400
+ var bl = buf.length;
4401
+ if (l2 > bl) {
4402
+ var nbuf = new u8(Math.max(bl * 2, l2));
4403
+ nbuf.set(buf);
4404
+ buf = nbuf;
4405
+ }
4406
+ };
4407
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
4408
+ var tbts = sl * 8;
4409
+ do {
4410
+ if (!lm) {
4411
+ final = bits(dat, pos, 1);
4412
+ var type = bits(dat, pos + 1, 3);
4413
+ pos += 3;
4414
+ if (!type) {
4415
+ var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
4416
+ if (t > sl) {
4417
+ if (noSt)
4418
+ err(0);
4419
+ break;
4420
+ }
4421
+ if (resize)
4422
+ cbuf(bt + l);
4423
+ buf.set(dat.subarray(s, t), bt);
4424
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
4425
+ continue;
4426
+ } else if (type == 1)
4427
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
4428
+ else if (type == 2) {
4429
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
4430
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
4431
+ pos += 14;
4432
+ var ldt = new u8(tl);
4433
+ var clt = new u8(19);
4434
+ for (var i2 = 0;i2 < hcLen; ++i2) {
4435
+ clt[clim[i2]] = bits(dat, pos + i2 * 3, 7);
4436
+ }
4437
+ pos += hcLen * 3;
4438
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
4439
+ var clm = hMap(clt, clb, 1);
4440
+ for (var i2 = 0;i2 < tl; ) {
4441
+ var r = clm[bits(dat, pos, clbmsk)];
4442
+ pos += r & 15;
4443
+ var s = r >> 4;
4444
+ if (s < 16) {
4445
+ ldt[i2++] = s;
4446
+ } else {
4447
+ var c = 0, n = 0;
4448
+ if (s == 16)
4449
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i2 - 1];
4450
+ else if (s == 17)
4451
+ n = 3 + bits(dat, pos, 7), pos += 3;
4452
+ else if (s == 18)
4453
+ n = 11 + bits(dat, pos, 127), pos += 7;
4454
+ while (n--)
4455
+ ldt[i2++] = c;
4456
+ }
4457
+ }
4458
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
4459
+ lbt = max(lt);
4460
+ dbt = max(dt);
4461
+ lm = hMap(lt, lbt, 1);
4462
+ dm = hMap(dt, dbt, 1);
4463
+ } else
4464
+ err(1);
4465
+ if (pos > tbts) {
4466
+ if (noSt)
4467
+ err(0);
4468
+ break;
4469
+ }
4470
+ }
4471
+ if (resize)
4472
+ cbuf(bt + 131072);
4473
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
4474
+ var lpos = pos;
4475
+ for (;; lpos = pos) {
4476
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
4477
+ pos += c & 15;
4478
+ if (pos > tbts) {
4479
+ if (noSt)
4480
+ err(0);
4481
+ break;
4482
+ }
4483
+ if (!c)
4484
+ err(2);
4485
+ if (sym < 256)
4486
+ buf[bt++] = sym;
4487
+ else if (sym == 256) {
4488
+ lpos = pos, lm = null;
4489
+ break;
4490
+ } else {
4491
+ var add = sym - 254;
4492
+ if (sym > 264) {
4493
+ var i2 = sym - 257, b = fleb[i2];
4494
+ add = bits(dat, pos, (1 << b) - 1) + fl[i2];
4495
+ pos += b;
4496
+ }
4497
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
4498
+ if (!d)
4499
+ err(3);
4500
+ pos += d & 15;
4501
+ var dt = fd[dsym];
4502
+ if (dsym > 3) {
4503
+ var b = fdeb[dsym];
4504
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
4505
+ }
4506
+ if (pos > tbts) {
4507
+ if (noSt)
4508
+ err(0);
4509
+ break;
4510
+ }
4511
+ if (resize)
4512
+ cbuf(bt + 131072);
4513
+ var end = bt + add;
4514
+ if (bt < dt) {
4515
+ var shift = dl - dt, dend = Math.min(dt, end);
4516
+ if (shift + bt < 0)
4517
+ err(3);
4518
+ for (;bt < dend; ++bt)
4519
+ buf[bt] = dict[shift + bt];
4520
+ }
4521
+ for (;bt < end; ++bt)
4522
+ buf[bt] = buf[bt - dt];
4523
+ }
4524
+ }
4525
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
4526
+ if (lm)
4527
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
4528
+ } while (!final);
4529
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
4530
+ };
3351
4531
  var wbits = function(d, p, v) {
3352
4532
  v <<= p & 7;
3353
4533
  var o = p / 8 | 0;
@@ -3695,6 +4875,15 @@ var mrg = function(a, b) {
3695
4875
  o[k] = b[k];
3696
4876
  return o;
3697
4877
  };
4878
+ var b2 = function(d, b) {
4879
+ return d[b] | d[b + 1] << 8;
4880
+ };
4881
+ var b4 = function(d, b) {
4882
+ return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
4883
+ };
4884
+ var b8 = function(d, b) {
4885
+ return b4(d, b) + b4(d, b + 4) * 4294967296;
4886
+ };
3698
4887
  var wbytes = function(d, b, v) {
3699
4888
  for (;v; ++b)
3700
4889
  d[b] = v, v >>>= 8;
@@ -3702,6 +4891,9 @@ var wbytes = function(d, b, v) {
3702
4891
  function deflateSync(data, opts) {
3703
4892
  return dopt(data, opts || {}, 0, 0);
3704
4893
  }
4894
+ function inflateSync(data, opts) {
4895
+ return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
4896
+ }
3705
4897
  var fltn = function(d, p, t, o) {
3706
4898
  for (var k in d) {
3707
4899
  var val = d[k], n = p + k, op = o;
@@ -3722,6 +4914,22 @@ try {
3722
4914
  td.decode(et, { stream: true });
3723
4915
  tds = 1;
3724
4916
  } catch (e) {}
4917
+ var dutf8 = function(d) {
4918
+ for (var r = "", i2 = 0;; ) {
4919
+ var c = d[i2++];
4920
+ var eb = (c > 127) + (c > 223) + (c > 239);
4921
+ if (i2 + eb > d.length)
4922
+ return { s: r, r: slc(d, i2 - 1) };
4923
+ if (!eb)
4924
+ r += String.fromCharCode(c);
4925
+ else if (eb == 3) {
4926
+ c = ((c & 15) << 18 | (d[i2++] & 63) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023);
4927
+ } else if (eb & 1)
4928
+ r += String.fromCharCode((c & 31) << 6 | d[i2++] & 63);
4929
+ else
4930
+ r += String.fromCharCode((c & 15) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63);
4931
+ }
4932
+ };
3725
4933
  function strToU8(str, latin1) {
3726
4934
  if (latin1) {
3727
4935
  var ar_1 = new u8(str.length);
@@ -3755,6 +4963,48 @@ function strToU8(str, latin1) {
3755
4963
  }
3756
4964
  return slc(ar, 0, ai);
3757
4965
  }
4966
+ function strFromU8(dat, latin1) {
4967
+ if (latin1) {
4968
+ var r = "";
4969
+ for (var i2 = 0;i2 < dat.length; i2 += 16384)
4970
+ r += String.fromCharCode.apply(null, dat.subarray(i2, i2 + 16384));
4971
+ return r;
4972
+ } else if (td) {
4973
+ return td.decode(dat);
4974
+ } else {
4975
+ var _a2 = dutf8(dat), s = _a2.s, r = _a2.r;
4976
+ if (r.length)
4977
+ err(8);
4978
+ return s;
4979
+ }
4980
+ }
4981
+ var slzh = function(d, b) {
4982
+ return b + 30 + b2(d, b + 26) + b2(d, b + 28);
4983
+ };
4984
+ var zh = function(d, b, z) {
4985
+ var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;
4986
+ var _a2 = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a2[0], su = _a2[1], off = _a2[2];
4987
+ return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off];
4988
+ };
4989
+ var z64hs = function(d, b, l, z, sc, su, off) {
4990
+ var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l;
4991
+ var nf = nsc + nsu + noff;
4992
+ if (z && nf) {
4993
+ for (;b + 4 < e; b += 4 + b2(d, b + 2)) {
4994
+ if (b2(d, b) == 1) {
4995
+ return [
4996
+ nsc ? b8(d, b + 4 + 8 * nsu) : sc,
4997
+ nsu ? b8(d, b + 4) : su,
4998
+ noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off,
4999
+ 1
5000
+ ];
5001
+ }
5002
+ }
5003
+ if (z < 2)
5004
+ err(13);
5005
+ }
5006
+ return [sc, su, off, 0];
5007
+ };
3758
5008
  var exfl = function(ex) {
3759
5009
  var le = 0;
3760
5010
  if (ex) {
@@ -3856,6 +5106,46 @@ function zipSync(data, opts) {
3856
5106
  wzf(out, o, files.length, cdl, oe);
3857
5107
  return out;
3858
5108
  }
5109
+ function unzipSync(data, opts) {
5110
+ var files = {};
5111
+ var e = data.length - 22;
5112
+ for (;b4(data, e) != 101010256; --e) {
5113
+ if (!e || data.length - e > 65558)
5114
+ err(13);
5115
+ }
5116
+ var c = b2(data, e + 8);
5117
+ if (!c)
5118
+ return {};
5119
+ var o = b4(data, e + 16);
5120
+ var z = b4(data, e - 20) == 117853008;
5121
+ if (z) {
5122
+ var ze = b4(data, e - 12);
5123
+ z = b4(data, ze) == 101075792;
5124
+ if (z) {
5125
+ c = b4(data, ze + 32);
5126
+ o = b4(data, ze + 48);
5127
+ }
5128
+ }
5129
+ var fltr = opts && opts.filter;
5130
+ for (var i2 = 0;i2 < c; ++i2) {
5131
+ var _a2 = zh(data, o, z), c_2 = _a2[0], sc = _a2[1], su = _a2[2], fn = _a2[3], no = _a2[4], off = _a2[5], b = slzh(data, off);
5132
+ o = no;
5133
+ if (!fltr || fltr({
5134
+ name: fn,
5135
+ size: sc,
5136
+ originalSize: su,
5137
+ compression: c_2
5138
+ })) {
5139
+ if (!c_2)
5140
+ files[fn] = slc(data, b, b + sc);
5141
+ else if (c_2 == 8)
5142
+ files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
5143
+ else
5144
+ err(14, "unknown compression type " + c_2);
5145
+ }
5146
+ }
5147
+ return files;
5148
+ }
3859
5149
  var isDockerCached;
3860
5150
  function hasDockerEnv() {
3861
5151
  try {
@@ -4427,324 +5717,91 @@ class NodeFileSystem {
4427
5717
  }
4428
5718
  return await fs6.readFile(path3);
4429
5719
  } catch (error) {
4430
- if (this.isEnoent(error))
4431
- return null;
4432
- throw error;
4433
- }
4434
- }
4435
- async writeFile(filePath, data) {
4436
- const dir = path2.dirname(filePath);
4437
- if (dir) {
4438
- await fs6.mkdir(dir, { recursive: true });
4439
- }
4440
- await fs6.writeFile(filePath, data);
4441
- }
4442
- async readdir(dirPath) {
4443
- try {
4444
- return await fs6.readdir(dirPath);
4445
- } catch (error) {
4446
- if (this.isEnoent(error))
4447
- return [];
4448
- throw error;
4449
- }
4450
- }
4451
- async stat(filePath) {
4452
- try {
4453
- const stats = await fs6.stat(filePath);
4454
- return {
4455
- isFile: () => stats.isFile(),
4456
- isDirectory: () => stats.isDirectory(),
4457
- size: stats.size,
4458
- mtimeMs: stats.mtimeMs
4459
- };
4460
- } catch (error) {
4461
- if (this.isEnoent(error))
4462
- return null;
4463
- throw error;
4464
- }
4465
- }
4466
- async exists(filePath) {
4467
- return existsSync7(filePath);
4468
- }
4469
- async mkdir(dirPath) {
4470
- await fs6.mkdir(dirPath, { recursive: true });
4471
- }
4472
- async rm(filePath) {
4473
- await fs6.rm(filePath, { recursive: true, force: true });
4474
- }
4475
- async rename(oldPath, newPath) {
4476
- await fs6.rename(oldPath, newPath);
4477
- }
4478
- async getTempDir() {
4479
- return await fs6.mkdtemp(path2.join(os2.tmpdir(), "uipath-fs-"));
4480
- }
4481
- async copyDirectory(sourcePath, destPath) {
4482
- const sourceStats = await this.stat(sourcePath);
4483
- if (!sourceStats) {
4484
- throw new Error(`Source directory does not exist: ${sourcePath}`);
4485
- }
4486
- if (!sourceStats.isDirectory()) {
4487
- throw new Error(`Source path is not a directory: ${sourcePath}`);
4488
- }
4489
- await this.mkdir(destPath);
4490
- const entries = await this.readdir(sourcePath);
4491
- for (const entry of entries) {
4492
- const srcEntry = path2.join(sourcePath, entry);
4493
- const destEntry = path2.join(destPath, entry);
4494
- const entryStats = await this.stat(srcEntry);
4495
- if (!entryStats)
4496
- continue;
4497
- if (entryStats.isDirectory()) {
4498
- await this.copyDirectory(srcEntry, destEntry);
4499
- } else if (entryStats.isFile()) {
4500
- const content = await this.readFile(srcEntry);
4501
- if (content !== null) {
4502
- await this.writeFile(destEntry, content);
4503
- }
4504
- }
4505
- }
4506
- }
4507
- isEnoent(error) {
4508
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
4509
- }
4510
- }
4511
- var fsInstance = new NodeFileSystem;
4512
- var getFileSystem = () => {
4513
- return fsInstance;
4514
- };
4515
- var EXCLUDED_NAMES = new Set([
4516
- "node_modules",
4517
- ".git",
4518
- ".env",
4519
- ".deno",
4520
- "dist",
4521
- ".uipath"
4522
- ]);
4523
- var EXCLUDED_EXTENSIONS = [".nupkg"];
4524
- var NPMRC = ".npmrc";
4525
- var UIPATH_SCOPE = "@uipath:";
4526
- var CREDENTIAL_KEYS = ["_authtoken", "_auth", "_password"];
4527
- function isComment(line) {
4528
- return line === "" || line.startsWith("#") || line.startsWith(";");
4529
- }
4530
- function isOurs(line) {
4531
- const trimmed = line.trim();
4532
- if (isComment(trimmed))
4533
- return false;
4534
- const key = (trimmed.split("=")[0] ?? "").trim().toLowerCase();
4535
- return key.startsWith(UIPATH_SCOPE) || CREDENTIAL_KEYS.some((c) => key.endsWith(c));
4536
- }
4537
- function sanitizeNpmrc(content) {
4538
- const kept = content.split(/\r?\n/).filter((line) => !isOurs(line));
4539
- return kept.some((line) => !isComment(line.trim())) ? kept.join(`
4540
- `) : null;
4541
- }
4542
- var LOCK_FILES = new Set(["bun.lock", "package-lock.json", "deno.lock", "yarn.lock"]);
4543
- async function buildFunctionsPackage(fs7, options) {
4544
- const { projectPath, outputPath, projectStorageId } = options;
4545
- const contentPath = fs7.path.join(outputPath, "content");
4546
- await fs7.mkdir(outputPath);
4547
- await fs7.mkdir(contentPath);
4548
- const uipathJsonRaw = await fs7.readFile(fs7.path.join(projectPath, "uipath.json"), "utf-8");
4549
- if (!uipathJsonRaw) {
4550
- throw new Error("uipath.json not found. Run 'uipath-functions init' first.");
4551
- }
4552
- const uipathJson = JSON.parse(uipathJsonRaw);
4553
- const entryPointsRaw = await fs7.readFile(fs7.path.join(projectPath, "entry-points.json"), "utf-8");
4554
- if (!entryPointsRaw) {
4555
- throw new Error("entry-points.json not found. Run 'uipath-functions pack' to generate it.");
4556
- }
4557
- const entryPoints = JSON.parse(entryPointsRaw);
4558
- const bindingsRaw = await fs7.readFile(fs7.path.join(projectPath, "bindings_v2.json"), "utf-8");
4559
- if (!bindingsRaw) {
4560
- throw new Error("bindings_v2.json not found. Run 'uipath-functions pack' to generate it.");
4561
- }
4562
- const bindings = JSON.parse(bindingsRaw);
4563
- const packageJsonRaw = await fs7.readFile(fs7.path.join(projectPath, "package.json"), "utf-8");
4564
- const packageDependencies = packageJsonRaw ? JSON.parse(packageJsonRaw).dependencies ?? {} : {};
4565
- const targetRuntime = detectRuntime(uipathJson.functions);
4566
- const includeLockFile = options.excludeLockFile ? false : uipathJson.packOptions?.includeLockFile ?? true;
4567
- await copyProjectFiles(fs7, projectPath, contentPath, includeLockFile, uipathJson.packOptions);
4568
- const operateJson = {
4569
- $schema: "https://cloud.uipath.com/draft/2024-12/operate",
4570
- projectId: projectStorageId,
4571
- contentType: "function",
4572
- targetFramework: "Portable",
4573
- targetRuntime,
4574
- runtimeOptions: {
4575
- requiresUserInteraction: false,
4576
- isAttended: false
4577
- },
4578
- deploymentOptions: {
4579
- generateSlug: true
4580
- },
4581
- dependencies: packageDependencies
4582
- };
4583
- await fs7.writeFile(fs7.path.join(contentPath, "operate.json"), JSON.stringify(operateJson, null, 2));
4584
- await fs7.writeFile(fs7.path.join(contentPath, "entry-points.json"), JSON.stringify(entryPoints, null, 2));
4585
- await fs7.writeFile(fs7.path.join(contentPath, "bindings_v2.json"), JSON.stringify(bindings, null, 2));
4586
- const packageDescriptor = {
4587
- $schema: "https://cloud.uipath.com/draft/2024-12/package-descriptor",
4588
- files: {
4589
- "operate.json": "content/operate.json",
4590
- "entry-points.json": "content/entry-points.json",
4591
- "bindings.json": "content/bindings_v2.json"
4592
- }
4593
- };
4594
- for (const ep of entryPoints.entryPoints) {
4595
- const fnEntry = uipathJson.functions?.[ep.filePath];
4596
- const filePath = fnEntry ? fnEntry.split(":")[0] ?? ep.filePath : ep.filePath;
4597
- packageDescriptor.files[ep.filePath] = `${filePath}`;
4598
- }
4599
- await fs7.writeFile(fs7.path.join(contentPath, "package-descriptor.json"), JSON.stringify(packageDescriptor, null, 2));
4600
- }
4601
- function detectRuntime(functions) {
4602
- if (!functions)
4603
- return "javascript";
4604
- const first = Object.values(functions)[0];
4605
- if (!first)
4606
- return "javascript";
4607
- const filePath = first.split(":")[0] ?? "";
4608
- const ext = filePath.slice(filePath.lastIndexOf("."));
4609
- if (ext === ".py")
4610
- return "python";
4611
- return "javascript";
4612
- }
4613
- async function copyProjectFiles(fs7, sourcePath, destPath, includeLockFile, packOptions) {
4614
- const extraExcludedDirs = new Set(packOptions?.directoriesExcluded ?? []);
4615
- const extraExcludedFiles = new Set(packOptions?.filesExcluded ?? []);
4616
- async function walk(src, dest) {
4617
- await fs7.mkdir(dest);
4618
- const entries = await fs7.readdir(src);
4619
- for (const name of entries) {
4620
- if (EXCLUDED_NAMES.has(name))
4621
- continue;
4622
- if (extraExcludedDirs.has(name))
4623
- continue;
4624
- if (extraExcludedFiles.has(name))
4625
- continue;
4626
- if (EXCLUDED_EXTENSIONS.some((ext) => name.endsWith(ext)))
4627
- continue;
4628
- if (!includeLockFile && LOCK_FILES.has(name))
4629
- continue;
4630
- const srcEntry = fs7.path.join(src, name);
4631
- const destEntry = fs7.path.join(dest, name);
4632
- const stat2 = await fs7.stat(srcEntry);
4633
- if (stat2?.isDirectory()) {
4634
- await walk(srcEntry, destEntry);
4635
- } else if (name === NPMRC) {
4636
- const sanitized = sanitizeNpmrc(await fs7.readFile(srcEntry, "utf-8") ?? "");
4637
- if (sanitized !== null)
4638
- await fs7.writeFile(destEntry, sanitized);
4639
- } else if (stat2?.isFile()) {
4640
- const content = await fs7.readFile(srcEntry);
4641
- if (content)
4642
- await fs7.writeFile(destEntry, content);
4643
- }
5720
+ if (this.isEnoent(error))
5721
+ return null;
5722
+ throw error;
4644
5723
  }
4645
5724
  }
4646
- await walk(sourcePath, destPath);
4647
- }
4648
- var CONSUMER_COMPILER_OPTIONS2 = {
4649
- target: ts3.ScriptTarget.ES2020,
4650
- module: ts3.ModuleKind.ESNext,
4651
- moduleResolution: ts3.ModuleResolutionKind.Bundler,
4652
- allowImportingTsExtensions: true,
4653
- allowJs: true,
4654
- strict: true,
4655
- skipLibCheck: true,
4656
- noEmit: true
4657
- };
4658
- var DIAGNOSTIC_CODES2 = {
4659
- UNSUPPORTED_VALIDATOR: "unsupported-validator",
4660
- UNSUPPORTED_TYPE: "unsupported-type",
4661
- NON_STATIC_LITERAL: "non-static-literal",
4662
- MISSING_TYPE_ARGUMENT: "missing-type-argument",
4663
- AMBIGUOUS_ROUTE: "ambiguous-route",
4664
- MULTIPLE_FUNCTIONS_PER_FILE: "multiple-functions-per-file",
4665
- DEPRECATED_MARKER: "deprecated-marker"
4666
- };
4667
- function newId() {
4668
- return globalThis.crypto.randomUUID();
4669
- }
4670
- function buildEntryPointsDoc(functions, existing, filePathPrefix = "content/") {
4671
- const functionIds = new Map;
4672
- const transactionRoots = new Set;
4673
- const preserved = [];
4674
- for (const ep of existing?.entryPoints ?? []) {
4675
- if (ep.type === "function") {
4676
- functionIds.set(ep.filePath, ep.uniqueId);
4677
- if (ep.isTransactionRoot === true) {
4678
- transactionRoots.add(ep.filePath);
4679
- }
4680
- } else {
4681
- preserved.push(ep);
5725
+ async writeFile(filePath, data) {
5726
+ const dir = path2.dirname(filePath);
5727
+ if (dir) {
5728
+ await fs6.mkdir(dir, { recursive: true });
4682
5729
  }
5730
+ await fs6.writeFile(filePath, data);
4683
5731
  }
4684
- const functionEntries = functions.map((fn) => {
4685
- const filePath = filePathPrefix + (fn.functionPath ?? "");
4686
- return {
4687
- filePath,
4688
- uniqueId: functionIds.get(filePath) ?? newId(),
4689
- type: "function",
4690
- input: fn.input ?? { type: "object" },
4691
- output: fn.output ?? { type: "object" },
4692
- ...transactionRoots.has(filePath) ? { isTransactionRoot: true } : {}
4693
- };
4694
- });
4695
- return {
4696
- $schema: "https://cloud.uipath.com/draft/2024-12/entry-point",
4697
- $id: "entry-points.json",
4698
- entryPoints: [...preserved, ...functionEntries]
4699
- };
4700
- }
4701
- function buildBindingsDoc(functions, entryPointIdByPath, existingBindings, filePathPrefix = "content/") {
4702
- const httpExisting = new Map;
4703
- const preserved = [];
4704
- for (const r of existingBindings?.resources ?? []) {
4705
- if (r.resource === "HttpTrigger") {
4706
- const meta = r.metadata;
4707
- if (meta?.Method && meta?.Slug) {
4708
- httpExisting.set(`${meta.Method}:${meta.Slug}`, { key: r.key, id: r.id });
4709
- }
4710
- } else {
4711
- preserved.push(r);
5732
+ async readdir(dirPath) {
5733
+ try {
5734
+ return await fs6.readdir(dirPath);
5735
+ } catch (error) {
5736
+ if (this.isEnoent(error))
5737
+ return [];
5738
+ throw error;
4712
5739
  }
4713
5740
  }
4714
- const httpTriggers = functions.filter((fn) => fn.method && fn.path).map((fn) => {
4715
- const existing = httpExisting.get(`${fn.method}:${fn.path}`);
4716
- const bindingKey = existing?.key ?? newId();
4717
- const bindingId = existing?.id ?? newId();
4718
- const entryPointUniqueId = entryPointIdByPath.get(filePathPrefix + (fn.functionPath ?? ""));
4719
- if (!entryPointUniqueId) {
4720
- throw new Error(`Internal error: binding for "${fn.method} ${fn.path}" references entry point "${filePathPrefix}${fn.functionPath}", which is missing from entry-points.json.`);
5741
+ async stat(filePath) {
5742
+ try {
5743
+ const stats = await fs6.stat(filePath);
5744
+ return {
5745
+ isFile: () => stats.isFile(),
5746
+ isDirectory: () => stats.isDirectory(),
5747
+ size: stats.size,
5748
+ mtimeMs: stats.mtimeMs
5749
+ };
5750
+ } catch (error) {
5751
+ if (this.isEnoent(error))
5752
+ return null;
5753
+ throw error;
4721
5754
  }
4722
- return {
4723
- resource: "HttpTrigger",
4724
- key: bindingKey,
4725
- id: bindingId,
4726
- value: {
4727
- EntryPointUniqueId: {
4728
- DefaultValue: entryPointUniqueId,
4729
- IsExpression: false
5755
+ }
5756
+ async exists(filePath) {
5757
+ return existsSync8(filePath);
5758
+ }
5759
+ async mkdir(dirPath) {
5760
+ await fs6.mkdir(dirPath, { recursive: true });
5761
+ }
5762
+ async rm(filePath) {
5763
+ await fs6.rm(filePath, { recursive: true, force: true });
5764
+ }
5765
+ async rename(oldPath, newPath) {
5766
+ await fs6.rename(oldPath, newPath);
5767
+ }
5768
+ async getTempDir() {
5769
+ return await fs6.mkdtemp(path2.join(os2.tmpdir(), "uipath-fs-"));
5770
+ }
5771
+ async copyDirectory(sourcePath, destPath) {
5772
+ const sourceStats = await this.stat(sourcePath);
5773
+ if (!sourceStats) {
5774
+ throw new Error(`Source directory does not exist: ${sourcePath}`);
5775
+ }
5776
+ if (!sourceStats.isDirectory()) {
5777
+ throw new Error(`Source path is not a directory: ${sourcePath}`);
5778
+ }
5779
+ await this.mkdir(destPath);
5780
+ const entries = await this.readdir(sourcePath);
5781
+ for (const entry of entries) {
5782
+ const srcEntry = path2.join(sourcePath, entry);
5783
+ const destEntry = path2.join(destPath, entry);
5784
+ const entryStats = await this.stat(srcEntry);
5785
+ if (!entryStats)
5786
+ continue;
5787
+ if (entryStats.isDirectory()) {
5788
+ await this.copyDirectory(srcEntry, destEntry);
5789
+ } else if (entryStats.isFile()) {
5790
+ const content = await this.readFile(srcEntry);
5791
+ if (content !== null) {
5792
+ await this.writeFile(destEntry, content);
4730
5793
  }
4731
- },
4732
- metadata: {
4733
- BindingsVersion: "2.1",
4734
- Name: fn.name ?? "",
4735
- Method: fn.method,
4736
- Slug: fn.path,
4737
- CallingMode: "LongPolling",
4738
- Description: fn.description ?? ""
4739
5794
  }
4740
- };
4741
- });
4742
- return {
4743
- $schema: "https://cloud.uipath.com/draft/2024-12/bindings",
4744
- version: "2.0",
4745
- resources: [...preserved, ...httpTriggers]
4746
- };
5795
+ }
5796
+ }
5797
+ isEnoent(error) {
5798
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
5799
+ }
4747
5800
  }
5801
+ var fsInstance = new NodeFileSystem;
5802
+ var getFileSystem = () => {
5803
+ return fsInstance;
5804
+ };
4748
5805
  function toExtractedFunctions(endpoints) {
4749
5806
  return endpoints.map((e) => ({
4750
5807
  functionPath: e.functionPath,
@@ -4760,20 +5817,20 @@ var tsxRegistered = false;
4760
5817
  async function extractAndWriteEntryPointsAndBindings(aggregatorPath, projectPath) {
4761
5818
  if (!tsxRegistered) {
4762
5819
  try {
4763
- const dbgPkg = join10(projectPath, SERVER_RUNNER_DIR, "package.json");
5820
+ const dbgPkg = join11(projectPath, SERVER_RUNNER_DIR, "package.json");
4764
5821
  const tsxEsm = createRequire4(dbgPkg).resolve("tsx/esm");
4765
- register(pathToFileURL(tsxEsm).href, pathToFileURL(join10(projectPath, SERVER_RUNNER_DIR) + "/").href);
5822
+ register(pathToFileURL2(tsxEsm).href, pathToFileURL2(join11(projectPath, SERVER_RUNNER_DIR) + "/").href);
4766
5823
  tsxRegistered = true;
4767
5824
  } catch {}
4768
5825
  }
4769
5826
  let app;
4770
5827
  try {
4771
- const mod = await import(pathToFileURL(aggregatorPath).href);
5828
+ const mod = await import(pathToFileURL2(aggregatorPath).href);
4772
5829
  app = mod.default;
4773
5830
  } catch (err2) {
4774
5831
  const msg = err2 instanceof Error ? err2.message : String(err2);
4775
5832
  if (msg.includes("Cannot find") || msg.includes("ERR_MODULE_NOT_FOUND")) {
4776
- throw new Error("Failed to load function modules. Run 'npm install' first, then retry.");
5833
+ throw new Error(`Failed to load function modules. Run '${describeInstallCommand(projectPath)}' first, then retry.`);
4777
5834
  }
4778
5835
  throw new Error(`Manifest extraction failed.
4779
5836
  ${msg}`);
@@ -4789,40 +5846,47 @@ ${msg}`);
4789
5846
  return manifest;
4790
5847
  }
4791
5848
  function writeEntryPointsAndBindings(functions, projectPath) {
4792
- const epPath = join10(projectPath, "entry-points.json");
5849
+ const epPath = join11(projectPath, "entry-points.json");
4793
5850
  let existingEntryPointsDoc = null;
4794
- if (existsSync8(epPath)) {
5851
+ if (existsSync9(epPath)) {
4795
5852
  try {
4796
- existingEntryPointsDoc = JSON.parse(readFileSync6(epPath, "utf-8"));
5853
+ existingEntryPointsDoc = JSON.parse(readFileSync7(epPath, "utf-8"));
4797
5854
  } catch {}
4798
5855
  }
4799
5856
  const entryPointsDoc = buildEntryPointsDoc(functions, existingEntryPointsDoc);
4800
- writeFileSync8(join10(projectPath, "entry-points.json"), JSON.stringify(entryPointsDoc, null, 2));
5857
+ writeFileSync9(join11(projectPath, "entry-points.json"), JSON.stringify(entryPointsDoc, null, 2));
4801
5858
  const entryPointIdByPath = new Map;
4802
5859
  for (const ep of entryPointsDoc.entryPoints) {
4803
5860
  if (ep.type === "function" && !entryPointIdByPath.has(ep.filePath)) {
4804
5861
  entryPointIdByPath.set(ep.filePath, ep.uniqueId);
4805
5862
  }
4806
5863
  }
4807
- const bindingsPath = join10(projectPath, "bindings_v2.json");
5864
+ const bindingsPath = join11(projectPath, "bindings_v2.json");
4808
5865
  let existingBindingsDoc = null;
4809
- if (existsSync8(bindingsPath)) {
5866
+ if (existsSync9(bindingsPath)) {
4810
5867
  try {
4811
- existingBindingsDoc = JSON.parse(readFileSync6(bindingsPath, "utf-8"));
5868
+ existingBindingsDoc = JSON.parse(readFileSync7(bindingsPath, "utf-8"));
4812
5869
  } catch {}
4813
5870
  }
4814
5871
  const bindingsDoc = buildBindingsDoc(functions, entryPointIdByPath, existingBindingsDoc);
4815
- writeFileSync8(join10(projectPath, "bindings_v2.json"), JSON.stringify(bindingsDoc, null, 2));
5872
+ writeFileSync9(join11(projectPath, "bindings_v2.json"), JSON.stringify(bindingsDoc, null, 2));
4816
5873
  }
4817
- async function writeManifest(extraction, aggregatorPath, projectPath) {
4818
- const needsExecution = extraction.diagnostics.some((d) => d.code === DIAGNOSTIC_CODES2.UNSUPPORTED_VALIDATOR);
4819
- for (const d of extraction.diagnostics) {
4820
- if (d.code === DIAGNOSTIC_CODES2.UNSUPPORTED_VALIDATOR)
4821
- continue;
4822
- const where = [d.functionName, d.field].filter(Boolean).join(".");
4823
- console.warn(` Warning${where ? ` (${where})` : ""}: ${d.message}`);
5874
+ function manifestNeedsExecution(extraction, functionsMap) {
5875
+ const forcesExecution = new Set([
5876
+ DIAGNOSTIC_CODES2.UNSUPPORTED_VALIDATOR,
5877
+ DIAGNOSTIC_CODES2.UNREADABLE_PROPERTY,
5878
+ DIAGNOSTIC_CODES2.NON_STATIC_LITERAL
5879
+ ]);
5880
+ if (extraction.diagnostics.some((d) => forcesExecution.has(d.code))) {
5881
+ return true;
4824
5882
  }
4825
- if (needsExecution) {
5883
+ if (!functionsMap)
5884
+ return false;
5885
+ const covered = new Set(extraction.functions.map((f) => f.functionPath));
5886
+ return Object.values(functionsMap).some((v) => !covered.has(v.split(":")[0]));
5887
+ }
5888
+ async function writeManifest(extraction, aggregatorPath, projectPath, functionsMap) {
5889
+ if (manifestNeedsExecution(extraction, functionsMap)) {
4826
5890
  const manifest = await extractAndWriteEntryPointsAndBindings(aggregatorPath, projectPath);
4827
5891
  return { count: manifest.endpoints.length, static: false };
4828
5892
  }
@@ -4834,34 +5898,34 @@ async function writeManifest(extraction, aggregatorPath, projectPath) {
4834
5898
  return { count: functions.length, static: true };
4835
5899
  }
4836
5900
  async function generateManifests(projectPath) {
4837
- const uipathJsonPath = join11(projectPath, "uipath.json");
4838
- if (!existsSync9(uipathJsonPath)) {
5901
+ const uipathJsonPath = join12(projectPath, "uipath.json");
5902
+ if (!existsSync10(uipathJsonPath)) {
4839
5903
  throw new Error("No uipath.json found. Run 'uipath-functions init' first.");
4840
5904
  }
4841
5905
  if (syncFunctionsMap(projectPath)) {
4842
5906
  console.log("Updated functions map in uipath.json.");
4843
5907
  }
4844
- const uipathJson = JSON.parse(readFileSync7(uipathJsonPath, "utf-8"));
5908
+ const uipathJson = JSON.parse(readFileSync8(uipathJsonPath, "utf-8"));
4845
5909
  if (!uipathJson.functions || Object.keys(uipathJson.functions).length === 0) {
4846
5910
  throw new Error("No functions defined in uipath.json.");
4847
5911
  }
4848
- let bootstrapped = false;
4849
- if (!existsSync9(join11(projectPath, "node_modules"))) {
4850
- setupRunDependencies(projectPath);
4851
- bootstrapped = true;
4852
- }
5912
+ assertReadyToPackage(projectPath);
4853
5913
  const previousDesignTime = process.env[DESIGN_TIME_ENV];
4854
5914
  process.env[DESIGN_TIME_ENV] = "1";
4855
5915
  try {
4856
- console.log("Generating aggregator...");
4857
5916
  const extraction = extractProject(uipathJson.functions, projectPath);
5917
+ const blocking = reportDiagnostics(extraction.diagnostics);
5918
+ if (blocking > 0) {
5919
+ throw new Error(`${blocking} error(s) in the project's function files — nothing was written. ` + `Fix them and re-run.`);
5920
+ }
5921
+ console.log("Generating aggregator...");
4858
5922
  const aggregatorPath = generateAggregator(uipathJson.functions, projectPath, "serve", toDerivedContracts(extraction.functions));
4859
- const needsExecution = extraction.diagnostics.some((d) => d.code === DIAGNOSTIC_CODES2.UNSUPPORTED_VALIDATOR);
4860
- if (needsExecution && !bootstrapped) {
4861
- setupRunDependencies(projectPath);
5923
+ const needsExecution = manifestNeedsExecution(extraction, uipathJson.functions);
5924
+ if (needsExecution) {
5925
+ installServerRunner(projectPath);
4862
5926
  }
4863
5927
  console.log("Extracting function manifest...");
4864
- return await writeManifest(extraction, aggregatorPath, projectPath);
5928
+ return await writeManifest(extraction, aggregatorPath, projectPath, uipathJson.functions);
4865
5929
  } finally {
4866
5930
  if (previousDesignTime === undefined) {
4867
5931
  delete process.env[DESIGN_TIME_ENV];
@@ -4871,8 +5935,11 @@ async function generateManifests(projectPath) {
4871
5935
  }
4872
5936
  }
4873
5937
  function registerPackCommand(program2) {
4874
- program2.command("pack").description("Pack the project into a .nupkg for deployment.").option("--nolock", "Exclude lock file from package").action(async (opts) => {
5938
+ program2.command("pack").description("Pack the project into a .nupkg for deployment.").option("--nolock", "Deprecated and ignored: the project's lock file is always packaged").action(async (opts) => {
4875
5939
  const cwd = resolve5(".");
5940
+ if (opts.nolock) {
5941
+ console.warn("--nolock is ignored: the project's lock file is always packaged, the pod installs from it.");
5942
+ }
4876
5943
  try {
4877
5944
  const result = await generateManifests(cwd);
4878
5945
  console.log(` ${result.count} function(s) — ${result.static ? "extracted statically" : "executed to extract"}.`);
@@ -4880,24 +5947,23 @@ function registerPackCommand(program2) {
4880
5947
  console.error(err2 instanceof Error ? err2.message : String(err2));
4881
5948
  process.exit(1);
4882
5949
  }
4883
- const uipathJsonPath = join12(cwd, "uipath.json");
4884
- const uipathJson = JSON.parse(readFileSync8(uipathJsonPath, "utf-8"));
4885
- const packageJson = JSON.parse(readFileSync8(join12(cwd, "package.json"), "utf-8"));
5950
+ const uipathJsonPath = join13(cwd, "uipath.json");
5951
+ const uipathJson = JSON.parse(readFileSync9(uipathJsonPath, "utf-8"));
5952
+ const packageJson = JSON.parse(readFileSync9(join13(cwd, "package.json"), "utf-8"));
4886
5953
  const packageId = (packageJson.name ?? "functions").replace(/[^a-zA-Z0-9._-]/g, "") || "functions";
4887
5954
  const version = packageJson.version ?? "1.0.0";
4888
5955
  if (!uipathJson.projectId) {
4889
5956
  uipathJson.projectId = randomUUID();
4890
- writeFileSync9(uipathJsonPath, JSON.stringify(uipathJson, null, 2), "utf-8");
5957
+ writeFileSync10(uipathJsonPath, JSON.stringify(uipathJson, null, 2), "utf-8");
4891
5958
  }
4892
5959
  console.log("Assembling package...");
4893
- const outputDir = join12(cwd, ".uipath", "package-build");
5960
+ const outputDir = join13(cwd, ".uipath", "package-build");
4894
5961
  mkdirSync5(outputDir, { recursive: true });
4895
5962
  const fs7 = getFileSystem();
4896
5963
  await buildFunctionsPackage(fs7, {
4897
5964
  projectPath: cwd,
4898
5965
  outputPath: outputDir,
4899
5966
  projectStorageId: uipathJson.projectId,
4900
- excludeLockFile: opts.nolock,
4901
5967
  package: {
4902
5968
  id: packageId,
4903
5969
  version,
@@ -4917,12 +5983,12 @@ function zipToNupkg(buildDir, cwd, packageId, version) {
4917
5983
  const files = {};
4918
5984
  function walk(dir, prefix) {
4919
5985
  for (const name of readdirSync3(dir)) {
4920
- const abs = join12(dir, name);
5986
+ const abs = join13(dir, name);
4921
5987
  const rel = prefix ? `${prefix}/${name}` : name;
4922
5988
  if (statSync(abs).isDirectory()) {
4923
5989
  walk(abs, rel);
4924
5990
  } else {
4925
- files[rel] = new Uint8Array(readFileSync8(abs));
5991
+ files[rel] = new Uint8Array(readFileSync9(abs));
4926
5992
  }
4927
5993
  }
4928
5994
  }
@@ -4932,15 +5998,31 @@ function zipToNupkg(buildDir, cwd, packageId, version) {
4932
5998
  files["[Content_Types].xml"] = enc.encode(`<?xml version="1.0" encoding="utf-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="nuspec" ContentType="application/octet"/><Default Extension="ts" ContentType="application/octet"/><Default Extension="js" ContentType="application/octet"/><Default Extension="json" ContentType="application/octet"/></Types>`);
4933
5999
  files["_rels/.rels"] = enc.encode(`<?xml version="1.0" encoding="utf-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Type="http://schemas.microsoft.com/packaging/2010/07/manifest" Target="/${packageId}.nuspec" Id="Rd1"/></Relationships>`);
4934
6000
  const zipped = zipSync(files);
4935
- mkdirSync5(join12(cwd, ".uipath"), { recursive: true });
4936
- const nupkgPath = join12(cwd, ".uipath", `${packageId}.${version}.nupkg`);
4937
- writeFileSync9(nupkgPath, zipped);
6001
+ mkdirSync5(join13(cwd, ".uipath"), { recursive: true });
6002
+ const nupkgPath = join13(cwd, ".uipath", `${packageId}.${version}.nupkg`);
6003
+ writeFileSync10(nupkgPath, zipped);
4938
6004
  return nupkgPath;
4939
6005
  }
4940
6006
  var GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4941
6007
  function isGuid(value) {
4942
6008
  return GUID_RE.test(value);
4943
6009
  }
6010
+ var CONTENT_PREFIX = "content/";
6011
+ function describeNupkgProblem(nupkg) {
6012
+ const packedName = (entryName) => entryName.startsWith(CONTENT_PREFIX) ? entryName.slice(CONTENT_PREFIX.length) : null;
6013
+ let entries;
6014
+ try {
6015
+ entries = unzipSync(nupkg, {
6016
+ filter: (file) => {
6017
+ const name = packedName(file.name);
6018
+ return name !== null && affectsDependencyInstall(name);
6019
+ }
6020
+ });
6021
+ } catch {
6022
+ return "is not a valid .nupkg archive.";
6023
+ }
6024
+ return describePackagedInstallProblem(Object.keys(entries).flatMap((name) => packedName(name) ?? []));
6025
+ }
4944
6026
  async function fetchProcessFeeds(baseUrl, org, tenant, token) {
4945
6027
  const url = `${baseUrl}/${org}/${tenant}/orchestrator_/api/PackageFeeds/GetFeeds`;
4946
6028
  const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
@@ -5016,8 +6098,8 @@ Publish cancelled.
5016
6098
  function registerPublishCommand(program2) {
5017
6099
  program2.command("publish").description("Upload the packed .nupkg to an Orchestrator feed. Fetches available feeds and prompts for selection; press ESC to cancel.").option("--url <url>", "UiPath platform base URL (or UIPATH_URL env)").option("--org <org>", "Organization name (or UIPATH_ORGANIZATION_NAME env)").option("--tenant <tenant>", "Tenant name (or UIPATH_TENANT_NAME env)").option("--token <token>", "Access token (or UIPATH_ACCESS_TOKEN env)").option("--feed-id <id>", "Feed ID — skips the interactive picker (for CI use)").action(async (opts) => {
5018
6100
  const cwd = resolve6(".");
5019
- const nupkgDir = join13(cwd, ".uipath");
5020
- if (!existsSync10(nupkgDir)) {
6101
+ const nupkgDir = join14(cwd, ".uipath");
6102
+ if (!existsSync11(nupkgDir)) {
5021
6103
  console.error("No .uipath/ directory found. Run 'uipath-functions pack' first.");
5022
6104
  process.exit(1);
5023
6105
  }
@@ -5026,8 +6108,13 @@ function registerPublishCommand(program2) {
5026
6108
  console.error("No .nupkg found in .uipath/. Run 'uipath-functions pack' first.");
5027
6109
  process.exit(1);
5028
6110
  }
5029
- const nupkgFile = nupkgs.map((f) => ({ name: f, mtime: statSync2(join13(nupkgDir, f)).mtimeMs })).sort((a, b) => b.mtime - a.mtime)[0].name;
5030
- const nupkgPath = join13(nupkgDir, nupkgFile);
6111
+ const nupkgFile = nupkgs.map((f) => ({ name: f, mtime: statSync2(join14(nupkgDir, f)).mtimeMs })).sort((a, b) => b.mtime - a.mtime)[0].name;
6112
+ const nupkgPath = join14(nupkgDir, nupkgFile);
6113
+ const nupkgProblem = describeNupkgProblem(readFileSync10(nupkgPath));
6114
+ if (nupkgProblem) {
6115
+ console.error(`${nupkgFile}: ${nupkgProblem} Run 'uipath-functions pack' again, then publish.`);
6116
+ process.exit(1);
6117
+ }
5031
6118
  const baseUrl = (opts.url ?? process.env["UIPATH_URL"])?.replace(/\/$/, "");
5032
6119
  const org = opts.org ?? process.env["UIPATH_ORGANIZATION_NAME"];
5033
6120
  const tenant = opts.tenant ?? process.env["UIPATH_TENANT_NAME"];
@@ -5073,7 +6160,7 @@ function registerPublishCommand(program2) {
5073
6160
  console.log(`
5074
6161
  Publishing ${nupkgFile} → ${feedLabel}...`);
5075
6162
  const form = new FormData;
5076
- const blob = new Blob([readFileSync9(nupkgPath)], {
6163
+ const blob = new Blob([readFileSync10(nupkgPath)], {
5077
6164
  type: "application/octet-stream"
5078
6165
  });
5079
6166
  form.append("file", blob, nupkgFile);
@@ -5120,11 +6207,11 @@ function resolveStudioMetadata(opts) {
5120
6207
  };
5121
6208
  }
5122
6209
  function readLocalStudioMetadata(projectDir) {
5123
- const path3 = join14(projectDir, STUDIO_METADATA_PATH);
5124
- if (!existsSync11(path3))
6210
+ const path3 = join15(projectDir, STUDIO_METADATA_PATH);
6211
+ if (!existsSync12(path3))
5125
6212
  return null;
5126
6213
  try {
5127
- const parsed = JSON.parse(readFileSync10(path3, "utf-8"));
6214
+ const parsed = JSON.parse(readFileSync11(path3, "utf-8"));
5128
6215
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
5129
6216
  return null;
5130
6217
  }
@@ -5134,9 +6221,9 @@ function readLocalStudioMetadata(projectDir) {
5134
6221
  }
5135
6222
  }
5136
6223
  function writeStudioMetadata(projectDir, metadata) {
5137
- const path3 = join14(projectDir, STUDIO_METADATA_PATH);
5138
- mkdirSync6(dirname3(path3), { recursive: true });
5139
- writeFileSync10(path3, JSON.stringify(metadata, null, 2) + `
6224
+ const path3 = join15(projectDir, STUDIO_METADATA_PATH);
6225
+ mkdirSync6(dirname4(path3), { recursive: true });
6226
+ writeFileSync11(path3, JSON.stringify(metadata, null, 2) + `
5140
6227
  `, "utf-8");
5141
6228
  return path3;
5142
6229
  }
@@ -5161,7 +6248,7 @@ function claim(claims, name) {
5161
6248
  }
5162
6249
  function authorFromPackageJson(projectDir) {
5163
6250
  try {
5164
- const pkg = JSON.parse(readFileSync10(join14(projectDir, "package.json"), "utf-8"));
6251
+ const pkg = JSON.parse(readFileSync11(join15(projectDir, "package.json"), "utf-8"));
5165
6252
  if (typeof pkg.author === "string")
5166
6253
  return pkg.author.trim();
5167
6254
  return (pkg.author?.email ?? pkg.author?.name ?? "").trim();
@@ -5189,7 +6276,7 @@ var IGNORE_FILES = new Set([
5189
6276
  ".gitignore",
5190
6277
  ".uipathignore",
5191
6278
  ".gitkeep",
5192
- ".npmrc"
6279
+ REGISTRY_CONFIG_FILE
5193
6280
  ]);
5194
6281
  var TEXT_EXTS = new Set([
5195
6282
  ".ts",
@@ -5229,7 +6316,7 @@ function collectLocalFiles(projectDir) {
5229
6316
  continue;
5230
6317
  if (name.startsWith(".") && IGNORE_FILES.has(name))
5231
6318
  continue;
5232
- const abs = join15(dir, name);
6319
+ const abs = join16(dir, name);
5233
6320
  const stat2 = statSync3(abs);
5234
6321
  if (stat2.isDirectory()) {
5235
6322
  walk(abs);
@@ -5320,7 +6407,7 @@ async function performStructuralMigration(cfg, lockKey, plan) {
5320
6407
  const form = new FormData;
5321
6408
  form.append("DeletedResources", JSON.stringify(plan.filesToDelete.map((f) => f.id)));
5322
6409
  plan.filesToUpload.forEach((f, i2) => {
5323
- const content = readFileSync11(f.absolutePath);
6410
+ const content = readFileSync12(f.absolutePath);
5324
6411
  const fileName = f.remotePath.split("/").at(-1);
5325
6412
  form.append(`AddedResources[${i2}].Content`, new Blob([content]), fileName);
5326
6413
  const parentPath = f.remotePath.includes("/") ? f.remotePath.slice(0, f.remotePath.lastIndexOf("/")) : "";
@@ -5328,7 +6415,7 @@ async function performStructuralMigration(cfg, lockKey, plan) {
5328
6415
  form.append(`AddedResources[${i2}].ParentPath`, parentPath);
5329
6416
  });
5330
6417
  plan.filesToUpdate.forEach(({ local, remoteId }, i2) => {
5331
- const content = readFileSync11(local.absolutePath);
6418
+ const content = readFileSync12(local.absolutePath);
5332
6419
  const fileName = local.remotePath.split("/").at(-1);
5333
6420
  form.append(`ModifiedResources[${i2}].Content`, new Blob([content]), fileName);
5334
6421
  form.append(`ModifiedResources[${i2}].Id`, remoteId);
@@ -5380,7 +6467,7 @@ async function computePlan(cfg, localFiles, structure) {
5380
6467
  plan.filesToUpload.push(lf);
5381
6468
  return;
5382
6469
  }
5383
- const localContent = readFileSync11(lf.absolutePath);
6470
+ const localContent = readFileSync12(lf.absolutePath);
5384
6471
  const localHash = computeHash(localContent, lf.absolutePath);
5385
6472
  const remoteContent = await downloadFile(cfg, remote.id);
5386
6473
  const remoteHash = computeHash(remoteContent, lf.absolutePath);
@@ -5449,9 +6536,9 @@ async function pushToStudio(cfg, projectDir, localFiles, onProgress) {
5449
6536
  }
5450
6537
  }
5451
6538
  function readPushCredentials(opts) {
5452
- const envPath = join15(process.cwd(), ".env");
5453
- if (existsSync12(envPath)) {
5454
- for (const line of readFileSync11(envPath, "utf-8").split(`
6539
+ const envPath = join16(process.cwd(), ".env");
6540
+ if (existsSync13(envPath)) {
6541
+ for (const line of readFileSync12(envPath, "utf-8").split(`
5455
6542
  `)) {
5456
6543
  if (line.trimStart().startsWith("#"))
5457
6544
  continue;
@@ -5477,21 +6564,23 @@ function readPushCredentials(opts) {
5477
6564
  function registerPushCommand(program2) {
5478
6565
  program2.command("push").description("Sync the project to Studio Web (generate entry-points, diff, upload changed files).").option("--url <url>", "UiPath base URL (or UIPATH_URL in env)").option("--org <org>", "Organization name (or UIPATH_ORGANIZATION_NAME in env)").option("--tenant <tenant>", "Tenant name (or UIPATH_TENANT_NAME in env)").option("--token <token>", "Access token (or UIPATH_ACCESS_TOKEN in env)").option("--project-id <id>", "Studio Web project ID — mandatory (or UIPATH_PROJECT_ID in env)").action(async (opts) => {
5479
6566
  const cwd = resolve7(".");
5480
- const uipathJsonPath = join16(cwd, "uipath.json");
5481
- if (!existsSync13(uipathJsonPath)) {
6567
+ const uipathJsonPath = join17(cwd, "uipath.json");
6568
+ if (!existsSync14(uipathJsonPath)) {
5482
6569
  console.error("No uipath.json found. Run 'uipath-functions init' first.");
5483
6570
  process.exit(1);
5484
6571
  }
5485
6572
  if (syncFunctionsMap(cwd)) {
5486
6573
  console.log("Updated functions map in uipath.json.");
5487
6574
  }
5488
- const uipathJson = JSON.parse(readFileSync12(uipathJsonPath, "utf-8"));
6575
+ const uipathJson = JSON.parse(readFileSync13(uipathJsonPath, "utf-8"));
5489
6576
  if (!uipathJson.functions || Object.keys(uipathJson.functions).length === 0) {
5490
6577
  console.error("No functions defined in uipath.json.");
5491
6578
  process.exit(1);
5492
6579
  }
5493
- if (!existsSync13(join16(cwd, "node_modules"))) {
5494
- console.error("node_modules not found. Run 'npm install' first.");
6580
+ try {
6581
+ assertReadyToPackage(cwd);
6582
+ } catch (err2) {
6583
+ console.error(err2 instanceof Error ? err2.message : String(err2));
5495
6584
  process.exit(1);
5496
6585
  }
5497
6586
  const creds = readPushCredentials(opts);
@@ -5502,14 +6591,18 @@ Create the project in Studio Web first to get UIPATH_PROJECT_ID.`);
5502
6591
  }
5503
6592
  if (!uipathJson.projectId) {
5504
6593
  uipathJson.projectId = creds.projectId;
5505
- writeFileSync11(uipathJsonPath, JSON.stringify(uipathJson, null, 2) + `
6594
+ writeFileSync12(uipathJsonPath, JSON.stringify(uipathJson, null, 2) + `
5506
6595
  `, "utf-8");
5507
6596
  }
5508
6597
  console.log("Generating entry-points.json...");
5509
6598
  const extraction = extractProject(uipathJson.functions, cwd);
6599
+ reportDiagnosticsOrExit(extraction.diagnostics);
5510
6600
  const aggregatorPath = generateAggregator(uipathJson.functions, cwd, "serve", toDerivedContracts(extraction.functions));
6601
+ if (manifestNeedsExecution(extraction, uipathJson.functions)) {
6602
+ installServerRunner(cwd);
6603
+ }
5511
6604
  try {
5512
- const result = await writeManifest(extraction, aggregatorPath, cwd);
6605
+ const result = await writeManifest(extraction, aggregatorPath, cwd, uipathJson.functions);
5513
6606
  console.log(` ${result.count} function(s) exported — ${result.static ? "extracted statically" : "executed to extract"}.`);
5514
6607
  } catch (err2) {
5515
6608
  console.error(err2 instanceof Error ? err2.message : String(err2));
@@ -5544,7 +6637,7 @@ function resolveTargetFile(cwd, opts) {
5544
6637
  return null;
5545
6638
  const match = entry.match(/^(.*?):([A-Za-z_$][\w$]*)$/);
5546
6639
  const filePart = match ? match[1] : entry;
5547
- const abs = isAbsolute2(filePart) ? filePart : resolve8(cwd, filePart);
6640
+ const abs = isAbsolute3(filePart) ? filePart : resolve8(cwd, filePart);
5548
6641
  return relative3(cwd, abs);
5549
6642
  }
5550
6643
  function writeDerivedContract(cwd, opts) {
@@ -5555,9 +6648,9 @@ function writeDerivedContract(cwd, opts) {
5555
6648
  const derived = opts.production ? readBakedContract(relFile, cwd) : deriveRunContract(relFile, cwd);
5556
6649
  if (!derived)
5557
6650
  return "";
5558
- const outPath = join17(cwd, DERIVED_CONTRACT_FILE);
5559
- mkdirSync7(join17(cwd, ".uipath/run"), { recursive: true });
5560
- writeFileSync12(outPath, JSON.stringify(derived), "utf-8");
6651
+ const outPath = join18(cwd, DERIVED_CONTRACT_FILE);
6652
+ mkdirSync7(join18(cwd, ".uipath/run"), { recursive: true });
6653
+ writeFileSync13(outPath, JSON.stringify(derived), "utf-8");
5561
6654
  return outPath;
5562
6655
  } catch (err2) {
5563
6656
  console.error("contract preparation skipped: " + (err2 instanceof Error ? err2.message : String(err2)));
@@ -5565,7 +6658,7 @@ function writeDerivedContract(cwd, opts) {
5565
6658
  }
5566
6659
  }
5567
6660
  function readFunctionsMap(cwd) {
5568
- const parsed = readJsonIfExists2(join17(cwd, "uipath.json"));
6661
+ const parsed = readJsonIfExists2(join18(cwd, "uipath.json"));
5569
6662
  const functions = isRecord(parsed) ? parsed.functions : undefined;
5570
6663
  if (!isRecord(functions))
5571
6664
  return {};
@@ -5580,32 +6673,58 @@ function isRecord(value) {
5580
6673
  return typeof value === "object" && value !== null;
5581
6674
  }
5582
6675
  function readJsonIfExists2(path3) {
5583
- if (!existsSync14(path3))
6676
+ if (!existsSync15(path3))
5584
6677
  return null;
5585
6678
  try {
5586
- return JSON.parse(readFileSync13(path3, "utf-8"));
6679
+ return JSON.parse(readFileSync14(path3, "utf-8"));
5587
6680
  } catch {
5588
6681
  return null;
5589
6682
  }
5590
6683
  }
5591
- var RUN_FUNCTION_CALL = `runFunction({ entrypoint: entrypoint || undefined, function: fn || undefined, input: input || undefined, inputFile: inputFile || undefined, context: context || undefined, contextFile: contextFile || undefined, derivedFile: derivedFile || undefined })`;
5592
- var DENO_ENTRY_CONTENT = `import { runFunction } from "@uipath/coded-functions-js-runtime";
6684
+ var RUN_FUNCTION_CALL = `runtime.runFunction({ entrypoint: entrypoint || undefined, function: fn || undefined, input: input || undefined, inputFile: inputFile || undefined, context: context || undefined, contextFile: contextFile || undefined, derivedFile: derivedFile || undefined, ...traced })`;
6685
+ var TRACED_OPTIONS = `let traced = {};
6686
+ if (env.UIPATH_TRACE_STORE === "1") {
6687
+ if (!runtime.traceStoreOptionsFromEnv) {
6688
+ console.error("trace store: the installed @uipath/coded-functions-js-runtime predates --trace-store (needs >= 0.9.1); spans will not be posted.");
6689
+ } else {
6690
+ traced = runtime.traceStoreOptionsFromEnv(env, (detail) => console.error(\`trace store: ingest failed: \${detail}\`)) ?? {};
6691
+ if (!traced.onSpans) { console.error("trace store: incomplete UIPATH_* trace scope/token; spans will not be posted."); }
6692
+ }
6693
+ }`;
6694
+ var DENO_ENTRY_CONTENT = `import * as runtime from "@uipath/coded-functions-js-runtime";
5593
6695
  const [entrypoint, fn, input, inputFile, context, contextFile, derivedFile] = Deno.args;
6696
+ const env = Deno.env.toObject();
6697
+ ${TRACED_OPTIONS}
5594
6698
  const exitCode = await ${RUN_FUNCTION_CALL};
5595
6699
  Deno.exit(exitCode);
5596
6700
  `;
5597
- var NODE_ENTRY_CONTENT = `import { runFunction } from "@uipath/coded-functions-js-runtime";
6701
+ var NODE_ENTRY_CONTENT = `import * as runtime from "@uipath/coded-functions-js-runtime";
5598
6702
  const [entrypoint, fn, input, inputFile, context, contextFile, derivedFile] = process.argv.slice(2);
6703
+ const env = process.env;
6704
+ ${TRACED_OPTIONS}
5599
6705
  ${RUN_FUNCTION_CALL}
5600
6706
  .then((code) => process.exit(code));
5601
6707
  `;
6708
+ var DEFAULT_INSPECTOR_ENDPOINT = "127.0.0.1:9229";
5602
6709
  function registerRunCommand(program2) {
5603
- program2.command("run").description("Execute a single coded function once (one-shot job) and report the result.").option("--runtime <runtime>", "Runtime: node (default) or deno", "node").option("--entrypoint <path>", "Path to the function file").option("--function <name>", "Function name resolved via uipath.json").option("--input <json>", "JSON input payload", "{}").option("--input-file <path>", "Path to a JSON input file (takes priority over --input)").option("--context <json>", "JSON runtime-context payload (used when --context-file is absent)").option("--context-file <path>", "Path to the runtime-context JSON file (takes priority over --context)").option("--production", "Run under production context; skip the .uipath/server-runner install when it already exists.").action((opts) => {
6710
+ program2.command("run").description("Execute a single coded function once (one-shot job) and report the result.").option("--runtime <runtime>", "Runtime: node (default) or deno", "node").option("--entrypoint <path>", "Path to the function file").option("--function <name>", "Function name resolved via uipath.json").option("--input <json>", "JSON input payload", "{}").option("--input-file <path>", "Path to a JSON input file (takes priority over --input)").option("--context <json>", "JSON runtime-context payload (used when --context-file is absent)").option("--context-file <path>", "Path to the runtime-context JSON file (takes priority over --context)").option("--production", "Run under production context; skip the .uipath/server-runner install when it already exists.").option("--inspect [endpoint]", `Open the V8 inspector on host:port while the function runs (default ${DEFAULT_INSPECTOR_ENDPOINT})`).option("--inspect-wait [endpoint]", `Open the V8 inspector on host:port and wait for a debugger to attach before executing (default ${DEFAULT_INSPECTOR_ENDPOINT})`).option("--trace-store", "Post the run's trace spans to the platform trace store (scope from UIPATH_* env vars + UIPATH_ACCESS_TOKEN)").action(async (opts) => {
5604
6711
  const cwd = resolve9(".");
5605
- const skipInstall = opts.production === true && existsSync15(join18(cwd, SERVER_RUNNER_DIR));
6712
+ if (opts.inspect && opts.inspectWait) {
6713
+ console.error("Provide only one of --inspect or --inspect-wait.");
6714
+ process.exit(1);
6715
+ }
6716
+ if (opts.production !== true) {
6717
+ try {
6718
+ assertDependenciesInstalled(cwd);
6719
+ } catch (err2) {
6720
+ console.error(err2 instanceof Error ? err2.message : String(err2));
6721
+ process.exit(1);
6722
+ }
6723
+ }
6724
+ const skipInstall = opts.production === true && existsSync16(join19(cwd, SERVER_RUNNER_DIR));
5606
6725
  if (!skipInstall) {
5607
6726
  try {
5608
- setupRunDependencies(cwd);
6727
+ installServerRunner(cwd);
5609
6728
  } catch (err2) {
5610
6729
  console.error(err2 instanceof Error ? err2.message : String(err2));
5611
6730
  process.exit(1);
@@ -5620,58 +6739,135 @@ function registerRunCommand(program2) {
5620
6739
  }
5621
6740
  });
5622
6741
  }
5623
- function denoPermissionFlags(cwd, production) {
6742
+ function inspectorFlags(opts) {
6743
+ const endpoint = (value) => value === true ? DEFAULT_INSPECTOR_ENDPOINT : value;
6744
+ if (opts.inspectWait) {
6745
+ return [`--inspect-wait=${endpoint(opts.inspectWait)}`];
6746
+ }
6747
+ if (opts.inspect) {
6748
+ return [`--inspect=${endpoint(opts.inspect)}`];
6749
+ }
6750
+ return [];
6751
+ }
6752
+ function runEnv(opts, base = process.env) {
6753
+ const env = { ...base };
6754
+ delete env.UIPATH_TRACE_STORE;
6755
+ return opts.traceStore ? { ...env, UIPATH_TRACE_STORE: "1" } : env;
6756
+ }
6757
+ function denoPermissionFlags(cwd, production, env = process.env) {
5624
6758
  if (!production) {
5625
6759
  return ["--allow-env", "--allow-net", "--allow-read", "--allow-write", "--allow-sys", "--allow-run"];
5626
6760
  }
5627
- const jobDir = process.env.JOB_WORKING_DIRECTORY ?? cwd;
6761
+ const jobDir = env.JOB_WORKING_DIRECTORY ?? cwd;
6762
+ const endpoint = env.UIPATH_JOB_API_ENDPOINT_PATH;
6763
+ const writeTargets = endpoint ? [jobDir, endpoint] : [jobDir];
5628
6764
  return [
5629
6765
  "--allow-env",
5630
6766
  "--allow-net",
5631
6767
  "--allow-read",
5632
- `--allow-write=${jobDir}`,
6768
+ `--allow-write=${writeTargets.join(",")}`,
5633
6769
  "--allow-sys=hostname,cpus,osRelease,systemMemoryInfo"
5634
6770
  ];
5635
6771
  }
6772
+ function readIfPresent(path3) {
6773
+ try {
6774
+ return readFileSync15(path3, "utf-8");
6775
+ } catch {
6776
+ return;
6777
+ }
6778
+ }
6779
+ function removeQuietly(path3) {
6780
+ try {
6781
+ rmSync2(path3, { force: true });
6782
+ return true;
6783
+ } catch {
6784
+ return false;
6785
+ }
6786
+ }
5636
6787
  function writeRunEntry(cwd, fileName, content) {
5637
- const serverRunnerDir = join18(cwd, SERVER_RUNNER_DIR);
6788
+ const serverRunnerDir = join19(cwd, SERVER_RUNNER_DIR);
5638
6789
  mkdirSync8(serverRunnerDir, { recursive: true });
5639
- const entryPath = join18(serverRunnerDir, fileName);
5640
- if (!existsSync15(entryPath)) {
5641
- const tmp = `${entryPath}.${process.pid}.tmp`;
5642
- writeFileSync13(tmp, content, "utf-8");
6790
+ const entryPath = join19(serverRunnerDir, fileName);
6791
+ if (readIfPresent(entryPath) === content) {
6792
+ return entryPath;
6793
+ }
6794
+ const tmp = `${entryPath}.${process.pid}.tmp`;
6795
+ try {
6796
+ writeFileSync14(tmp, content, "utf-8");
5643
6797
  renameSync(tmp, entryPath);
6798
+ } catch (err2) {
6799
+ removeQuietly(tmp);
6800
+ if (!existsSync16(entryPath)) {
6801
+ throw err2;
6802
+ }
6803
+ if (readIfPresent(entryPath) !== content) {
6804
+ console.error(`Warning: could not refresh ${entryPath} (${err2 instanceof Error ? err2.message : String(err2)}); running the existing entry.`);
6805
+ }
5644
6806
  }
5645
6807
  return entryPath;
5646
6808
  }
5647
6809
  function runArgs(opts) {
5648
6810
  return [opts.entrypoint ?? "", opts.function ?? "", opts.input ?? "{}", opts.inputFile ?? "", opts.context ?? "", opts.contextFile ?? "", opts.derivedFile ?? ""];
5649
6811
  }
5650
- function onChildExit(proc, missingMessage) {
6812
+ var SIGNAL_EXIT_GRACE_MS = 2000;
6813
+ function onChildExit(proc, missingMessage, forwardSignals) {
6814
+ let forwarded;
6815
+ if (forwardSignals && process.platform !== "win32") {
6816
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
6817
+ process.once(signal, () => {
6818
+ forwarded = signal;
6819
+ proc.kill(signal);
6820
+ setTimeout(() => process.kill(process.pid, signal), SIGNAL_EXIT_GRACE_MS).unref();
6821
+ });
6822
+ }
6823
+ }
5651
6824
  proc.on("error", (err2) => {
5652
6825
  console.error(err2.code === "ENOENT" ? missingMessage : err2);
5653
6826
  process.exit(1);
5654
6827
  });
5655
- proc.on("exit", (code) => process.exit(code ?? 0));
6828
+ proc.on("exit", (code, signal) => {
6829
+ if (forwarded) {
6830
+ process.kill(process.pid, forwarded);
6831
+ return;
6832
+ }
6833
+ process.exit(code ?? (signal ? 1 : 0));
6834
+ });
5656
6835
  }
5657
6836
  function runDeno(cwd, opts) {
5658
6837
  const entryPath = writeRunEntry(cwd, "run-deno.ts", DENO_ENTRY_CONTENT);
5659
- const deno = process.env.DENO_BINARY ?? (process.platform === "win32" ? "deno.exe" : "deno");
6838
+ const deno = resolveDeno();
5660
6839
  const denoArgs = [
5661
6840
  "run",
5662
6841
  ...denoPermissionFlags(cwd, opts.production),
5663
6842
  "--no-check",
6843
+ ...inspectorFlags(opts),
5664
6844
  entryPath,
5665
6845
  ...runArgs(opts)
5666
6846
  ];
5667
- const proc = spawn2(deno, denoArgs, { cwd, env: process.env, stdio: "inherit" });
5668
- onChildExit(proc, "Deno not found. Ensure DENO_BINARY is set or deno is on PATH.");
6847
+ const proc = spawn2(deno, denoArgs, { cwd, env: runEnv(opts), stdio: "inherit" });
6848
+ onChildExit(proc, "Deno not found. Ensure DENO_BINARY is set or deno is on PATH.", inspectorFlags(opts).length > 0);
6849
+ }
6850
+ function nodeCommand(cwd, inspector) {
6851
+ const loader = inspector.length > 0 ? resolveTsxLoader(cwd) : undefined;
6852
+ if (loader) {
6853
+ return ["node", [...inspector, ...loader]];
6854
+ }
6855
+ const [bin, tsxPrefix] = resolveTsx(cwd);
6856
+ return [bin, [...tsxPrefix, ...inspector]];
5669
6857
  }
5670
6858
  function runNode(cwd, opts) {
5671
6859
  const entryPath = writeRunEntry(cwd, "run-node.ts", NODE_ENTRY_CONTENT);
5672
- const [bin, tsxPrefix] = resolveTsx(cwd);
5673
- const proc = spawn2(bin, [...tsxPrefix, entryPath, ...runArgs(opts)], { cwd, env: process.env, stdio: "inherit" });
5674
- onChildExit(proc, "tsx not found. Run 'uipath-functions setup'.");
6860
+ const inspector = inspectorFlags(opts);
6861
+ let bin;
6862
+ let prefix;
6863
+ try {
6864
+ [bin, prefix] = nodeCommand(cwd, inspector);
6865
+ } catch (err2) {
6866
+ console.error(err2 instanceof Error ? err2.message : String(err2));
6867
+ process.exit(1);
6868
+ }
6869
+ const proc = spawn2(bin, [...prefix, entryPath, ...runArgs(opts)], { cwd, env: runEnv(opts), stdio: "inherit" });
6870
+ onChildExit(proc, "node not found. Run 'uipath-functions setup'.", inspector.length > 0);
5675
6871
  }
5676
6872
  function registerInvokeCommand(program2) {
5677
6873
  program2.command("invoke <path>").description("Invoke a function against the local serve endpoint over HTTP (dev convenience). Pass the function's HTTP path, e.g. /hello.").option("--port <port>", "Port the local server is running on", "7070").option("--input <json>", "JSON input payload", "{}").action(async (path3, opts) => {
@@ -5707,8 +6903,15 @@ ${err2.message}`);
5707
6903
  });
5708
6904
  }
5709
6905
  function registerPrepareRuntimeCommand(program2) {
5710
- program2.command("runtime-install").description("Create a runner folder with a package.json and install runtime dependencies.").requiredOption("--path <folder>", "Target folder to create and install into").action((opts) => {
6906
+ program2.command("runtime-install").description("Create a runner folder with a package.json and install runtime dependencies.").requiredOption("--path <folder>", "Target folder to create and install into").addOption(new Option("--package-manager <name-or-path>", "Install with this package manager instead of the folder's own").hideHelp()).action((opts) => {
5711
6907
  const runnerDir = resolve10(opts.path);
6908
+ let manager;
6909
+ try {
6910
+ manager = resolvePackageManager(runnerDir, opts.packageManager);
6911
+ } catch (err2) {
6912
+ console.error(err2 instanceof Error ? err2.message : String(err2));
6913
+ process.exit(1);
6914
+ }
5712
6915
  mkdirSync9(runnerDir, { recursive: true });
5713
6916
  const pkg = {
5714
6917
  name: "runner",
@@ -5717,37 +6920,30 @@ function registerPrepareRuntimeCommand(program2) {
5717
6920
  dependencies: {
5718
6921
  "@uipath/coded-functions-js-runtime": RUNTIME_VERSION,
5719
6922
  "@uipath/coreipc": COREIPC_VERSION,
5720
- "@hono/node-server": HONO_NODE_VERSION,
5721
6923
  tsx: TSX_VERSION,
5722
6924
  "@microsoft/signalr": SIGNALR_VERSION,
5723
6925
  "@jridgewell/trace-mapping": TRACE_MAPPING_VERSION
5724
6926
  }
5725
6927
  };
5726
- const pkgPath = join19(runnerDir, "package.json");
5727
- writeFileSync14(pkgPath, JSON.stringify(pkg, null, 2), "utf-8");
6928
+ const pkgPath = join20(runnerDir, "package.json");
6929
+ writeFileSync15(pkgPath, JSON.stringify(pkg, null, 2), "utf-8");
5728
6930
  console.log(`Wrote ${pkgPath}`);
5729
- if (process.env["GITHUB_TOKEN"]) {
5730
- writeFileSync14(join19(runnerDir, ".npmrc"), NPM_RC, "utf-8");
5731
- }
6931
+ writeRunnerRegistryConfig(runnerDir);
5732
6932
  console.log("Installing dependencies...");
5733
- const { cmd, args } = getInstallCommand(true);
5734
- const result = spawnSync4(cmd, args, {
5735
- cwd: runnerDir,
5736
- stdio: "inherit",
5737
- shell: process.platform === "win32"
5738
- });
5739
- if (result.status !== 0) {
5740
- console.error(`${cmd} install failed in ${runnerDir}.`);
6933
+ try {
6934
+ manager.runInstall(runnerDir, { production: true });
6935
+ } catch (err2) {
6936
+ console.error(err2 instanceof Error ? err2.message : String(err2));
5741
6937
  process.exit(1);
5742
6938
  }
5743
6939
  console.log(`Runner ready at ${runnerDir}`);
5744
6940
  });
5745
6941
  }
5746
6942
  function registerInstallServerCommand(program2) {
5747
- program2.command("install-server").description("Prepare runtime dependencies for running the function server.").option("--template <path>", "Path to the server-runner template folder").action((opts) => {
6943
+ program2.command("install-server").description("Provision a packed project: install the server-runner and, when node_modules is missing, its production dependencies.").option("--template <path>", "Path to the server-runner template folder").addOption(new Option("--package-manager <name-or-path>", "Install with this package manager instead of the project's own").hideHelp()).action((opts) => {
5748
6944
  const cwd = resolve11(".");
5749
6945
  try {
5750
- setupRunDependencies(cwd, opts.template);
6946
+ provisionPackage(cwd, opts.template, opts.packageManager);
5751
6947
  } catch (err2) {
5752
6948
  console.error(err2 instanceof Error ? err2.message : String(err2));
5753
6949
  process.exit(1);
@@ -5760,27 +6956,27 @@ var DEFAULT_INSPECT = "127.0.0.1:9231";
5760
6956
  var BRIDGE_FILE = "debug-bridge.ts";
5761
6957
  var WORKER_FILE = "debug-job-worker.ts";
5762
6958
  function resolveDebugAssetsDir(moduleUrl) {
5763
- const moduleDir = dirname4(fileURLToPath2(moduleUrl));
6959
+ const moduleDir = dirname5(fileURLToPath2(moduleUrl));
5764
6960
  const candidates = [
5765
- join20(moduleDir, "deno-runtime", "debug"),
5766
- join20(moduleDir, "..", "deno-runtime", "debug"),
5767
- join20(moduleDir, "..", "..", "deno-runtime", "debug")
6961
+ join21(moduleDir, "deno-runtime", "debug"),
6962
+ join21(moduleDir, "..", "deno-runtime", "debug"),
6963
+ join21(moduleDir, "..", "..", "deno-runtime", "debug")
5768
6964
  ];
5769
6965
  for (const candidate of candidates) {
5770
- if (existsSync16(join20(candidate, BRIDGE_FILE))) {
6966
+ if (existsSync17(join21(candidate, BRIDGE_FILE))) {
5771
6967
  return candidate;
5772
6968
  }
5773
6969
  }
5774
6970
  throw new Error(`debug assets not found (looked in: ${candidates.join(", ")})`);
5775
6971
  }
5776
6972
  function stageDebugAssets(cwd) {
5777
- const stagedDir = join20(cwd, SERVER_RUNNER_DIR, "debug");
6973
+ const stagedDir = join21(cwd, SERVER_RUNNER_DIR, "debug");
5778
6974
  mkdirSync10(stagedDir, { recursive: true });
5779
6975
  const assetsDir = resolveDebugAssetsDir(import.meta.url);
5780
6976
  for (const entry of readdirSync6(assetsDir)) {
5781
- writeFileSync15(join20(stagedDir, entry), readFileSync14(join20(assetsDir, entry), "utf-8"), "utf-8");
6977
+ writeFileSync16(join21(stagedDir, entry), readFileSync16(join21(assetsDir, entry), "utf-8"), "utf-8");
5782
6978
  }
5783
- return { bridge: join20(stagedDir, BRIDGE_FILE), worker: join20(stagedDir, WORKER_FILE) };
6979
+ return { bridge: join21(stagedDir, BRIDGE_FILE), worker: join21(stagedDir, WORKER_FILE) };
5784
6980
  }
5785
6981
  function buildBridgeSpawn(bridgePath, workerEntry, opts) {
5786
6982
  const modeEnv = opts.runAsJob ? {
@@ -5823,7 +7019,7 @@ function buildBridgeSpawn(bridgePath, workerEntry, opts) {
5823
7019
  };
5824
7020
  }
5825
7021
  function registerDebugCommand(program2) {
5826
- program2.command("debug").description("Debug a coded function: bridges StudioWeb's SignalR DebugHub to the Deno V8 inspector for line breakpoints.").option("--session <id>", "Debug session id / jobKey (must match the FE debug hub group)").option("--hub <url>", "SignalR DebugHub relay URL", DEFAULT_HUB).option("--run-as-job", "Debug a one-shot coded function job without an HTTP server").option("--entrypoint <path>", "Path to the function file (run-as-job mode)").option("--function <name>", "Which function from uipath.json to debug (default: the first)").option("--port <port>", "Port the debug server listens on", String(DEFAULT_PORT2)).option("--input <json>", "JSON input passed to the function's main method", "{}").option("--input-file <path>", "Path to a JSON input file (takes priority over --input)").option("--context <json>", "JSON runtime-context payload (used when --context-file is absent)").option("--context-file <path>", "Path to the runtime-context JSON file (takes priority over --context)").option("--production", "Use the preinstalled server-runner dependencies when available").option("--inspect <endpoint>", "V8 inspector endpoint for the spawned runner", DEFAULT_INSPECT).option("--token <jwt>", "Bearer token for a remote SignalR hub. Falls back to env HUB_ACCESS_TOKEN when omitted; leave both unset for an unauthenticated local hub.", "").action(async (opts) => {
7022
+ program2.command("debug").description("Debug a coded function: bridges StudioWeb's SignalR DebugHub to the Deno V8 inspector for line breakpoints. Without Deno, --run-as-job falls back to a plain Node run of the same job.").option("--session <id>", "Debug session id / jobKey (must match the FE debug hub group)").option("--hub <url>", "SignalR DebugHub relay URL", DEFAULT_HUB).option("--run-as-job", "Debug a one-shot coded function job without an HTTP server").option("--entrypoint <path>", "Path to the function file (run-as-job mode)").option("--function <name>", "Which function from uipath.json to debug (default: the first)").option("--port <port>", "Port the debug server listens on", String(DEFAULT_PORT2)).option("--input <json>", "JSON input passed to the function's main method", "{}").option("--input-file <path>", "Path to a JSON input file (takes priority over --input)").option("--context <json>", "JSON runtime-context payload (used when --context-file is absent)").option("--context-file <path>", "Path to the runtime-context JSON file (takes priority over --context)").option("--production", "Use the preinstalled server-runner dependencies when available").option("--inspect <endpoint>", "V8 inspector endpoint for the spawned runner", DEFAULT_INSPECT).option("--token <jwt>", "Bearer token for a remote SignalR hub. Falls back to env HUB_ACCESS_TOKEN when omitted; leave both unset for an unauthenticated local hub.", "").action(async (opts) => {
5827
7023
  const cwd = resolve12(".");
5828
7024
  const runAsJob = opts.runAsJob === true;
5829
7025
  if (opts.entrypoint && !runAsJob) {
@@ -5838,17 +7034,17 @@ function registerDebugCommand(program2) {
5838
7034
  console.error("Provide only one of --entrypoint or --function.");
5839
7035
  process.exit(1);
5840
7036
  }
5841
- const uipathJsonPath = join20(cwd, "uipath.json");
5842
- if (!existsSync16(uipathJsonPath) && (!runAsJob || !opts.entrypoint)) {
7037
+ const uipathJsonPath = join21(cwd, "uipath.json");
7038
+ if (!existsSync17(uipathJsonPath) && (!runAsJob || !opts.entrypoint)) {
5843
7039
  console.error("No uipath.json found. Run 'uipath-functions init' first.");
5844
7040
  process.exit(1);
5845
7041
  }
5846
- if (!opts.entrypoint && existsSync16(uipathJsonPath) && syncFunctionsMap(cwd)) {
7042
+ if (!opts.entrypoint && existsSync17(uipathJsonPath) && syncFunctionsMap(cwd)) {
5847
7043
  console.log("Updated functions map in uipath.json.");
5848
7044
  }
5849
7045
  const functions = {};
5850
- if (existsSync16(uipathJsonPath)) {
5851
- const uipathJson = JSON.parse(readFileSync14(uipathJsonPath, "utf-8"));
7046
+ if (existsSync17(uipathJsonPath)) {
7047
+ const uipathJson = JSON.parse(readFileSync16(uipathJsonPath, "utf-8"));
5852
7048
  if (typeof uipathJson === "object" && uipathJson !== null && "functions" in uipathJson && typeof uipathJson.functions === "object" && uipathJson.functions !== null) {
5853
7049
  for (const [name, entry] of Object.entries(uipathJson.functions)) {
5854
7050
  if (typeof entry === "string") {
@@ -5885,15 +7081,40 @@ function registerDebugCommand(program2) {
5885
7081
  }
5886
7082
  const fnName = opts.entrypoint ? "" : opts.function ?? names[0] ?? "";
5887
7083
  const port = runAsJob ? undefined : parseInt(opts.port, 10) || DEFAULT_PORT2;
5888
- const skipInstall = opts.production === true && existsSync16(join20(cwd, SERVER_RUNNER_DIR));
7084
+ if (opts.production !== true) {
7085
+ try {
7086
+ assertDependenciesInstalled(cwd);
7087
+ } catch (err2) {
7088
+ console.error(err2 instanceof Error ? err2.message : String(err2));
7089
+ process.exit(1);
7090
+ }
7091
+ }
7092
+ const skipInstall = opts.production === true && existsSync17(join21(cwd, SERVER_RUNNER_DIR));
5889
7093
  if (!skipInstall) {
5890
7094
  try {
5891
- setupRunDependencies(cwd);
7095
+ installServerRunner(cwd);
5892
7096
  } catch (err2) {
5893
7097
  console.error(err2 instanceof Error ? err2.message : String(err2));
5894
7098
  process.exit(1);
5895
7099
  }
5896
7100
  }
7101
+ if (!denoAvailable()) {
7102
+ if (!runAsJob) {
7103
+ console.error("Deno not found, and the HTTP debug bridge needs it. Install it with 'uipath-functions setup --runtime deno', or debug a single invocation with --run-as-job.");
7104
+ process.exit(1);
7105
+ }
7106
+ console.error("Deno not found: running the job under Node instead, without breakpoints or the debug hub bridge. Install Deno with 'uipath-functions setup --runtime deno' for a full debug session.");
7107
+ const selector = { entrypoint: opts.entrypoint, function: fnName || undefined, production: opts.production };
7108
+ runNode(cwd, {
7109
+ ...selector,
7110
+ input: inputJson,
7111
+ inputFile: opts.inputFile,
7112
+ context: opts.context,
7113
+ contextFile: opts.contextFile,
7114
+ derivedFile: writeDerivedContract(cwd, selector)
7115
+ });
7116
+ return;
7117
+ }
5897
7118
  const staged = stageDebugAssets(cwd);
5898
7119
  let workerEntry;
5899
7120
  let derivedFile = "";
@@ -5901,7 +7122,9 @@ function registerDebugCommand(program2) {
5901
7122
  derivedFile = writeDerivedContract(cwd, { entrypoint: opts.entrypoint, function: opts.function, production: opts.production });
5902
7123
  workerEntry = staged.worker;
5903
7124
  } else {
5904
- const derived = deriveMarkerContracts(functions, cwd);
7125
+ const extraction = extractProject(functions, cwd);
7126
+ reportDiagnosticsOrExit(extraction.diagnostics);
7127
+ const derived = toDerivedContracts(extraction.functions);
5905
7128
  const aggregatorPath = generateAggregator(functions, cwd, "serve", derived);
5906
7129
  workerEntry = writeDenoServeEntry(cwd, port, aggregatorPath);
5907
7130
  freePort(port);
@@ -5920,13 +7143,13 @@ function registerDebugCommand(program2) {
5920
7143
  context: opts.context ?? "",
5921
7144
  contextFile: opts.contextFile ?? "",
5922
7145
  token: opts.token && opts.token.length > 0 ? opts.token : process.env.HUB_ACCESS_TOKEN ?? "",
5923
- envFile: existsSync16(join20(cwd, ".env")) ? ".env" : "",
7146
+ envFile: existsSync17(join21(cwd, ".env")) ? ".env" : "",
5924
7147
  derivedFile
5925
7148
  };
5926
7149
  const { args, env } = buildBridgeSpawn(staged.bridge, workerEntry, resolved);
5927
7150
  const target = resolved.entrypoint || resolved.functionName;
5928
7151
  console.log(runAsJob ? `Debug bridge: session=${resolved.session} hub=${resolved.hub} job=${target} inspector=${resolved.inspect}` : `Debug bridge: session=${resolved.session} hub=${resolved.hub} function=${fnName} port=${port} inspector=${resolved.inspect}`);
5929
- const deno = process.env.DENO_BINARY ?? (process.platform === "win32" ? "deno.exe" : "deno");
7152
+ const deno = resolveDeno();
5930
7153
  const proc = spawn3(deno, args, {
5931
7154
  cwd,
5932
7155
  env: { ...process.env, ...env },
@@ -5943,8 +7166,8 @@ function registerDebugCommand(program2) {
5943
7166
  proc.on("exit", (code) => process.exit(code ?? 0));
5944
7167
  });
5945
7168
  }
5946
- var __dirname3 = dirname5(fileURLToPath3(import.meta.url));
5947
- var pkg = JSON.parse(readFileSync15(join21(__dirname3, "..", "package.json"), "utf-8"));
7169
+ var __dirname3 = dirname6(fileURLToPath3(import.meta.url));
7170
+ var pkg = JSON.parse(readFileSync17(join22(__dirname3, "..", "package.json"), "utf-8"));
5948
7171
  function buildProgram() {
5949
7172
  const program2 = new Command;
5950
7173
  program2.name("uipath-functions").description("Build, serve, and publish UiPath JS/TS Functions").version(pkg.version);
@@ -5967,4 +7190,4 @@ async function cliRunner(args) {
5967
7190
  }
5968
7191
  export { generateManifests, cliRunner };
5969
7192
 
5970
- //# debugId=DF52938DC2551B7B64756E2164756E21
7193
+ //# debugId=A1F90FDD6E84435C64756E2164756E21