@highstate/common 0.9.27 → 0.9.28

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.
@@ -794,7 +794,8 @@ var AccessPointRoute = class extends ComponentResource {
794
794
  {
795
795
  providers: output(args.accessPoint).dnsProviders,
796
796
  values: this.route.endpoints,
797
- waitAt: "local"
797
+ waitAt: "local",
798
+ proxied: accessPoint.proxied
798
799
  },
799
800
  { ...opts, parent: this }
800
801
  );
@@ -1445,5 +1446,5 @@ async function createServerEntity({
1445
1446
  }
1446
1447
 
1447
1448
  export { AccessPointRoute, Command, DnsRecord, DnsRecordSet, GatewayRoute, ImplementationMediator, MaterializedFile, MaterializedFolder, TlsCertificate, archiveFromFolder, assetFromFile, createServerBundle, createServerEntity, createSshTerminal, dnsRecordMediator, fetchFileSize, filterEndpoints, gatewayRouteMediator, generateKey, generatePassword, generateSshPrivateKey, getNameByEndpoint, getServerConnection, l34EndpointToString, l3EndpointToCidr, l3EndpointToL4, l3EndpointToString, l4EndpointToString, l4EndpointWithProtocolToString, l7EndpointToString, parseEndpoints, parseL34Endpoint, parseL3Endpoint, parseL4Endpoint, parseL7Endpoint, requireInputL3Endpoint, requireInputL4Endpoint, sshPrivateKeyToKeyPair, tlsCertificateMediator, updateEndpoints, updateEndpointsWithFqdn };
1448
- //# sourceMappingURL=chunk-FHSPC2ZL.js.map
1449
- //# sourceMappingURL=chunk-FHSPC2ZL.js.map
1449
+ //# sourceMappingURL=chunk-RKTGGVPZ.js.map
1450
+ //# sourceMappingURL=chunk-RKTGGVPZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shared/network.ts","../src/shared/command.ts","../src/shared/impl-ref.ts","../src/shared/dns.ts","../src/shared/gateway.ts","../src/shared/tls.ts","../src/shared/access-point.ts","../src/shared/files.ts","../src/shared/passwords.ts","../assets/images.json","../src/shared/ssh.ts"],"names":["ssh","command","environment","env","triggers","toPromise","output","ComponentResource","resolvedType","interpolate","mat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AS,aAAA,CAAc,MAAA,CAAO,MAAM,CAAA,CAAA,KAAK,CAAA,CAAE,MAAM,CAAA;AAAA,MACjD,UAAU,UAAA,CAAW,QAAA;AAAA,MACrB,SAAS,UAAA,GACL,UAAA,GACA,aAAA,GACE,sBAAA,CAAuB,aAAa,CAAA,GACpC;AAAA;AACR,GACD,CAAA;AACH","file":"chunk-RKTGGVPZ.js","sourcesContent":["import type { ArrayPatchMode, network } from \"@highstate/library\"\nimport { type Input, toPromise } from \"@highstate/pulumi\"\nimport { uniqueBy } from \"remeda\"\n\n/**\n * The L3 or L4 endpoint for some service.\n *\n * The format is: `[protocol://]endpoint[:port]`\n */\nexport type InputL34Endpoint = network.L34Endpoint | string\n\n/**\n * The L3 endpoint for some service.\n */\nexport type InputL3Endpoint = network.L3Endpoint | string\n\n/**\n * The L4 endpoint for some service.\n */\nexport type InputL4Endpoint = network.L4Endpoint | string\n\n/**\n * The L7 endpoint for some service.\n *\n * The format is: `appProtocol://endpoint[:port][/resource]`\n */\nexport type InputL7Endpoint = network.L7Endpoint | string\n\n/**\n * Stringifies a L3 endpoint object into a string.\n *\n * @param l3Endpoint The L3 endpoint object to stringify.\n * @returns The string representation of the L3 endpoint.\n */\nexport function l3EndpointToString(l3Endpoint: network.L3Endpoint): string {\n switch (l3Endpoint.type) {\n case \"ipv4\":\n return l3Endpoint.address\n case \"ipv6\":\n return l3Endpoint.address\n case \"hostname\":\n return l3Endpoint.hostname\n }\n}\n\n/**\n * Stringifies a L4 endpoint object into a string.\n *\n * @param l4Endpoint The L4 endpoint object to stringify.\n * @returns The string representation of the L4 endpoint.\n */\nexport function l4EndpointToString(l4Endpoint: network.L4Endpoint): string {\n if (l4Endpoint.type === \"ipv6\") {\n return `[${l4Endpoint.address}]:${l4Endpoint.port}`\n }\n\n return `${l3EndpointToString(l4Endpoint)}:${l4Endpoint.port}`\n}\n\n/**\n * Stringifies a L4 endpoint object into a string with protocol.\n *\n * @param l4Endpoint The L4 endpoint object to stringify.\n * @returns The string representation of the L4 endpoint with protocol.\n */\nexport function l4EndpointWithProtocolToString(l4Endpoint: network.L4Endpoint): string {\n const protocol = `${l4Endpoint.protocol}://`\n\n return `${protocol}${l4EndpointToString(l4Endpoint)}`\n}\n\n/**\n * Stringifies a L7 endpoint object into a string.\n *\n * The format is: `appProtocol://endpoint[:port][/resource]`\n * @param l7Endpoint The L7 endpoint object to stringify.\n * @returns The string representation of the L7 endpoint.\n */\nexport function l7EndpointToString(l7Endpoint: network.L7Endpoint): string {\n const protocol = `${l7Endpoint.appProtocol}://`\n\n let endpoint = l4EndpointToString(l7Endpoint)\n\n if (l7Endpoint.resource) {\n endpoint += `/${l7Endpoint.resource}`\n }\n\n return `${protocol}${endpoint}`\n}\n\n/**\n * Stringifies a L3 or L4 endpoint object into a string.\n *\n * @param l34Endpoint The L3 or L4 endpoint object to stringify.\n * @returns The string representation of the L3 or L4 endpoint.\n */\nexport function l34EndpointToString(l34Endpoint: network.L34Endpoint): string {\n if (l34Endpoint.port) {\n return l4EndpointToString(l34Endpoint)\n }\n\n return l3EndpointToString(l34Endpoint)\n}\n\nconst L34_ENDPOINT_RE =\n /^(?:(?<protocol>[a-z]+):\\/\\/)?(?:(?:\\[?(?<ipv6>[0-9A-Fa-f:]+)\\]?)|(?<ipv4>(?:\\d{1,3}\\.){3}\\d{1,3})|(?<hostname>[a-zA-Z0-9-*]+(?:\\.[a-zA-Z0-9-*]+)*))(?::(?<port>\\d{1,5}))?$/\n\nconst L7_ENDPOINT_RE =\n /^(?<appProtocol>[a-z]+):\\/\\/(?:(?:\\[?(?<ipv6>[0-9A-Fa-f:]+)\\]?)|(?<ipv4>(?:\\d{1,3}\\.){3}\\d{1,3})|(?<hostname>[a-zA-Z0-9-*]+(?:\\.[a-zA-Z0-9-*]+)*))(?::(?<port>\\d{1,5}))?(?:\\/(?<resource>.*))?$/\n\n/**\n * Parses a L3 or L4 endpoint from a string.\n *\n * The format is `[protocol://]endpoint[:port]`.\n *\n * @param l34Endpoint The L3 or L4 endpoint string to parse.\n * @returns The parsed L3 or L4 endpoint object.\n */\nexport function parseL34Endpoint(l34Endpoint: InputL34Endpoint): network.L34Endpoint {\n if (typeof l34Endpoint === \"object\") {\n return l34Endpoint\n }\n\n const match = l34Endpoint.match(L34_ENDPOINT_RE)\n if (!match) {\n throw new Error(`Invalid L3/L4 endpoint: \"${l34Endpoint}\"`)\n }\n\n const { protocol, ipv6, ipv4, hostname, port } = match.groups!\n\n if (protocol && protocol !== \"tcp\" && protocol !== \"udp\") {\n throw new Error(`Invalid L4 endpoint protocol: \"${protocol}\"`)\n }\n\n let visibility: network.EndpointVisibility = \"public\"\n\n if (ipv4 && IPV4_PRIVATE_REGEX.test(ipv4)) {\n visibility = \"external\"\n } else if (ipv6 && IPV6_PRIVATE_REGEX.test(ipv6)) {\n visibility = \"external\"\n }\n\n const fallbackProtocol = port ? \"tcp\" : undefined\n\n return {\n type: ipv6 ? \"ipv6\" : ipv4 ? \"ipv4\" : \"hostname\",\n visibility,\n address: ipv6 || ipv4,\n hostname: hostname,\n port: port ? parseInt(port, 10) : undefined,\n protocol: protocol ? (protocol as network.L4Protocol) : fallbackProtocol,\n } as network.L34Endpoint\n}\n\n/**\n * Parses a L3 endpoint from a string.\n *\n * The same as `parseL34Endpoint`, but only for L3 endpoints and will throw an error if the endpoint contains a port.\n *\n * @param l3Endpoint The L3 endpoint string to parse.\n * @returns The parsed L3 endpoint object.\n */\nexport function parseL3Endpoint(l3Endpoint: InputL3Endpoint): network.L3Endpoint {\n if (typeof l3Endpoint === \"object\") {\n return l3Endpoint\n }\n\n const parsed = parseL34Endpoint(l3Endpoint)\n\n if (parsed.port) {\n throw new Error(`Port cannot be specified in L3 endpoint: \"${l3Endpoint}\"`)\n }\n\n return parsed\n}\n\n/**\n * Parses a L4 endpoint from a string.\n *\n * The same as `parseL34Endpoint`, but only for L4 endpoints and will throw an error if the endpoint does not contain a port.\n */\nexport function parseL4Endpoint(l4Endpoint: InputL4Endpoint): network.L4Endpoint {\n if (typeof l4Endpoint === \"object\") {\n return l4Endpoint\n }\n\n const parsed = parseL34Endpoint(l4Endpoint)\n\n if (!parsed.port) {\n throw new Error(`No port found in L4 endpoint: \"${l4Endpoint}\"`)\n }\n\n return parsed\n}\n\nconst IPV4_PRIVATE_REGEX =\n /^(?:10|127)(?:\\.\\d{1,3}){3}$|^(?:172\\.1[6-9]|172\\.2[0-9]|172\\.3[0-1])(?:\\.\\d{1,3}){2}$|^(?:192\\.168)(?:\\.\\d{1,3}){2}$/\n\nconst IPV6_PRIVATE_REGEX =\n /^(?:fc|fd)(?:[0-9a-f]{2}){0,2}::(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}$|^::(?:ffff:(?:10|127)(?:\\.\\d{1,3}){3}|(?:172\\.1[6-9]|172\\.2[0-9]|172\\.3[0-1])(?:\\.\\d{1,3}){2}|(?:192\\.168)(?:\\.\\d{1,3}){2})$/\n\n/**\n * Helper function to get the input L3 endpoint from the raw endpoint or input endpoint.\n *\n * If neither is provided, an error is thrown.\n *\n * @param rawEndpoint The raw endpoint string to parse.\n * @param inputEndpoint The input endpoint object to use if the raw endpoint is not provided.\n * @returns The parsed L3 endpoint object.\n */\nexport async function requireInputL3Endpoint(\n rawEndpoint: string | undefined,\n inputEndpoint: Input<network.L3Endpoint> | undefined,\n): Promise<network.L3Endpoint> {\n if (rawEndpoint) {\n return parseL3Endpoint(rawEndpoint)\n }\n\n if (inputEndpoint) {\n return toPromise(inputEndpoint)\n }\n\n throw new Error(\"No endpoint provided\")\n}\n\n/**\n * Helper function to get the input L4 endpoint from the raw endpoint or input endpoint.\n *\n * If neither is provided, an error is thrown.\n *\n * @param rawEndpoint The raw endpoint string to parse.\n * @param inputEndpoint The input endpoint object to use if the raw endpoint is not provided.\n * @returns The parsed L4 endpoint object.\n */\nexport async function requireInputL4Endpoint(\n rawEndpoint: string | undefined,\n inputEndpoint: Input<network.L4Endpoint> | undefined,\n): Promise<network.L4Endpoint> {\n if (rawEndpoint) {\n return parseL4Endpoint(rawEndpoint)\n }\n\n if (inputEndpoint) {\n return toPromise(inputEndpoint)\n }\n\n throw new Error(\"No endpoint provided\")\n}\n\n/**\n * Converts L3 endpoint to L4 endpoint by adding a port and protocol.\n *\n * @param l3Endpoint The L3 endpoint to convert.\n * @param port The port to add to the L3 endpoint.\n * @param protocol The protocol to add to the L3 endpoint. Defaults to \"tcp\".\n * @returns The L4 endpoint with the port and protocol added.\n */\nexport function l3EndpointToL4(\n l3Endpoint: InputL3Endpoint,\n port: number,\n protocol: network.L4Protocol = \"tcp\",\n): network.L4Endpoint {\n return {\n ...parseL3Endpoint(l3Endpoint),\n port,\n protocol,\n }\n}\n\n/**\n * Filters the endpoints based on the given filter.\n *\n * @param endpoints The list of endpoints to filter.\n * @param filter The filter to apply. If not provided, the endpoints will be filtered by the most accessible type: `public` > `external` > `internal`.\n * @param types The list of endpoint types to filter by. If provided, only endpoints of these types will be returned.\n *\n * @returns The filtered list of endpoints.\n */\nexport function filterEndpoints<\n TEndpoint extends network.L34Endpoint,\n TType extends network.L34Endpoint[\"type\"],\n>(\n endpoints: TEndpoint[],\n filter?: network.EndpointFilter,\n types?: TType[],\n): (TEndpoint & { type: TType })[] {\n if (filter?.length) {\n endpoints = endpoints.filter(endpoint => filter.includes(endpoint.visibility))\n } else if (endpoints.some(endpoint => endpoint.visibility === \"public\")) {\n endpoints = endpoints.filter(endpoint => endpoint.visibility === \"public\")\n } else if (endpoints.some(endpoint => endpoint.visibility === \"external\")) {\n endpoints = endpoints.filter(endpoint => endpoint.visibility === \"external\")\n }\n\n if (types?.length) {\n endpoints = endpoints.filter(endpoint => types.includes(endpoint.type as TType))\n }\n\n return endpoints as (TEndpoint & { type: TType })[]\n}\n\n/**\n * Converts a L3 endpoint to CIDR notation.\n *\n * If the endpoint is a hostname, an error is thrown.\n *\n * @param l3Endpoint The L3 endpoint to convert.\n * @returns The CIDR notation of the L3 endpoint.\n */\nexport function l3EndpointToCidr(l3Endpoint: network.L3Endpoint): string {\n switch (l3Endpoint.type) {\n case \"ipv4\":\n return `${l3Endpoint.address}/32`\n case \"ipv6\":\n return `${l3Endpoint.address}/128`\n case \"hostname\":\n throw new Error(\"Cannot convert hostname to CIDR\")\n }\n}\n\nconst udpAppProtocols = [\"dns\", \"dhcp\"]\n\n/**\n * Parses a L7 endpoint from a string.\n *\n * The format is: `appProtocol://endpoint[:port][/resource]`\n *\n * @param l7Endpoint The L7 endpoint string to parse.\n * @returns The parsed L7 endpoint object.\n */\nexport function parseL7Endpoint(l7Endpoint: InputL7Endpoint): network.L7Endpoint {\n if (typeof l7Endpoint === \"object\") {\n return l7Endpoint\n }\n\n const match = l7Endpoint.match(L7_ENDPOINT_RE)\n if (!match) {\n throw new Error(`Invalid L7 endpoint: \"${l7Endpoint}\"`)\n }\n\n const { appProtocol, ipv6, ipv4, hostname, port, resource } = match.groups!\n\n let visibility: network.EndpointVisibility = \"public\"\n\n if (ipv4 && IPV4_PRIVATE_REGEX.test(ipv4)) {\n visibility = \"external\"\n } else if (ipv6 && IPV6_PRIVATE_REGEX.test(ipv6)) {\n visibility = \"external\"\n }\n\n return {\n type: ipv6 ? \"ipv6\" : ipv4 ? \"ipv4\" : \"hostname\",\n visibility,\n address: ipv6 || ipv4,\n hostname: hostname,\n\n // Default port for L7 endpoints (TODO: add more specific defaults for common protocols)\n port: port ? parseInt(port, 10) : 443,\n\n // L7 endpoints typically use TCP, but can also use UDP for specific protocols\n protocol: udpAppProtocols.includes(appProtocol) ? \"udp\" : \"tcp\",\n\n appProtocol,\n resource: resource || \"\",\n } as network.L7Endpoint\n}\n\n/**\n * Updates the endpoints based on the given mode.\n *\n * @param currentEndpoints The current endpoints to update.\n * @param endpoints The new endpoints to add in string format.\n * @param inputEndpoints The input endpoints to add in object format.\n * @param mode The mode to use when updating the endpoints. Can be \"replace\" or \"prepend\". Defaults to \"prepend\".\n * @returns The updated list of endpoints with duplicates removed.\n */\nexport async function updateEndpoints<TEndpoints extends network.L34Endpoint>(\n currentEndpoints: Input<TEndpoints[]>,\n endpoints: string[] | undefined,\n inputEndpoints: Input<TEndpoints[]> | undefined,\n mode: ArrayPatchMode = \"prepend\",\n): Promise<TEndpoints[]> {\n const resolvedCurrentEndpoints = await toPromise(currentEndpoints)\n const newEndpoints = await parseEndpoints(endpoints, inputEndpoints)\n\n if (mode === \"replace\") {\n return newEndpoints as TEndpoints[]\n }\n\n return uniqueBy(\n [...newEndpoints, ...resolvedCurrentEndpoints],\n l34EndpointToString,\n ) as TEndpoints[]\n}\n\n/**\n * Parses a list of endpoints from strings and input objects.\n *\n * @param endpoints The list of endpoint strings to parse.\n * @param inputEndpoints The list of input endpoint objects to use.\n * @returns The parsed list of endpoint objects with duplicates removed.\n */\nexport async function parseEndpoints<TEndpoints extends network.L34Endpoint>(\n endpoints: string[] | undefined,\n inputEndpoints: Input<TEndpoints[]> | undefined,\n): Promise<TEndpoints[]> {\n const resolvedInputEndpoints = await toPromise(inputEndpoints)\n\n return uniqueBy(\n [...(endpoints?.map(parseL34Endpoint) ?? []), ...(resolvedInputEndpoints ?? [])],\n l34EndpointToString,\n ) as TEndpoints[]\n}\n","import type { common, ssh } from \"@highstate/library\"\nimport { homedir } from \"node:os\"\nimport {\n ComponentResource,\n type ComponentResourceOptions,\n type Input,\n type InputOrArray,\n interpolate,\n type Output,\n output,\n toPromise,\n} from \"@highstate/pulumi\"\nimport { sha256 } from \"@noble/hashes/sha2\"\nimport { local, remote, type types } from \"@pulumi/command\"\nimport { flat } from \"remeda\"\nimport { l3EndpointToString } from \"./network\"\n\n/**\n * Creates a connection object for the given SSH credentials.\n *\n * @param ssh The SSH credentials.\n * @returns An output connection object for Pulumi remote commands.\n */\nexport function getServerConnection(\n ssh: Input<ssh.Connection>,\n): Output<types.input.remote.ConnectionArgs> {\n return output(ssh).apply(ssh => ({\n host: l3EndpointToString(ssh.endpoints[0]),\n port: ssh.endpoints[0].port,\n user: ssh.user,\n password: ssh.password,\n privateKey: ssh.keyPair?.privateKey,\n dialErrorLimit: 3,\n hostKey: ssh.hostKey,\n }))\n}\n\nexport type CommandHost = \"local\" | Input<common.Server>\nexport type CommandRunMode = \"auto\" | \"prefer-host\"\n\nexport type CommandArgs = {\n /**\n * The host to run the command on.\n *\n * Can be \"local\" for local execution or a server object for remote execution.\n */\n host: CommandHost\n\n /**\n * The command to run when the resource is created.\n *\n * If an array is provided, it will be joined with spaces.\n */\n create: InputOrArray<string>\n\n /**\n * The command to run when the resource is updated or one of the triggers changes.\n *\n * If not set, the `create` command will be used.\n */\n update?: InputOrArray<string>\n\n /**\n * The command to run when the resource is deleted.\n */\n delete?: InputOrArray<string>\n\n /**\n * The stdin content to pass to the command.\n */\n stdin?: Input<string>\n\n /**\n * The logging level for the command.\n */\n logging?: Input<local.Logging>\n\n /**\n * The triggers for the command.\n *\n * They will be captured in the command's state and will trigger the command to run again\n * if they change.\n */\n triggers?: InputOrArray<unknown>\n\n /**\n * The update triggers for the command.\n *\n * Unlike `triggers`, which replace the entire resource on change, these will only trigger the `update` command.\n *\n * Under the hood, it is implemented using a hash of the provided values and passing it as environment variable.\n * It is recommended to pass only primitive values (strings, numbers, booleans) or small objects/arrays for proper serialization.\n */\n updateTriggers?: InputOrArray<unknown>\n\n /**\n * The working directory for the command.\n *\n * If not set, the command will run in the user's home directory (for both local and remote hosts).\n */\n cwd?: Input<string>\n\n /**\n * The environment variables to set for the command.\n */\n environment?: Input<Record<string, Input<string>>>\n\n /**\n * The run mode for the command.\n *\n * - `auto` (default): if the `image` is set, it will always run in a container, never on the host;\n * otherwise, it will run on the host.\n *\n * - `prefer-host`: it will try to run on the host if the executable is available;\n * otherwise, it will run in a container or throw an error if the `image` is not set.\n */\n runMode?: CommandRunMode\n\n /**\n * The container image to use to run the command.\n */\n image?: Input<string>\n\n /**\n * The paths to mount if the command runs in a container.\n *\n * They will be mounted to the same paths in the container.\n */\n mounts?: InputOrArray<string>\n}\n\nexport type TextFileArgs = {\n /**\n * The host to run the command on.\n */\n host: CommandHost\n\n /**\n * The absolute path to the file on the host.\n */\n path: Input<string>\n\n /**\n * The content to write to the file.\n */\n content: Input<string>\n}\n\nexport type WaitForArgs = CommandArgs & {\n /**\n * The timeout in seconds to wait for the command to complete.\n *\n * Defaults to 5 minutes (300 seconds).\n */\n timeout?: Input<number>\n\n /**\n * The interval in seconds to wait between checks.\n *\n * Defaults to 5 seconds.\n */\n interval?: Input<number>\n}\n\nfunction createCommand(command: string | string[]): string {\n if (Array.isArray(command)) {\n return command.join(\" \")\n }\n\n return command\n}\n\nfunction wrapWithWorkDir(dir?: Input<string>) {\n if (!dir) {\n return (command: string) => output(command)\n }\n\n return (command: string) => interpolate`cd \"${dir}\" && ${command}`\n}\n\nfunction wrapWithEnvironment(environment?: Input<Record<string, Input<string>>>) {\n if (!environment) {\n return (command: string) => output(command)\n }\n\n return (command: string) =>\n output({ command, environment }).apply(({ command, environment }) => {\n if (!environment || Object.keys(environment).length === 0) {\n return command\n }\n\n const envExport = Object.entries(environment)\n .map(([key, value]) => `export ${key}=\"${value}\"`)\n .join(\" && \")\n\n return `${envExport} && ${command}`\n })\n}\n\nfunction wrapWithWaitFor(timeout: Input<number> = 300, interval: Input<number> = 5) {\n return (command: string | string[]) =>\n // TOD: escape the command\n interpolate`timeout ${timeout} bash -c 'while ! ${createCommand(command)}; do sleep ${interval}; done'`\n}\n\nfunction applyUpdateTriggers(\n env: Input<Record<string, Input<string>>> | undefined,\n triggers: InputOrArray<unknown> | undefined,\n) {\n return output({ env, triggers }).apply(({ env, triggers }) => {\n if (!triggers) {\n return env\n }\n\n const hash = sha256(JSON.stringify(triggers))\n const hashHex = Buffer.from(hash).toString(\"hex\")\n\n return {\n ...env,\n HIGHSTATE_UPDATE_TRIGGER_HASH: hashHex,\n }\n })\n}\n\nexport class Command extends ComponentResource {\n public readonly stdout: Output<string>\n public readonly stderr: Output<string>\n\n constructor(name: string, args: CommandArgs, opts?: ComponentResourceOptions) {\n super(\"highstate:common:Command\", name, args, opts)\n\n const environment = applyUpdateTriggers(\n args.environment,\n args.updateTriggers,\n ) as local.CommandArgs[\"environment\"]\n\n const command =\n args.host === \"local\"\n ? new local.Command(\n name,\n {\n create: output(args.create).apply(createCommand),\n update: args.update ? output(args.update).apply(createCommand) : undefined,\n delete: args.delete ? output(args.delete).apply(createCommand) : undefined,\n logging: args.logging,\n triggers: args.triggers ? output(args.triggers).apply(flat) : undefined,\n dir: args.cwd ?? homedir(),\n environment,\n stdin: args.stdin,\n },\n { ...opts, parent: this },\n )\n : new remote.Command(\n name,\n {\n connection: output(args.host).apply(server => {\n if (!server.ssh) {\n throw new Error(`The server \"${server.hostname}\" has no SSH credentials`)\n }\n\n return getServerConnection(server.ssh)\n }),\n\n create: output(args.create)\n .apply(createCommand)\n .apply(wrapWithWorkDir(args.cwd))\n .apply(wrapWithEnvironment(environment)),\n\n update: args.update\n ? output(args.update)\n .apply(createCommand)\n .apply(wrapWithWorkDir(args.cwd))\n .apply(wrapWithEnvironment(environment))\n : undefined,\n\n delete: args.delete\n ? output(args.delete)\n .apply(createCommand)\n .apply(wrapWithWorkDir(args.cwd))\n .apply(wrapWithEnvironment(environment))\n : undefined,\n\n logging: args.logging,\n triggers: args.triggers ? output(args.triggers).apply(flat) : undefined,\n stdin: args.stdin,\n\n addPreviousOutputInEnv: false,\n\n // TODO: does not work if server do not define AcceptEnv\n // environment,\n },\n { ...opts, parent: this },\n )\n\n this.stdout = command.stdout\n this.stderr = command.stderr\n\n this.registerOutputs({\n stdout: this.stdout,\n stderr: this.stderr,\n })\n }\n\n /**\n * Waits for the command to complete and returns its output.\n * The standard output will be returned.\n */\n async wait(): Promise<string> {\n return await toPromise(this.stdout)\n }\n\n /**\n * Creates a command that writes the given content to a file on the host.\n * The file will be created if it does not exist, and overwritten if it does.\n *\n * Use for small text files like configuration files.\n */\n static createTextFile(\n name: string,\n options: TextFileArgs,\n opts?: ComponentResourceOptions,\n ): Command {\n return new Command(\n name,\n {\n host: options.host,\n create: interpolate`mkdir -p $(dirname \"${options.path}\") && cat > ${options.path}`,\n delete: interpolate`rm -rf ${options.path}`,\n stdin: options.content,\n },\n opts,\n )\n }\n\n /**\n * Creates a command that waits for a file to be created and then reads its content.\n * This is useful for waiting for a file to be generated by another process.\n *\n * Use for small text files like configuration files.\n */\n static receiveTextFile(\n name: string,\n options: Omit<TextFileArgs, \"content\">,\n opts?: ComponentResourceOptions,\n ): Command {\n return new Command(\n name,\n {\n host: options.host,\n create: interpolate`while ! test -f \"${options.path}\"; do sleep 1; done; cat \"${options.path}\"`,\n logging: \"stderr\",\n },\n opts,\n )\n }\n\n /**\n * Creates a command that waits for a condition to be met.\n * The command will run until the condition is met or the timeout is reached.\n *\n * The condition is considered met if the command returns a zero exit code.\n *\n * @param name The name of the command resource.\n * @param args The arguments for the command, including the condition to check.\n * @param opts Optional resource options.\n */\n static waitFor(name: string, args: WaitForArgs, opts?: ComponentResourceOptions): Command {\n return new Command(\n name,\n {\n ...args,\n create: output(args.create).apply(wrapWithWaitFor(args.timeout, args.interval)),\n update: args.update\n ? output(args.update).apply(wrapWithWaitFor(args.timeout, args.interval))\n : undefined,\n delete: args.delete\n ? output(args.delete).apply(wrapWithWaitFor(args.timeout, args.interval))\n : undefined,\n },\n opts,\n )\n }\n}\n","import type { z } from \"@highstate/contract\"\nimport type { ImplementationReference } from \"@highstate/library\"\nimport { type Input, type Output, output, toPromise, type Unwrap } from \"@highstate/pulumi\"\n\n/**\n * The ImplementationMediator is used as a contract between the calling code and the implementation.\n *\n * From the calling code perspective, it provides a way to define the input and output schemas for the implementation\n * and call the implementation with the provided input.\n *\n * From the implementation perspective, it provides a way to get zod function with automatic type inference and validation.\n */\nexport class ImplementationMediator<\n TInputSchema extends z.ZodType,\n TOutputSchema extends z.ZodType,\n> {\n constructor(\n readonly path: string,\n private readonly inputSchema: TInputSchema,\n private readonly outputSchema: TOutputSchema,\n ) {}\n\n implement<TDataSchema extends z.ZodType>(\n dataSchema: TDataSchema,\n func: (\n input: z.infer<TInputSchema>,\n data: z.infer<TDataSchema>,\n ) => z.infer<TOutputSchema> | Promise<z.infer<TOutputSchema>>,\n ) {\n return async (\n input: z.infer<TInputSchema>,\n data: z.infer<TDataSchema>,\n ): Promise<z.infer<TOutputSchema>> => {\n const parsedInput = this.inputSchema.safeParse(input)\n if (!parsedInput.success) {\n throw new Error(\n `Invalid input for implementation \"${this.path}\": ${parsedInput.error.message}`,\n )\n }\n\n const parsedData = dataSchema.safeParse(data)\n if (!parsedData.success) {\n throw new Error(\n `Invalid data for implementation \"${this.path}\": ${parsedData.error.message}`,\n )\n }\n\n const result = await func(parsedInput.data, parsedData.data)\n const parsedResult = this.outputSchema.safeParse(result)\n\n if (!parsedResult.success) {\n throw new Error(\n `Invalid output from implementation \"${this.path}\": ${parsedResult.error.message}`,\n )\n }\n\n return parsedResult.data\n }\n }\n\n async call(\n implRef: Input<ImplementationReference>,\n input: Input<z.infer<TInputSchema>>,\n ): Promise<z.infer<TOutputSchema>> {\n const resolvedImplRef = await toPromise(implRef)\n const resolvedInput = await toPromise(input)\n\n const importPath = `${resolvedImplRef.package}/impl/${this.path}`\n\n let impl: Record<string, unknown>\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n impl = await import(importPath)\n } catch (error) {\n throw new Error(`Failed to import module \"${importPath}\" required by implementation.`, {\n cause: error,\n })\n }\n\n const funcs = Object.entries(impl).filter(value => typeof value[1] === \"function\") as [\n string,\n (...args: unknown[]) => unknown,\n ][]\n\n if (funcs.length === 0) {\n throw new Error(`No implementation functions found in module \"${importPath}\".`)\n }\n\n if (funcs.length > 1) {\n throw new Error(\n `Multiple implementation functions found in module \"${importPath}\": ${funcs.map(func => func[0]).join(\", \")}. ` +\n \"Ensure only one function is exported.\",\n )\n }\n\n const [funcName, implFunc] = funcs[0]\n\n let result: unknown\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n result = await implFunc(resolvedInput, resolvedImplRef.data)\n } catch (error) {\n console.error(`Error in implementation function \"${funcName}\":`, error)\n throw new Error(`Implementation function \"${funcName}\" failed`)\n }\n\n const parsedResult = this.outputSchema.safeParse(result)\n if (!parsedResult.success) {\n throw new Error(\n `Implementation function \"${funcName}\" returned invalid result: ${parsedResult.error.message}`,\n )\n }\n\n return parsedResult.data\n }\n\n callOutput(\n implRef: Input<ImplementationReference>,\n input: Input<z.infer<TInputSchema>>,\n ): Output<Unwrap<z.infer<TOutputSchema>>> {\n return output(this.call(implRef, input))\n }\n}\n","import type { ArrayPatchMode, dns, network } from \"@highstate/library\"\nimport { getOrCreate, z } from \"@highstate/contract\"\nimport {\n ComponentResource,\n type Input,\n type InputArray,\n type InputOrArray,\n interpolate,\n normalizeInputsAndMap,\n type Output,\n output,\n type ResourceOptions,\n toPromise,\n type Unwrap,\n} from \"@highstate/pulumi\"\nimport { flat, groupBy, uniqueBy } from \"remeda\"\nimport { Command, type CommandHost } from \"./command\"\nimport { ImplementationMediator } from \"./impl-ref\"\nimport {\n filterEndpoints,\n type InputL3Endpoint,\n l3EndpointToString,\n l34EndpointToString,\n parseL3Endpoint,\n} from \"./network\"\n\nexport const dnsRecordMediator = new ImplementationMediator(\n \"dns-record\",\n z.object({ name: z.string(), args: z.custom<ResolvedDnsRecordArgs>() }),\n z.instanceof(ComponentResource),\n)\n\nexport type DnsRecordArgs = {\n /**\n * The DNS provider to use.\n */\n provider: Input<dns.Provider>\n\n /**\n * The name of the DNS record.\n * If not provided, the name of the resource will be used.\n */\n name?: Input<string>\n\n /**\n * The type of the DNS record.\n *\n * If not provided, will be automatically detected based on the value.\n */\n type?: Input<string>\n\n /**\n * The value of the DNS record.\n */\n value: Input<InputL3Endpoint>\n\n /**\n * Whether the DNS record is proxied (e.g. to provide DDoS protection).\n *\n * Available only for public IPs and some DNS providers like Cloudflare.\n * If not supported, the DNS provider will ignore this value.\n */\n proxied?: Input<boolean>\n\n /**\n * The TTL of the DNS record.\n *\n * If not provided, the DNS provider will use its default value.\n */\n ttl?: Input<number>\n\n /**\n * The priority of the DNS record.\n *\n * Only used for some DNS record types (e.g. MX).\n */\n priority?: Input<number>\n\n /**\n * Wait for the DNS record to be created/updated at the specified environment(s) before continuing.\n */\n waitAt?: InputOrArray<CommandHost>\n}\n\nexport type ResolvedDnsRecordArgs = Pick<DnsRecordArgs, \"name\" | \"priority\" | \"ttl\" | \"proxied\"> & {\n /**\n * The value of the DNS record.\n */\n value: Input<string>\n\n /**\n * The type of the DNS record.\n */\n type: Input<string>\n}\n\nexport type DnsRecordSetArgs = Omit<DnsRecordArgs, \"provider\" | \"value\"> & {\n /**\n * The DNS providers to use to create the DNS records.\n *\n * If multiple providers matched the specified domain, records will be created for each of them.\n */\n providers: Input<dns.Provider[]>\n\n /**\n * The value of the DNS record.\n */\n value?: Input<InputL3Endpoint>\n\n /**\n * The values of the DNS records.\n */\n values?: InputArray<InputL3Endpoint>\n}\n\nfunction getTypeByEndpoint(endpoint: network.L3Endpoint): string {\n switch (endpoint.type) {\n case \"ipv4\":\n return \"A\"\n case \"ipv6\":\n return \"AAAA\"\n case \"hostname\":\n return \"CNAME\"\n }\n}\n\n/**\n * Creates a DNS record for the specified value and waits for it to be resolved.\n *\n * Uses the specified DNS provider to create the record.\n */\nexport class DnsRecord extends ComponentResource {\n /**\n * The underlying dns record resource.\n */\n readonly dnsRecord: Output<ComponentResource>\n\n /**\n * The commands to be executed after the DNS record is created/updated.\n *\n * These commands will wait for the DNS record to be resolved to the specified value.\n */\n readonly waitCommands: Output<Command[]>\n\n constructor(name: string, args: DnsRecordArgs, opts?: ResourceOptions) {\n super(\"highstate:common:DnsRecord\", name, args, opts)\n\n const l3Endpoint = output(args.value).apply(value => parseL3Endpoint(value))\n const resolvedValue = l3Endpoint.apply(l3EndpointToString)\n const resolvedType = args.type ? output(args.type) : l3Endpoint.apply(getTypeByEndpoint)\n\n this.dnsRecord = output(args.provider).apply(provider => {\n return dnsRecordMediator.call(provider.implRef, {\n name,\n args: {\n name: args.name,\n priority: args.priority,\n ttl: args.ttl,\n value: resolvedValue,\n type: resolvedType,\n },\n })\n })\n\n this.waitCommands = output({\n waitAt: args.waitAt,\n resolvedType,\n proxied: args.proxied,\n }).apply(({ waitAt, resolvedType, proxied }) => {\n if (resolvedType === \"CNAME\") {\n // TODO: handle CNAME records\n return []\n }\n\n const resolvedHosts = waitAt ? [waitAt].flat() : []\n\n if (proxied) {\n // for proxied records do not verify the value since we do not know the actual IP addressa\n\n return (resolvedHosts as Unwrap<CommandHost>[]).map(host => {\n const hostname = host === \"local\" ? \"local\" : host.hostname\n\n return new Command(\n `${name}.wait-for-dns.${hostname}`,\n {\n host,\n create: [\n interpolate`while ! getent hosts \"${args.name}\";`,\n interpolate`do echo \"Waiting for DNS record \\\"${args.name}\\\" to be available...\";`,\n `sleep 5;`,\n `done`,\n ],\n },\n { parent: this },\n )\n })\n }\n\n return (resolvedHosts as Unwrap<CommandHost>[]).map(host => {\n const hostname = host === \"local\" ? \"local\" : host.hostname\n\n return new Command(\n `${name}.wait-for-dns.${hostname}`,\n {\n host,\n create: [\n interpolate`while ! getent hosts \"${args.name}\" | grep \"${resolvedValue}\";`,\n interpolate`do echo \"Waiting for DNS record \\\"${args.name}\" to resolve to \"${resolvedValue}\"...\";`,\n `sleep 5;`,\n `done`,\n ],\n },\n { parent: this },\n )\n })\n })\n }\n}\n\n/**\n * Creates a set of DNS records for the specified values and waits for them to be resolved.\n */\nexport class DnsRecordSet extends ComponentResource {\n /**\n * The underlying dns record resources.\n */\n readonly dnsRecords: Output<DnsRecord[]>\n\n /**\n * The flat list of all wait commands for the DNS records.\n */\n readonly waitCommands: Output<Command[]>\n\n constructor(name: string, args: DnsRecordSetArgs, opts?: ResourceOptions) {\n super(\"highstate:common:DnsRecordSet\", name, args, opts)\n\n const matchedProviders = output({\n providers: args.providers,\n name: args.name ?? name,\n }).apply(({ providers }) => {\n const matchedProviders = providers.filter(provider => name.endsWith(provider.domain))\n\n if (matchedProviders.length === 0) {\n throw new Error(`No DNS provider matched the domain \"${name}\"`)\n }\n\n return matchedProviders\n })\n\n this.dnsRecords = normalizeInputsAndMap(args.value, args.values, value => {\n return output({\n name: args.name ?? name,\n providers: matchedProviders,\n }).apply(({ name, providers }) => {\n return providers.flatMap(provider => {\n const l3Endpoint = parseL3Endpoint(value)\n\n return new DnsRecord(\n `${name}.${provider.id}.${l3EndpointToString(l3Endpoint)}`,\n {\n name,\n provider,\n value: l3Endpoint,\n type: args.type ?? getTypeByEndpoint(l3Endpoint),\n proxied: args.proxied,\n ttl: args.ttl,\n priority: args.priority,\n waitAt: args.waitAt,\n },\n { parent: this },\n )\n })\n })\n }).apply(flat)\n\n this.waitCommands = this.dnsRecords\n .apply(records => records.flatMap(record => record.waitCommands))\n .apply(flat)\n }\n\n private static readonly dnsRecordSetCache = new Map<string, DnsRecordSet>()\n\n /**\n * Creates a DNS record set for the specified endpoints and waits for it to be resolved.\n *\n * If a DNS record set with the same name already exists, it will be reused.\n *\n * @param name The name of the DNS record set.\n * @param args The arguments for the DNS record set.\n * @param opts The options for the resource.\n */\n static createOnce(name: string, args: DnsRecordSetArgs, opts?: ResourceOptions): DnsRecordSet {\n return getOrCreate(\n DnsRecordSet.dnsRecordSetCache,\n name,\n () => new DnsRecordSet(name, args, opts),\n )\n }\n}\n\n/**\n * Registers the DNS record set for the given endpoints and prepends the corresponding hostname endpoint to the list.\n *\n * Waits for the DNS record set to be created/updated before continuing.\n *\n * Ignores the \"hostname\" endpoints in the list.\n *\n * @param endpoints The list of endpoints to register. Will be modified in place.\n * @param fqdn The FQDN to register the DNS record set for. If not provided, no DNS record set will be created and array will not be modified.\n * @param fqdnEndpointFilter The filter to apply to the endpoints before passing them to the DNS record set. Does not apply to the resulted endpoint list.\n * @param dnsProviders The DNS providers to use to create the DNS records.\n */\nexport async function updateEndpointsWithFqdn<TEndpoint extends network.L34Endpoint>(\n endpoints: Input<TEndpoint[]>,\n fqdn: string | undefined,\n fqdnEndpointFilter: network.EndpointFilter,\n patchMode: ArrayPatchMode,\n dnsProviders: Input<dns.Provider[]>,\n): Promise<{ endpoints: TEndpoint[]; dnsRecordSet: DnsRecordSet | undefined }> {\n const resolvedEndpoints = await toPromise(endpoints)\n\n if (!fqdn) {\n return {\n endpoints: resolvedEndpoints as TEndpoint[],\n dnsRecordSet: undefined,\n }\n }\n\n const filteredEndpoints = filterEndpoints(resolvedEndpoints, fqdnEndpointFilter)\n\n const dnsRecordSet = new DnsRecordSet(fqdn, {\n providers: dnsProviders,\n values: filteredEndpoints,\n waitAt: \"local\",\n })\n\n const portProtocolGroups = groupBy(filteredEndpoints, endpoint =>\n endpoint.port ? `${endpoint.port}-${endpoint.protocol}` : \"\",\n )\n\n const newEndpoints: TEndpoint[] = []\n\n for (const group of Object.values(portProtocolGroups)) {\n newEndpoints.unshift({\n type: \"hostname\",\n hostname: fqdn,\n visibility: group[0].visibility,\n port: group[0].port,\n protocol: group[0].protocol,\n } as TEndpoint)\n }\n\n await toPromise(\n dnsRecordSet.waitCommands.apply(waitCommands => waitCommands.map(command => command.stdout)),\n )\n\n if (patchMode === \"prepend\") {\n return {\n endpoints: uniqueBy(\n //\n [...newEndpoints, ...(resolvedEndpoints as TEndpoint[])],\n endpoint => l34EndpointToString(endpoint),\n ),\n dnsRecordSet,\n }\n }\n\n return {\n endpoints: newEndpoints,\n dnsRecordSet,\n }\n}\n","import type { TlsCertificate } from \"./tls\"\nimport { z } from \"@highstate/contract\"\nimport { type common, network } from \"@highstate/library\"\nimport {\n ComponentResource,\n type ComponentResourceOptions,\n type Input,\n type Output,\n output,\n Resource,\n} from \"@highstate/pulumi\"\nimport { ImplementationMediator } from \"./impl-ref\"\n\nexport const gatewayRouteMediator = new ImplementationMediator(\n \"gateway-route\",\n z.object({\n name: z.string(),\n spec: z.custom<GatewayRouteSpec>(),\n opts: z.custom<ComponentResourceOptions>().optional(),\n }),\n z.object({\n resource: z.instanceof(Resource),\n endpoints: network.l3EndpointEntity.schema.array(),\n }),\n)\n\nexport type GatewayRouteSpec = {\n /**\n * The FQDN to expose the workload on.\n */\n fqdn?: Input<string>\n\n /**\n * The endpoints of the backend workload to route traffic to.\n */\n endpoints: Input<network.L4Endpoint[]>\n\n /**\n * The native data to pass to the implementation.\n *\n * This is used for data which implementation may natively understand,\n * such as Kubernetes `Service` resources.\n *\n * Implementations may use this data to create more efficient routes\n * using native resources.\n */\n nativeData?: Input<unknown>\n\n /**\n * The TLS certificate to use for the route.\n */\n tlsCertificate?: Input<TlsCertificate | undefined>\n} & (\n | {\n type: \"http\"\n\n /**\n * Whether to expose the workload over plain HTTP.\n *\n * By default, the workload will be exposed over HTTPS.\n */\n insecure?: Input<boolean>\n\n /**\n * The relative path to expose the workload on.\n *\n * By default, the workload will be exposed on the root path (`/`).\n */\n path?: Input<string>\n }\n | {\n type: \"l3\"\n\n /**\n * The ports to request for the workload.\n *\n * The order must match the order of the ports in the service.\n *\n * If not provided, random ports will be assigned.\n */\n ports?: number\n }\n)\n\nexport type GatewayRouteArgs = GatewayRouteSpec & {\n /**\n * The gateway to attach the route to.\n */\n gateway: Input<common.Gateway>\n}\n\nexport class GatewayRoute extends ComponentResource {\n /**\n * The underlying resource created by the implementation.\n */\n readonly resource: Output<Resource>\n\n /**\n * The endpoints of the gateway which serve this route.\n *\n * In most cases, this will be a single endpoint of the gateway shared for all routes.\n */\n readonly endpoints: Output<network.L3Endpoint[]>\n\n constructor(name: string, args: GatewayRouteArgs, opts?: ComponentResourceOptions) {\n super(\"highstate:common:GatewayRoute\", name, args, opts)\n\n const { resource, endpoints } = gatewayRouteMediator.callOutput(output(args.gateway).implRef, {\n name,\n spec: args,\n opts: { ...opts, parent: this },\n })\n\n this.resource = resource\n this.endpoints = endpoints\n }\n}\n","import type { common } from \"@highstate/library\"\nimport { getOrCreate, z } from \"@highstate/contract\"\nimport {\n ComponentResource,\n type ComponentResourceOptions,\n type Input,\n type InputArray,\n normalizeInputs,\n type Output,\n output,\n Resource,\n} from \"@highstate/pulumi\"\nimport { ImplementationMediator } from \"./impl-ref\"\n\nexport const tlsCertificateMediator = new ImplementationMediator(\n \"tls-certificate\",\n z.object({\n name: z.string(),\n spec: z.custom<TlsCertificateSpec>(),\n opts: z.custom<ComponentResourceOptions>().optional(),\n }),\n z.instanceof(Resource),\n)\n\nexport type TlsCertificateSpec = {\n /**\n * The common name for the certificate.\n */\n commonName?: Input<string>\n\n /**\n * The alternative DNS names for the certificate.\n */\n dnsNames?: InputArray<string>\n\n /**\n * The native data to pass to the implementation.\n *\n * This is used for data which implementation may natively understand\n * and may use this data to create certificates using native resources.\n */\n nativeData?: unknown\n}\n\nexport type TlsCertificateArgs = TlsCertificateSpec & {\n /**\n * The issuer to use for the certificate.\n */\n issuer?: Input<common.TlsIssuer>\n\n /**\n * The issuers to use for the certificate.\n *\n * If multiple issuers are provided, the certificate will be created using the first issuer that supports the requested common name.\n */\n issuers?: InputArray<common.TlsIssuer>\n}\n\nexport class TlsCertificate extends ComponentResource {\n /**\n * The underlying resource created by the implementation.\n */\n readonly resource: Output<Resource>\n\n constructor(name: string, args: TlsCertificateArgs, opts?: ComponentResourceOptions) {\n super(\"highstate:common:TlsCertificate\", name, args, opts)\n\n const issuers = normalizeInputs(args.issuer, args.issuers)\n\n this.resource = output({\n issuers,\n commonName: args.commonName,\n dnsNames: args.dnsNames,\n }).apply(async ({ issuers, commonName, dnsNames }) => {\n // for now, we require single issuer to match all requested names\n const matchedIssuer = issuers.find(issuer => {\n if (commonName && !commonName.endsWith(issuer.domain)) {\n return false\n }\n\n if (dnsNames && !dnsNames.every(name => name.endsWith(issuer.domain))) {\n return false\n }\n\n return true\n })\n\n if (!matchedIssuer) {\n throw new Error(\n `No TLS issuer matched the common name \"${commonName}\" and DNS names \"${dnsNames?.join(\", \") ?? \"\"}\"`,\n )\n }\n\n return await tlsCertificateMediator.call(matchedIssuer.implRef, {\n name,\n spec: args,\n })\n })\n }\n\n private static readonly tlsCertificateCache = new Map<string, TlsCertificate>()\n\n /**\n * Creates a TLS certificate for the specified common name and DNS names.\n *\n * If a TLS certificate with the same name already exists, it will be reused.\n *\n * @param name The name of the TLS certificate.\n * @param args The arguments for the TLS certificate.\n * @param opts The options for the resource.\n */\n static createOnce(\n name: string,\n args: TlsCertificateArgs,\n opts?: ComponentResourceOptions,\n ): TlsCertificate {\n return getOrCreate(\n TlsCertificate.tlsCertificateCache,\n name,\n () => new TlsCertificate(name, args, opts),\n )\n }\n}\n","import type { common } from \"@highstate/library\"\nimport type { Except } from \"type-fest\"\nimport {\n ComponentResource,\n type ComponentResourceOptions,\n type Input,\n type Output,\n output,\n toPromise,\n} from \"@highstate/pulumi\"\nimport { DnsRecordSet } from \"./dns\"\nimport { GatewayRoute, type GatewayRouteSpec } from \"./gateway\"\nimport { TlsCertificate } from \"./tls\"\n\nexport type AccessPointRouteArgs = Except<GatewayRouteSpec, \"nativeData\"> & {\n /**\n * The access point to use to expose the route.\n */\n accessPoint: Input<common.AccessPoint>\n\n /**\n * The native data to pass to the gateway route implementation.\n */\n gatewayNativeData?: unknown\n\n /**\n * The native data to pass to the tls ceertificate implementation.\n */\n tlsCertificateNativeData?: unknown\n}\n\nexport class AccessPointRoute extends ComponentResource {\n /**\n * The created gateway route.\n */\n readonly route: GatewayRoute\n\n /**\n * The DNS record set created for the route.\n *\n * May be shared between multiple routes with the same FQDN.\n */\n readonly dnsRecordSet?: Output<DnsRecordSet | undefined>\n\n /**\n * The TLS certificate created for the route.\n *\n * May be shared between multiple routes with the same FQDN.\n */\n readonly tlsCertificate?: Output<TlsCertificate | undefined>\n\n constructor(name: string, args: AccessPointRouteArgs, opts?: ComponentResourceOptions) {\n super(\"highstate:common:AccessPointRoute\", name, args, opts)\n\n // 1. create TLS certificate if the route is HTTPS and the access point has TLS issuers\n if (args.fqdn && args.type === \"http\" && !args.insecure) {\n this.tlsCertificate = output(args.accessPoint).apply(accessPoint => {\n if (accessPoint.tlsIssuers.length === 0) {\n return undefined\n }\n\n return TlsCertificate.createOnce(\n name,\n {\n issuers: accessPoint.tlsIssuers,\n dnsNames: args.fqdn ? [args.fqdn] : [],\n nativeData: args.tlsCertificateNativeData,\n },\n { ...opts, parent: this },\n )\n })\n }\n\n // 2. create the route and resolve the gateway endpoints\n this.route = new GatewayRoute(\n name,\n {\n ...args,\n gateway: output(args.accessPoint).gateway,\n tlsCertificate: this.tlsCertificate,\n nativeData: args.gatewayNativeData,\n },\n { ...opts, parent: this },\n )\n\n // 3. register DNS records if FQDN is provided and the access point has DNS providers\n if (args.fqdn) {\n this.dnsRecordSet = output(args.accessPoint).apply(async accessPoint => {\n if (accessPoint.dnsProviders.length === 0) {\n return undefined\n }\n\n const fqdn = await toPromise(args.fqdn)\n if (!fqdn) {\n return undefined\n }\n\n return DnsRecordSet.createOnce(\n fqdn,\n {\n providers: output(args.accessPoint).dnsProviders,\n values: this.route.endpoints,\n waitAt: \"local\",\n proxied: accessPoint.proxied,\n },\n { ...opts, parent: this },\n )\n })\n }\n }\n}\n","import type { common, network } from \"@highstate/library\"\nimport { createHash } from \"node:crypto\"\nimport { createReadStream } from \"node:fs\"\nimport { cp, mkdir, mkdtemp, rename, rm, stat, writeFile } from \"node:fs/promises\"\nimport { tmpdir } from \"node:os\"\nimport { basename, dirname, extname, join } from \"node:path\"\nimport { Readable } from \"node:stream\"\nimport { pipeline } from \"node:stream/promises\"\nimport { type CommonObjectMeta, type File, HighstateSignature } from \"@highstate/contract\"\nimport { asset, toPromise } from \"@highstate/pulumi\"\nimport { minimatch } from \"minimatch\"\nimport * as tar from \"tar\"\nimport unzipper from \"unzipper\"\nimport { type InputL7Endpoint, l7EndpointToString, parseL7Endpoint } from \"./network\"\n\nexport type FolderPackOptions = {\n /**\n * The patterns to include in the packed archive.\n * If not provided, all files and folders will be included.\n */\n include?: string[]\n\n /**\n * The patterns to exclude from the packed archive.\n * Applied after include patterns.\n * If not provided, no files or folders will be excluded.\n */\n exclude?: string[]\n}\n\n/**\n * Creates Pulumi asset from Highstate file.\n *\n * @param file The file entity to create the asset from.\n * @returns The created asset.\n */\nexport function assetFromFile(file: common.File): asset.Asset {\n if (file.content.type === \"remote\") {\n return new asset.RemoteAsset(l7EndpointToString(file.content.endpoint))\n }\n\n if (file.content.type === \"local\") {\n return new asset.FileAsset(file.content.path)\n }\n\n if (file.content.type === \"artifact\") {\n throw new Error(\n \"Artifact-based files cannot be converted to Pulumi assets directly. Use MaterializedFile instead.\",\n )\n }\n\n if (file.content.isBinary) {\n throw new Error(\n \"Cannot create asset from inline binary file content. Please open an issue if you need this feature.\",\n )\n }\n\n return new asset.StringAsset(file.content.value)\n}\n\n/**\n * Creates Pulumi archive from Highstate folder.\n *\n * @param folder The folder entity to create the asset archive from.\n * @returns The created asset archive.\n */\nexport function archiveFromFolder(folder: common.Folder): asset.Archive {\n if (folder.content.type === \"remote\") {\n return new asset.RemoteArchive(l7EndpointToString(folder.content.endpoint))\n }\n\n if (folder.content.type === \"local\") {\n return new asset.FileArchive(folder.content.path)\n }\n\n if (folder.content.type === \"artifact\") {\n throw new Error(\n \"Artifact-based folders cannot be converted to Pulumi assets directly. Use MaterializedFolder instead.\",\n )\n }\n\n const files: Record<string, asset.Asset> = {}\n\n for (const file of folder.content.files) {\n files[file.meta.name] = assetFromFile(file)\n }\n\n for (const subfolder of folder.content.folders) {\n files[subfolder.meta.name] = archiveFromFolder(subfolder)\n }\n\n return new asset.AssetArchive(files)\n}\n\n/**\n * Extracts a tar or zip archive from a stream to a destination directory.\n *\n * @param stream The stream containing the archive data\n * @param destinationPath The path where to extract the archive\n * @param archiveType The type of archive ('tar' or 'zip')\n */\nasync function unarchiveFromStream(\n stream: Readable,\n destinationPath: string,\n archiveType: \"tar\" | \"zip\",\n): Promise<void> {\n await mkdir(destinationPath, { recursive: true })\n\n switch (archiveType) {\n case \"tar\": {\n const extractStream = tar.extract({\n cwd: destinationPath,\n strict: true,\n })\n\n await pipeline(stream, extractStream)\n return\n }\n case \"zip\": {\n // Extract directly from stream using unzipper\n await pipeline(stream, unzipper.Extract({ path: destinationPath }))\n return\n }\n }\n}\n\n/**\n * Determines the archive type based on file extension or content type.\n *\n * @param fileName The name of the file\n * @param contentType Optional content type from HTTP headers\n * @returns The detected archive type or null if not an archive\n */\nfunction detectArchiveType(fileName: string, contentType?: string): \"tar\" | \"zip\" | null {\n const ext = extname(fileName).toLowerCase()\n\n if (ext === \".tar\" || ext === \".tgz\" || ext === \".tar.gz\") {\n return \"tar\"\n }\n\n if (ext === \".zip\") {\n return \"zip\"\n }\n\n // Fallback to content type\n if (contentType) {\n if (contentType.includes(\"tar\") || contentType.includes(\"gzip\")) {\n return \"tar\"\n }\n if (contentType.includes(\"zip\")) {\n return \"zip\"\n }\n }\n\n return null\n}\n\n/**\n * The `MaterializedFile` class represents a file entity that has been materialized\n * to a local filesystem path.\n *\n * It handles creating a temporary directory, writing the file content to that directory,\n * and cleaning up the temporary files when disposed.\n *\n * For improved cleanup reliability, the class will use HIGHSTATE_TEMP_PATH as the base\n * directory for temporary files if available, allowing for centralized cleanup by the runner.\n */\nexport class MaterializedFile implements AsyncDisposable {\n private _tmpPath?: string\n private _path!: string\n private _disposed = false\n\n readonly artifactMeta: CommonObjectMeta\n\n constructor(\n readonly entity: common.File,\n readonly parent?: MaterializedFolder,\n ) {\n this.artifactMeta = {\n title: `Materialized file \"${entity.meta.name}\"`,\n }\n }\n\n get path(): string {\n return this._path\n }\n\n private async _open(): Promise<void> {\n if (this.parent) {\n // if the parent folder is provided, the file path is relative to the parent folder\n this._path = join(this.parent.path, this.entity.meta.name)\n } else {\n // otherwise, the file path is in a temporary directory\n // use HIGHSTATE_TEMP_PATH as base if available for better cleanup reliability\n const tempBase = process.env.HIGHSTATE_TEMP_PATH || tmpdir()\n this._tmpPath = await mkdtemp(join(tempBase, \"highstate-file-\"))\n this._path = join(this._tmpPath, this.entity.meta.name)\n }\n\n switch (this.entity.content.type) {\n case \"embedded\": {\n const content = this.entity.content.isBinary\n ? Buffer.from(this.entity.content.value, \"base64\")\n : this.entity.content.value\n\n await writeFile(this._path, content, { mode: this.entity.meta.mode })\n break\n }\n case \"local\": {\n await cp(this.entity.content.path, this._path, { mode: this.entity.meta.mode })\n break\n }\n case \"remote\": {\n const response = await fetch(l7EndpointToString(this.entity.content.endpoint))\n if (!response.ok) throw new Error(`Failed to fetch: ${response.statusText}`)\n\n const arrayBuffer = await response.arrayBuffer()\n await writeFile(this._path, Buffer.from(arrayBuffer), { mode: this.entity.meta.mode })\n\n break\n }\n case \"artifact\": {\n const artifactPath = process.env.HIGHSTATE_ARTIFACT_READ_PATH\n if (!artifactPath) {\n throw new Error(\n \"HIGHSTATE_ARTIFACT_READ_PATH environment variable is not set but required for artifact content\",\n )\n }\n\n const tgzPath = join(artifactPath, `${this.entity.content.hash}.tgz`)\n\n // extract the tgz file directly to the target path\n const readStream = createReadStream(tgzPath)\n await unarchiveFromStream(readStream, dirname(this._path), \"tar\")\n break\n }\n }\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n if (this._disposed) return\n this._disposed = true\n\n try {\n if (this._tmpPath) {\n // clear the whole temporary directory if it was created\n await rm(this._tmpPath, { recursive: true, force: true })\n } else {\n // otherwise, just remove the file\n await rm(this._path, { force: true })\n }\n } catch (error) {\n // ignore errors during cleanup, as the file might have been already removed\n // or the temporary directory might not exist\n // TODO: centralized logging for unit code\n console.warn(\"failed to clean up materialized file:\", error)\n }\n }\n\n /**\n * Packs the materialized file into an artifact and returns the file entity with artifact content.\n *\n * Creates a tgz archive of the file and stores it in HIGHSTATE_ARTIFACT_WRITE_PATH where it will be collected by Highstate.\n */\n async pack(): Promise<File> {\n const writeDir = process.env.HIGHSTATE_ARTIFACT_WRITE_PATH\n if (!writeDir) {\n throw new Error(\"HIGHSTATE_ARTIFACT_WRITE_PATH environment variable is not set\")\n }\n\n // read actual file stats from filesystem\n const fileStats = await stat(this._path)\n\n // create tgz archive of the file\n const tempBase = process.env.HIGHSTATE_TEMP_PATH || tmpdir()\n const tempArchivePath = join(tempBase, `highstate-pack-${Date.now()}.tgz`)\n\n try {\n await tar.create(\n {\n gzip: true,\n file: tempArchivePath,\n cwd: dirname(this._path),\n noMtime: true, // to reproduce the same archive every time\n },\n [basename(this._path)],\n )\n\n // calculate hash of the archive\n const fileContent = createReadStream(tempArchivePath)\n const hash = createHash(\"sha256\")\n\n for await (const chunk of fileContent) {\n hash.update(chunk as Buffer)\n }\n\n const hashValue = hash.digest(\"hex\")\n\n // move archive to write directory with hash name\n const finalArchivePath = join(writeDir, `${hashValue}.tgz`)\n await rename(tempArchivePath, finalArchivePath)\n\n const newMeta = {\n name: this.entity.meta.name,\n mode: fileStats.mode & 0o777, // extract only permission bits\n size: fileStats.size,\n }\n\n // return file entity with artifact content using actual filesystem stats\n return {\n meta: newMeta,\n content: {\n type: \"artifact\",\n [HighstateSignature.Artifact]: true,\n hash: hashValue,\n meta: await toPromise(this.artifactMeta),\n },\n }\n } finally {\n // clean up temporary archive\n try {\n await rm(tempArchivePath, { force: true })\n } catch {\n // ignore cleanup errors\n }\n }\n }\n\n /**\n * Creates an empty materialized file with the given name.\n *\n * @param name The name of the file to create\n * @param content Optional initial content of the file (default is empty string)\n * @param mode Optional file mode (permissions)\n * @returns A new MaterializedFile instance representing an empty file\n */\n static async create(name: string, content = \"\", mode?: number): Promise<MaterializedFile> {\n const entity: common.File = {\n meta: {\n name,\n mode,\n size: 0,\n },\n content: {\n type: \"embedded\",\n value: content,\n },\n }\n\n const materializedFile = new MaterializedFile(entity)\n\n try {\n await materializedFile._open()\n } catch (error) {\n await materializedFile[Symbol.asyncDispose]()\n throw error\n }\n\n return materializedFile\n }\n\n static async open(file: common.File, parent?: MaterializedFolder): Promise<MaterializedFile> {\n const materializedFile = new MaterializedFile(file, parent)\n\n try {\n await materializedFile._open()\n } catch (error) {\n await materializedFile[Symbol.asyncDispose]()\n throw error\n }\n\n return materializedFile\n }\n}\n\n/**\n * The `MaterializedFolder` class represents a folder entity that has been materialized\n * to a local filesystem path.\n *\n * It handles creating a temporary directory, copying the folder content to that directory,\n * and cleaning up the temporary files when disposed.\n *\n * For improved cleanup reliability, the class will use HIGHSTATE_TEMP_PATH as the base\n * directory for temporary files if available, allowing for centralized cleanup by the runner.\n */\nexport class MaterializedFolder implements AsyncDisposable {\n private _tmpPath?: string\n private _path!: string\n private _disposed = false\n\n private readonly _disposables: AsyncDisposable[] = []\n\n readonly artifactMeta: CommonObjectMeta\n\n constructor(\n readonly entity: common.Folder,\n readonly parent?: MaterializedFolder,\n ) {\n this.artifactMeta = {\n title: `Materialized folder \"${entity.meta.name}\"`,\n }\n }\n\n get path(): string {\n return this._path\n }\n\n private async _open(): Promise<void> {\n if (this.parent) {\n // if the parent folder is provided, the folder path is relative to the parent folder\n this._path = join(this.parent.path, this.entity.meta.name)\n } else {\n // otherwise, the folder path is in a temporary directory\n // use HIGHSTATE_TEMP_PATH as base if available for better cleanup reliability\n const tempBase = process.env.HIGHSTATE_TEMP_PATH || tmpdir()\n this._tmpPath = await mkdtemp(join(tempBase, \"highstate-folder-\"))\n this._path = join(this._tmpPath, this.entity.meta.name)\n }\n\n switch (this.entity.content.type) {\n case \"embedded\": {\n // create the folder itself\n await mkdir(this._path, { mode: this.entity.meta.mode })\n\n for (const file of this.entity.content.files) {\n const materializedFile = await MaterializedFile.open(file, this)\n this._disposables.push(materializedFile)\n }\n\n for (const subfolder of this.entity.content.folders) {\n const materializedFolder = await MaterializedFolder.open(subfolder, this)\n this._disposables.push(materializedFolder)\n }\n\n break\n }\n case \"local\": {\n // Check if the local path is an archive file that needs extraction\n const archiveType = detectArchiveType(this.entity.content.path)\n\n if (archiveType) {\n // Extract archive to the destination path\n const readStream = createReadStream(this.entity.content.path)\n await unarchiveFromStream(readStream, this._path, archiveType)\n } else {\n // Regular directory copy\n await cp(this.entity.content.path, this._path, {\n recursive: true,\n mode: this.entity.meta.mode,\n })\n }\n\n break\n }\n case \"remote\": {\n const response = await fetch(l7EndpointToString(this.entity.content.endpoint))\n if (!response.ok) throw new Error(`Failed to fetch: ${response.statusText}`)\n if (!response.body) throw new Error(\"Response body is empty\")\n\n // Try to detect archive type from URL or content type\n const url = new URL(l7EndpointToString(this.entity.content.endpoint))\n const archiveType = detectArchiveType(\n url.pathname,\n response.headers.get(\"content-type\") || undefined,\n )\n\n if (!archiveType) {\n throw new Error(\"Remote folder content must be an archive (tar, tar.gz, tgz, or zip)\")\n }\n\n if (!response.body) {\n throw new Error(\"Response body is empty\")\n }\n\n const reader = response.body.getReader()\n const stream = new Readable({\n async read() {\n try {\n const { done, value } = await reader.read()\n if (done) {\n this.push(null)\n } else {\n this.push(Buffer.from(value))\n }\n } catch (error) {\n this.destroy(error instanceof Error ? error : new Error(String(error)))\n }\n },\n })\n\n await unarchiveFromStream(stream, this._path, archiveType)\n\n break\n }\n case \"artifact\": {\n const artifactPath = process.env.HIGHSTATE_ARTIFACT_READ_PATH\n\n if (!artifactPath) {\n throw new Error(\n \"HIGHSTATE_ARTIFACT_READ_PATH environment variable is not set but required for artifact content\",\n )\n }\n\n const tgzPath = join(artifactPath, `${this.entity.content.hash}.tgz`)\n\n // extract the tgz file directly to the target path\n const readStream = createReadStream(tgzPath)\n await unarchiveFromStream(readStream, dirname(this._path), \"tar\")\n\n break\n }\n }\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n if (this._disposed) return\n this._disposed = true\n\n try {\n if (this._tmpPath) {\n // clear the whole temporary directory if it was created\n await rm(this._tmpPath, { recursive: true, force: true })\n } else {\n // otherwise, just remove the folder\n await rm(this._path, { recursive: true, force: true })\n }\n } catch (error) {\n // ignore errors during cleanup, as the folder might have been already removed\n // or the temporary directory might not exist\n // TODO: centralized logging for unit code\n console.warn(\"failed to clean up materialized folder:\", error)\n }\n\n // dispose all materialized children\n for (const disposable of this._disposables) {\n await disposable[Symbol.asyncDispose]()\n }\n }\n\n /**\n * Packs the materialized folder into an artifact and returns the folder entity with artifact content.\n *\n * Creates a tgz archive of the entire folder and stores it in HIGHSTATE_ARTIFACT_WRITE_PATH where it will be collected by Highstate.\n */\n async pack({ include, exclude }: FolderPackOptions = {}): Promise<common.Folder> {\n const writeDir = process.env.HIGHSTATE_ARTIFACT_WRITE_PATH\n if (!writeDir) {\n throw new Error(\"HIGHSTATE_ARTIFACT_WRITE_PATH environment variable is not set\")\n }\n\n // read actual folder stats from filesystem\n const folderStats = await stat(this._path)\n\n // create tgz archive of the folder\n const tempBase = process.env.HIGHSTATE_TEMP_PATH || tmpdir()\n const tempArchivePath = join(tempBase, `highstate-pack-${Date.now()}.tgz`)\n\n const entity = this.entity\n\n try {\n await tar.create(\n {\n gzip: true,\n file: tempArchivePath,\n cwd: dirname(this._path),\n\n filter(path) {\n // match without the folder name prefix\n path = path.slice(entity.meta.name.length + 1)\n\n // handle explicit excludes\n for (const pattern of exclude ?? []) {\n if (minimatch(path, pattern)) {\n return false\n }\n }\n\n // try to match include patterns\n for (const pattern of include ?? []) {\n if (minimatch(path, pattern)) {\n return true\n }\n }\n\n // include all files if no include patterns are specified\n return !include || include.length === 0\n },\n\n // to reproduce the same archive every time\n portable: true,\n noMtime: true,\n },\n [basename(this._path)],\n )\n\n // calculate hash of the archive\n const fileContent = createReadStream(tempArchivePath)\n const hash = createHash(\"sha256\")\n\n for await (const chunk of fileContent) {\n hash.update(chunk as Buffer)\n }\n\n const hashValue = hash.digest(\"hex\")\n\n // move archive to write directory with hash name\n const finalArchivePath = join(writeDir, `${hashValue}.tgz`)\n await rename(tempArchivePath, finalArchivePath)\n\n const newMeta = {\n name: this.entity.meta.name,\n mode: folderStats.mode & 0o777, // extract only permission bits\n }\n\n // return folder entity with artifact content using actual filesystem stats\n return {\n meta: newMeta,\n content: {\n [HighstateSignature.Artifact]: true,\n type: \"artifact\",\n hash: hashValue,\n meta: await toPromise(this.artifactMeta),\n },\n }\n } finally {\n // clean up temporary archive\n try {\n await rm(tempArchivePath, { force: true })\n } catch {\n // ignore cleanup errors\n }\n }\n }\n\n /**\n * Creates an empty materialized folder with the given name.\n *\n * @param name The name of the folder to create\n * @param mode Optional folder mode (permissions)\n * @param parent Optional parent folder to create the folder in\n * @returns A new MaterializedFolder instance representing an empty folder\n */\n static async create(\n name: string,\n mode?: number,\n parent?: MaterializedFolder,\n ): Promise<MaterializedFolder> {\n const entity: common.Folder = {\n meta: {\n name,\n mode,\n },\n content: {\n type: \"embedded\",\n files: [],\n folders: [],\n },\n }\n\n const materializedFolder = new MaterializedFolder(entity, parent)\n\n try {\n await materializedFolder._open()\n } catch (error) {\n await materializedFolder[Symbol.asyncDispose]()\n throw error\n }\n\n return materializedFolder\n }\n\n static async open(\n folder: common.Folder,\n parent?: MaterializedFolder,\n ): Promise<MaterializedFolder> {\n const materializedFolder = new MaterializedFolder(folder, parent)\n\n try {\n await materializedFolder._open()\n } catch (error) {\n await materializedFolder[Symbol.asyncDispose]()\n throw error\n }\n\n return materializedFolder\n }\n}\n\n/**\n * Fetches the size of a file from a given L7 endpoint.\n *\n * @param endpoint The L7 endpoint to fetch the file size from.\n * @returns The size of the file in bytes.\n * @throws If the protocol is not HTTP/HTTPS or if the request fails.\n */\nexport async function fetchFileSize(endpoint: network.L7Endpoint): Promise<number> {\n if (endpoint.appProtocol !== \"http\" && endpoint.appProtocol !== \"https\") {\n throw new Error(\n `Unsupported protocol: ${endpoint.appProtocol}. Only HTTP and HTTPS are supported.`,\n )\n }\n\n const url = l7EndpointToString(endpoint)\n const response = await fetch(url, { method: \"HEAD\" })\n\n if (!response.ok) {\n throw new Error(`Failed to fetch file size: ${response.statusText}`)\n }\n\n const contentLength = response.headers.get(\"content-length\")\n if (!contentLength) {\n throw new Error(\"Content-Length header is missing in the response\")\n }\n\n const size = parseInt(contentLength, 10)\n if (Number.isNaN(size)) {\n throw new Error(`Invalid Content-Length value: ${contentLength}`)\n }\n\n return size\n}\n\n/**\n * Extracts the name from an L7 endpoint URL without its file extension.\n */\nexport function getNameByEndpoint(endpoint: InputL7Endpoint): string {\n const parsedEndpoint = parseL7Endpoint(endpoint)\n\n return parsedEndpoint.resource ? basename(parsedEndpoint.resource) : \"\"\n}\n","import { bytesToHex, randomBytes } from \"@noble/hashes/utils\"\nimport { secureMask } from \"micro-key-producer/password.js\"\n\n/**\n * Generates a secure random password strong enough for online use.\n *\n * It uses \"Safari Keychain Secure Password\" format.\n *\n * The approximate entropy is [71 bits](https://support.apple.com/guide/security/automatic-strong-passwords-secc84c811c4/web).\n */\nexport function generatePassword(): string {\n return secureMask.apply(randomBytes(32)).password\n}\n\ntype KeyFormatMap = {\n raw: Uint8Array\n hex: string\n base64: string\n}\n\n/**\n * Generates a secure random key strong enough for offline use such as encryption.\n *\n * The strong entropy is 256 bits.\n *\n * @param format The format of the generated key. By default, it is \"hex\".\n */\nexport function generateKey<TFormat extends keyof KeyFormatMap = \"hex\">(\n format: TFormat = \"hex\" as TFormat,\n): KeyFormatMap[TFormat] {\n const bytes = randomBytes(32)\n\n if (format === \"raw\") {\n return bytes as KeyFormatMap[TFormat]\n }\n\n if (format === \"base64\") {\n return Buffer.from(bytes).toString(\"base64\") as KeyFormatMap[TFormat]\n }\n\n return bytesToHex(bytes) as KeyFormatMap[TFormat]\n}\n","{\n \"terminal-ssh\": {\n \"name\": \"ghcr.io/exeteres/highstate/terminal-ssh\",\n \"tag\": \"latest\",\n \"image\": \"ghcr.io/exeteres/highstate/terminal-ssh:latest@sha256:99380e0405522afa0058eedce124c1970a87408663365b2dbce737801a7cd5d1\"\n }\n}\n","import type { common, network, ssh } from \"@highstate/library\"\nimport { stripNullish, type UnitTerminal } from \"@highstate/contract\"\nimport {\n fileFromString,\n type Input,\n type Output,\n output,\n secret,\n toPromise,\n} from \"@highstate/pulumi\"\nimport { remote } from \"@pulumi/command\"\nimport getKeys, { PrivateExport } from \"micro-key-producer/ssh.js\"\nimport { randomBytes } from \"micro-key-producer/utils.js\"\nimport * as images from \"../../assets/images.json\"\nimport { Command } from \"./command\"\nimport { l3EndpointToL4, l3EndpointToString } from \"./network\"\n\nexport async function createSshTerminal(\n credentials: Input<ssh.Connection>,\n): Promise<Output<UnitTerminal>> {\n const resolvedCredentials = await toPromise(credentials)\n\n const command = [\"ssh\", \"-tt\", \"-o\", \"UserKnownHostsFile=/known_hosts\"]\n\n // TODO: select best endpoint based on the environment\n const endpoint = resolvedCredentials.endpoints[0]\n\n command.push(\"-p\", endpoint.port.toString())\n\n if (resolvedCredentials.keyPair) {\n command.push(\"-i\", \"/private_key\")\n }\n\n command.push(`${resolvedCredentials.user}@${l3EndpointToString(endpoint)}`)\n\n if (resolvedCredentials.password) {\n command.unshift(\"sshpass\", \"-f\", \"/password\")\n }\n\n return output({\n name: \"ssh\",\n\n meta: {\n title: \"Shell\",\n description: \"Connect to the server via SSH.\",\n icon: \"gg:remote\",\n },\n\n spec: {\n image: images[\"terminal-ssh\"].image,\n command,\n\n files: stripNullish({\n \"/password\": resolvedCredentials.password\n ? fileFromString(\"password\", resolvedCredentials.password, { isSecret: true })\n : undefined,\n\n \"/private_key\": resolvedCredentials.keyPair?.privateKey\n ? fileFromString(\"private_key\", resolvedCredentials.keyPair.privateKey, {\n isSecret: true,\n mode: 0o600,\n })\n : undefined,\n\n \"/known_hosts\": fileFromString(\n \"known_hosts\",\n `${l3EndpointToString(endpoint)} ${resolvedCredentials.hostKey}`,\n { mode: 0o644 },\n ),\n }),\n },\n })\n}\n\n/**\n * Generates a secure random SSH private key.\n * The key is generated using the Ed25519 algorithm.\n *\n * @returns The generated SSH private key in PEM format.\n */\nexport function generateSshPrivateKey(): Output<string> {\n const seed = randomBytes(32)\n\n return secret(getKeys(seed).privateKey)\n}\n\n/**\n * Converts a private SSH key string to a KeyPair object.\n *\n * @param privateKeyString The private key string to convert.\n * @returns An Output of the KeyPair object.\n */\nexport function sshPrivateKeyToKeyPair(privateKeyString: Input<string>): Output<ssh.KeyPair> {\n return output(privateKeyString).apply(privateKeyString => {\n const privateKeyStruct = PrivateExport.decode(privateKeyString)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const privKey = privateKeyStruct.keys[0].privKey.privKey as Uint8Array\n\n const { fingerprint, publicKey } = getKeys(privKey.slice(0, 32))\n\n return output({\n type: \"ed25519\" as const,\n fingerprint,\n publicKey,\n privateKey: secret(privateKeyString),\n })\n })\n}\n\nexport type ServerOptions = {\n /**\n * The local name of the server to namespace resources.\n */\n name: string\n\n /**\n * The fallback hostname to use if the server cannot be determined.\n *\n * If not provided, the `name` will be used as the fallback hostname.\n */\n fallbackHostname?: string\n\n /**\n * The L3 endpoints of the server.\n */\n endpoints: network.L3Endpoint[]\n\n /**\n * The arguments for the SSH connection.\n */\n sshArgs?: Partial<ssh.Args>\n\n /**\n * The password for the SSH connection.\n */\n sshPassword?: Input<string>\n\n /**\n * The private key for the SSH connection.\n */\n sshPrivateKey?: Input<string>\n\n /**\n * The SSH key pair for the server.\n * If provided, it will take precedence over the `sshPrivateKey` argument.\n */\n sshKeyPair?: Input<ssh.KeyPair>\n\n /**\n * Whether to wait for the server to respond to a ping command before returning.\n *\n * If true, the command will wait for a successful ping response before proceeding.\n *\n * By default, this is equal to `!waitForSsh`, so when `waitForSsh` is true, no extra ping is performed.\n */\n waitForPing?: boolean\n\n /**\n * The interval in seconds to wait between ping attempts.\n *\n * Only used if `waitForPing` is true.\n * By default, it will wait 5 seconds between attempts.\n */\n pingInterval?: number\n\n /**\n * The timeout in seconds to wait for the server to respond to a ping command.\n *\n * Only used if `waitForPing` is true.\n * By default, it will wait 5 minutes (300 seconds) before timing out.\n */\n pingTimeout?: number\n\n /**\n * Whether to wait for the SSH service to be available before returning.\n *\n * If true, the command will wait for the SSH service to respond before proceeding.\n *\n * By default, this is true if `sshArgs.enabled` is true, otherwise false.\n */\n waitForSsh?: boolean\n\n /**\n * The interval in seconds to wait between SSH connection attempts.\n *\n * Only used if `waitForSsh` is true.\n * By default, it will wait 5 seconds between attempts.\n */\n sshCheckInterval?: number\n\n /**\n * The timeout in seconds to wait for the SSH service to respond.\n *\n * Only used if `waitForSsh` is true.\n * By default, it will wait 5 minutes (300 seconds) before timing out.\n */\n sshCheckTimeout?: number\n}\n\nexport type ServerBundle = {\n /**\n * The server entity created with the provided options.\n */\n server: Output<common.Server>\n\n /**\n * The SSH terminal created for the server.\n */\n terminal?: Output<UnitTerminal>\n}\n\n/**\n * Creates a server entity with the provided options and returns a bundle containing the server entity and terminal.\n *\n * Basically, it just a convenience function that calls `createServerEntity` and `createSshTerminal`.\n *\n * @param options The options for creating the server entity.\n * @returns A promise that resolves to a ServerBundle containing the server entity and terminal.\n */\nexport async function createServerBundle(options: ServerOptions): Promise<ServerBundle> {\n const server = await createServerEntity(options)\n const ssh = await toPromise(server.ssh)\n\n return {\n server,\n terminal: ssh ? await createSshTerminal(ssh) : undefined,\n }\n}\n\n/**\n * Creates a server entity with the provided options.\n * It will create a command to check the SSH service and return the server entity.\n *\n * @param options The options for creating the server entity.\n * @returns A promise that resolves to the created server entity.\n */\nexport async function createServerEntity({\n name,\n fallbackHostname,\n endpoints,\n sshArgs = { enabled: true, port: 22, user: \"root\" },\n sshPassword,\n sshPrivateKey,\n sshKeyPair,\n pingInterval,\n pingTimeout,\n waitForPing,\n waitForSsh,\n sshCheckInterval,\n sshCheckTimeout,\n}: ServerOptions): Promise<Output<common.Server>> {\n if (endpoints.length === 0) {\n throw new Error(\"At least one L3 endpoint is required to create a server entity\")\n }\n\n fallbackHostname ??= name\n waitForSsh ??= sshArgs.enabled\n waitForPing ??= !waitForSsh\n\n if (waitForPing) {\n await Command.waitFor(`${name}.ping`, {\n host: \"local\",\n create: `ping -c 1 ${l3EndpointToString(endpoints[0])}`,\n timeout: pingTimeout ?? 300,\n interval: pingInterval ?? 5,\n triggers: [Date.now()],\n }).wait()\n }\n\n if (!sshArgs.enabled) {\n return output({\n hostname: name,\n endpoints,\n })\n }\n\n const sshHost = sshArgs?.host ?? l3EndpointToString(endpoints[0])\n\n if (waitForSsh) {\n await Command.waitFor(`${name}.ssh`, {\n host: \"local\",\n create: `nc -zv ${sshHost} ${sshArgs.port}`,\n timeout: sshCheckTimeout ?? 300,\n interval: sshCheckInterval ?? 5,\n triggers: [Date.now()],\n }).wait()\n }\n\n const connection = output({\n host: sshHost,\n port: sshArgs.port,\n user: sshArgs.user,\n password: sshPassword,\n privateKey: sshKeyPair ? output(sshKeyPair).privateKey : sshPrivateKey,\n dialErrorLimit: 3,\n })\n\n const hostnameResult = new remote.Command(\"hostname\", {\n connection,\n create: \"hostname\",\n triggers: [Date.now()],\n })\n\n const hostKeyResult = new remote.Command(\"host-key\", {\n connection,\n create: \"cat /etc/ssh/ssh_host_ed25519_key.pub\",\n triggers: [Date.now()],\n })\n\n return output({\n endpoints,\n hostname: hostnameResult.stdout.apply(x => x.trim()),\n ssh: {\n endpoints: [l3EndpointToL4(sshHost, sshArgs.port ?? 22)],\n user: sshArgs.user ?? \"root\",\n hostKey: hostKeyResult.stdout.apply(x => x.trim()),\n password: connection.password,\n keyPair: sshKeyPair\n ? sshKeyPair\n : sshPrivateKey\n ? sshPrivateKeyToKeyPair(sshPrivateKey)\n : undefined,\n },\n })\n}\n"]}
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- export { AccessPointRoute, Command, DnsRecord, DnsRecordSet, GatewayRoute, ImplementationMediator, MaterializedFile, MaterializedFolder, TlsCertificate, archiveFromFolder, assetFromFile, createServerBundle, createServerEntity, createSshTerminal, dnsRecordMediator, fetchFileSize, filterEndpoints, gatewayRouteMediator, generateKey, generatePassword, generateSshPrivateKey, getNameByEndpoint, getServerConnection, l34EndpointToString, l3EndpointToCidr, l3EndpointToL4, l3EndpointToString, l4EndpointToString, l4EndpointWithProtocolToString, l7EndpointToString, parseEndpoints, parseL34Endpoint, parseL3Endpoint, parseL4Endpoint, parseL7Endpoint, requireInputL3Endpoint, requireInputL4Endpoint, sshPrivateKeyToKeyPair, tlsCertificateMediator, updateEndpoints, updateEndpointsWithFqdn } from './chunk-FHSPC2ZL.js';
1
+ export { AccessPointRoute, Command, DnsRecord, DnsRecordSet, GatewayRoute, ImplementationMediator, MaterializedFile, MaterializedFolder, TlsCertificate, archiveFromFolder, assetFromFile, createServerBundle, createServerEntity, createSshTerminal, dnsRecordMediator, fetchFileSize, filterEndpoints, gatewayRouteMediator, generateKey, generatePassword, generateSshPrivateKey, getNameByEndpoint, getServerConnection, l34EndpointToString, l3EndpointToCidr, l3EndpointToL4, l3EndpointToString, l4EndpointToString, l4EndpointWithProtocolToString, l7EndpointToString, parseEndpoints, parseL34Endpoint, parseL3Endpoint, parseL4Endpoint, parseL7Endpoint, requireInputL3Endpoint, requireInputL4Endpoint, sshPrivateKeyToKeyPair, tlsCertificateMediator, updateEndpoints, updateEndpointsWithFqdn } from './chunk-RKTGGVPZ.js';
2
2
  //# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { parseEndpoints } from '../../../chunk-FHSPC2ZL.js';
1
+ import { parseEndpoints } from '../../../chunk-RKTGGVPZ.js';
2
2
  import { databases } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
 
@@ -1,4 +1,4 @@
1
- import { parseEndpoints } from '../../../chunk-FHSPC2ZL.js';
1
+ import { parseEndpoints } from '../../../chunk-RKTGGVPZ.js';
2
2
  import { databases } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
 
@@ -1,4 +1,4 @@
1
- import { parseEndpoints } from '../../../chunk-FHSPC2ZL.js';
1
+ import { parseEndpoints } from '../../../chunk-RKTGGVPZ.js';
2
2
  import { databases } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
 
@@ -1,4 +1,4 @@
1
- import { updateEndpointsWithFqdn } from '../../../chunk-FHSPC2ZL.js';
1
+ import { updateEndpointsWithFqdn } from '../../../chunk-RKTGGVPZ.js';
2
2
  import { dns } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
 
@@ -1,4 +1,4 @@
1
- import { requireInputL3Endpoint, createServerBundle, l3EndpointToString } from '../../chunk-FHSPC2ZL.js';
1
+ import { requireInputL3Endpoint, createServerBundle, l3EndpointToString } from '../../chunk-RKTGGVPZ.js';
2
2
  import { common } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
  import { map } from 'remeda';
@@ -1,4 +1,4 @@
1
- import { parseL3Endpoint } from '../../../chunk-FHSPC2ZL.js';
1
+ import { parseL3Endpoint } from '../../../chunk-RKTGGVPZ.js';
2
2
  import { network } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
 
@@ -1,4 +1,4 @@
1
- import { parseL4Endpoint } from '../../../chunk-FHSPC2ZL.js';
1
+ import { parseL4Endpoint } from '../../../chunk-RKTGGVPZ.js';
2
2
  import { network } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
 
@@ -1,4 +1,4 @@
1
- import { Command } from '../../chunk-FHSPC2ZL.js';
1
+ import { Command } from '../../chunk-RKTGGVPZ.js';
2
2
  import { common } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
 
@@ -1,4 +1,4 @@
1
- import { updateEndpointsWithFqdn, l3EndpointToString } from '../../chunk-FHSPC2ZL.js';
1
+ import { updateEndpointsWithFqdn, l3EndpointToString } from '../../chunk-RKTGGVPZ.js';
2
2
  import { common } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
 
@@ -1,4 +1,4 @@
1
- import { updateEndpoints, l3EndpointToString } from '../../chunk-FHSPC2ZL.js';
1
+ import { updateEndpoints, l3EndpointToString } from '../../chunk-RKTGGVPZ.js';
2
2
  import { common } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
 
@@ -1,4 +1,4 @@
1
- import { generateSshPrivateKey, sshPrivateKeyToKeyPair } from '../../../chunk-FHSPC2ZL.js';
1
+ import { generateSshPrivateKey, sshPrivateKeyToKeyPair } from '../../../chunk-RKTGGVPZ.js';
2
2
  import { ssh } from '@highstate/library';
3
3
  import { forUnit } from '@highstate/pulumi';
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@highstate/common",
3
- "version": "0.9.27",
3
+ "version": "0.9.28",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist",
@@ -91,9 +91,9 @@
91
91
  "biome:check": "biome check --error-on-warnings"
92
92
  },
93
93
  "dependencies": {
94
- "@highstate/contract": "^0.9.27",
95
- "@highstate/library": "^0.9.27",
96
- "@highstate/pulumi": "^0.9.27",
94
+ "@highstate/contract": "^0.9.28",
95
+ "@highstate/library": "^0.9.28",
96
+ "@highstate/pulumi": "^0.9.28",
97
97
  "@noble/hashes": "^1.7.1",
98
98
  "@pulumi/command": "^1.0.2",
99
99
  "micro-key-producer": "^0.7.3",
@@ -104,11 +104,11 @@
104
104
  },
105
105
  "devDependencies": {
106
106
  "@biomejs/biome": "2.2.0",
107
- "@highstate/cli": "^0.9.27",
107
+ "@highstate/cli": "^0.9.28",
108
108
  "@types/tar": "^6.1.13",
109
109
  "@types/unzipper": "^0.10.11",
110
110
  "@typescript/native-preview": "^7.0.0-dev.20250920.1",
111
111
  "type-fest": "^4.41.0"
112
112
  },
113
- "gitHead": "e4dfdb6c1394a6739591f9881c4f5f11d9daa0ba"
113
+ "gitHead": "6de09d98fa66e808c42aba7fe65e6e0762945b9b"
114
114
  }
@@ -101,6 +101,7 @@ export class AccessPointRoute extends ComponentResource {
101
101
  providers: output(args.accessPoint).dnsProviders,
102
102
  values: this.route.endpoints,
103
103
  waitAt: "local",
104
+ proxied: accessPoint.proxied,
104
105
  },
105
106
  { ...opts, parent: this },
106
107
  )
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/shared/network.ts","../src/shared/command.ts","../src/shared/impl-ref.ts","../src/shared/dns.ts","../src/shared/gateway.ts","../src/shared/tls.ts","../src/shared/access-point.ts","../src/shared/files.ts","../src/shared/passwords.ts","../assets/images.json","../src/shared/ssh.ts"],"names":["ssh","command","environment","env","triggers","toPromise","output","ComponentResource","resolvedType","interpolate","matchedProviders","name","flat","uniqueBy","z","Resource","issuers","getOrCreate","terminal-ssh","randomBytes","privateKeyString","remote"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkCO,SAAS,mBAAmB,UAAA,EAAwC;AACzE,EAAA,QAAQ,WAAW,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AACR,GACD,CAAA;AACH","file":"chunk-FHSPC2ZL.js","sourcesContent":["import type { ArrayPatchMode, network } from \"@highstate/library\"\nimport { type Input, toPromise } from \"@highstate/pulumi\"\nimport { uniqueBy } from \"remeda\"\n\n/**\n * The L3 or L4 endpoint for some service.\n *\n * The format is: `[protocol://]endpoint[:port]`\n */\nexport type InputL34Endpoint = network.L34Endpoint | string\n\n/**\n * The L3 endpoint for some service.\n */\nexport type InputL3Endpoint = network.L3Endpoint | string\n\n/**\n * The L4 endpoint for some service.\n */\nexport type InputL4Endpoint = network.L4Endpoint | string\n\n/**\n * The L7 endpoint for some service.\n *\n * The format is: `appProtocol://endpoint[:port][/resource]`\n */\nexport type InputL7Endpoint = network.L7Endpoint | string\n\n/**\n * Stringifies a L3 endpoint object into a string.\n *\n * @param l3Endpoint The L3 endpoint object to stringify.\n * @returns The string representation of the L3 endpoint.\n */\nexport function l3EndpointToString(l3Endpoint: network.L3Endpoint): string {\n switch (l3Endpoint.type) {\n case \"ipv4\":\n return l3Endpoint.address\n case \"ipv6\":\n return l3Endpoint.address\n case \"hostname\":\n return l3Endpoint.hostname\n }\n}\n\n/**\n * Stringifies a L4 endpoint object into a string.\n *\n * @param l4Endpoint The L4 endpoint object to stringify.\n * @returns The string representation of the L4 endpoint.\n */\nexport function l4EndpointToString(l4Endpoint: network.L4Endpoint): string {\n if (l4Endpoint.type === \"ipv6\") {\n return `[${l4Endpoint.address}]:${l4Endpoint.port}`\n }\n\n return `${l3EndpointToString(l4Endpoint)}:${l4Endpoint.port}`\n}\n\n/**\n * Stringifies a L4 endpoint object into a string with protocol.\n *\n * @param l4Endpoint The L4 endpoint object to stringify.\n * @returns The string representation of the L4 endpoint with protocol.\n */\nexport function l4EndpointWithProtocolToString(l4Endpoint: network.L4Endpoint): string {\n const protocol = `${l4Endpoint.protocol}://`\n\n return `${protocol}${l4EndpointToString(l4Endpoint)}`\n}\n\n/**\n * Stringifies a L7 endpoint object into a string.\n *\n * The format is: `appProtocol://endpoint[:port][/resource]`\n * @param l7Endpoint The L7 endpoint object to stringify.\n * @returns The string representation of the L7 endpoint.\n */\nexport function l7EndpointToString(l7Endpoint: network.L7Endpoint): string {\n const protocol = `${l7Endpoint.appProtocol}://`\n\n let endpoint = l4EndpointToString(l7Endpoint)\n\n if (l7Endpoint.resource) {\n endpoint += `/${l7Endpoint.resource}`\n }\n\n return `${protocol}${endpoint}`\n}\n\n/**\n * Stringifies a L3 or L4 endpoint object into a string.\n *\n * @param l34Endpoint The L3 or L4 endpoint object to stringify.\n * @returns The string representation of the L3 or L4 endpoint.\n */\nexport function l34EndpointToString(l34Endpoint: network.L34Endpoint): string {\n if (l34Endpoint.port) {\n return l4EndpointToString(l34Endpoint)\n }\n\n return l3EndpointToString(l34Endpoint)\n}\n\nconst L34_ENDPOINT_RE =\n /^(?:(?<protocol>[a-z]+):\\/\\/)?(?:(?:\\[?(?<ipv6>[0-9A-Fa-f:]+)\\]?)|(?<ipv4>(?:\\d{1,3}\\.){3}\\d{1,3})|(?<hostname>[a-zA-Z0-9-*]+(?:\\.[a-zA-Z0-9-*]+)*))(?::(?<port>\\d{1,5}))?$/\n\nconst L7_ENDPOINT_RE =\n /^(?<appProtocol>[a-z]+):\\/\\/(?:(?:\\[?(?<ipv6>[0-9A-Fa-f:]+)\\]?)|(?<ipv4>(?:\\d{1,3}\\.){3}\\d{1,3})|(?<hostname>[a-zA-Z0-9-*]+(?:\\.[a-zA-Z0-9-*]+)*))(?::(?<port>\\d{1,5}))?(?:\\/(?<resource>.*))?$/\n\n/**\n * Parses a L3 or L4 endpoint from a string.\n *\n * The format is `[protocol://]endpoint[:port]`.\n *\n * @param l34Endpoint The L3 or L4 endpoint string to parse.\n * @returns The parsed L3 or L4 endpoint object.\n */\nexport function parseL34Endpoint(l34Endpoint: InputL34Endpoint): network.L34Endpoint {\n if (typeof l34Endpoint === \"object\") {\n return l34Endpoint\n }\n\n const match = l34Endpoint.match(L34_ENDPOINT_RE)\n if (!match) {\n throw new Error(`Invalid L3/L4 endpoint: \"${l34Endpoint}\"`)\n }\n\n const { protocol, ipv6, ipv4, hostname, port } = match.groups!\n\n if (protocol && protocol !== \"tcp\" && protocol !== \"udp\") {\n throw new Error(`Invalid L4 endpoint protocol: \"${protocol}\"`)\n }\n\n let visibility: network.EndpointVisibility = \"public\"\n\n if (ipv4 && IPV4_PRIVATE_REGEX.test(ipv4)) {\n visibility = \"external\"\n } else if (ipv6 && IPV6_PRIVATE_REGEX.test(ipv6)) {\n visibility = \"external\"\n }\n\n const fallbackProtocol = port ? \"tcp\" : undefined\n\n return {\n type: ipv6 ? \"ipv6\" : ipv4 ? \"ipv4\" : \"hostname\",\n visibility,\n address: ipv6 || ipv4,\n hostname: hostname,\n port: port ? parseInt(port, 10) : undefined,\n protocol: protocol ? (protocol as network.L4Protocol) : fallbackProtocol,\n } as network.L34Endpoint\n}\n\n/**\n * Parses a L3 endpoint from a string.\n *\n * The same as `parseL34Endpoint`, but only for L3 endpoints and will throw an error if the endpoint contains a port.\n *\n * @param l3Endpoint The L3 endpoint string to parse.\n * @returns The parsed L3 endpoint object.\n */\nexport function parseL3Endpoint(l3Endpoint: InputL3Endpoint): network.L3Endpoint {\n if (typeof l3Endpoint === \"object\") {\n return l3Endpoint\n }\n\n const parsed = parseL34Endpoint(l3Endpoint)\n\n if (parsed.port) {\n throw new Error(`Port cannot be specified in L3 endpoint: \"${l3Endpoint}\"`)\n }\n\n return parsed\n}\n\n/**\n * Parses a L4 endpoint from a string.\n *\n * The same as `parseL34Endpoint`, but only for L4 endpoints and will throw an error if the endpoint does not contain a port.\n */\nexport function parseL4Endpoint(l4Endpoint: InputL4Endpoint): network.L4Endpoint {\n if (typeof l4Endpoint === \"object\") {\n return l4Endpoint\n }\n\n const parsed = parseL34Endpoint(l4Endpoint)\n\n if (!parsed.port) {\n throw new Error(`No port found in L4 endpoint: \"${l4Endpoint}\"`)\n }\n\n return parsed\n}\n\nconst IPV4_PRIVATE_REGEX =\n /^(?:10|127)(?:\\.\\d{1,3}){3}$|^(?:172\\.1[6-9]|172\\.2[0-9]|172\\.3[0-1])(?:\\.\\d{1,3}){2}$|^(?:192\\.168)(?:\\.\\d{1,3}){2}$/\n\nconst IPV6_PRIVATE_REGEX =\n /^(?:fc|fd)(?:[0-9a-f]{2}){0,2}::(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}$|^::(?:ffff:(?:10|127)(?:\\.\\d{1,3}){3}|(?:172\\.1[6-9]|172\\.2[0-9]|172\\.3[0-1])(?:\\.\\d{1,3}){2}|(?:192\\.168)(?:\\.\\d{1,3}){2})$/\n\n/**\n * Helper function to get the input L3 endpoint from the raw endpoint or input endpoint.\n *\n * If neither is provided, an error is thrown.\n *\n * @param rawEndpoint The raw endpoint string to parse.\n * @param inputEndpoint The input endpoint object to use if the raw endpoint is not provided.\n * @returns The parsed L3 endpoint object.\n */\nexport async function requireInputL3Endpoint(\n rawEndpoint: string | undefined,\n inputEndpoint: Input<network.L3Endpoint> | undefined,\n): Promise<network.L3Endpoint> {\n if (rawEndpoint) {\n return parseL3Endpoint(rawEndpoint)\n }\n\n if (inputEndpoint) {\n return toPromise(inputEndpoint)\n }\n\n throw new Error(\"No endpoint provided\")\n}\n\n/**\n * Helper function to get the input L4 endpoint from the raw endpoint or input endpoint.\n *\n * If neither is provided, an error is thrown.\n *\n * @param rawEndpoint The raw endpoint string to parse.\n * @param inputEndpoint The input endpoint object to use if the raw endpoint is not provided.\n * @returns The parsed L4 endpoint object.\n */\nexport async function requireInputL4Endpoint(\n rawEndpoint: string | undefined,\n inputEndpoint: Input<network.L4Endpoint> | undefined,\n): Promise<network.L4Endpoint> {\n if (rawEndpoint) {\n return parseL4Endpoint(rawEndpoint)\n }\n\n if (inputEndpoint) {\n return toPromise(inputEndpoint)\n }\n\n throw new Error(\"No endpoint provided\")\n}\n\n/**\n * Converts L3 endpoint to L4 endpoint by adding a port and protocol.\n *\n * @param l3Endpoint The L3 endpoint to convert.\n * @param port The port to add to the L3 endpoint.\n * @param protocol The protocol to add to the L3 endpoint. Defaults to \"tcp\".\n * @returns The L4 endpoint with the port and protocol added.\n */\nexport function l3EndpointToL4(\n l3Endpoint: InputL3Endpoint,\n port: number,\n protocol: network.L4Protocol = \"tcp\",\n): network.L4Endpoint {\n return {\n ...parseL3Endpoint(l3Endpoint),\n port,\n protocol,\n }\n}\n\n/**\n * Filters the endpoints based on the given filter.\n *\n * @param endpoints The list of endpoints to filter.\n * @param filter The filter to apply. If not provided, the endpoints will be filtered by the most accessible type: `public` > `external` > `internal`.\n * @param types The list of endpoint types to filter by. If provided, only endpoints of these types will be returned.\n *\n * @returns The filtered list of endpoints.\n */\nexport function filterEndpoints<\n TEndpoint extends network.L34Endpoint,\n TType extends network.L34Endpoint[\"type\"],\n>(\n endpoints: TEndpoint[],\n filter?: network.EndpointFilter,\n types?: TType[],\n): (TEndpoint & { type: TType })[] {\n if (filter?.length) {\n endpoints = endpoints.filter(endpoint => filter.includes(endpoint.visibility))\n } else if (endpoints.some(endpoint => endpoint.visibility === \"public\")) {\n endpoints = endpoints.filter(endpoint => endpoint.visibility === \"public\")\n } else if (endpoints.some(endpoint => endpoint.visibility === \"external\")) {\n endpoints = endpoints.filter(endpoint => endpoint.visibility === \"external\")\n }\n\n if (types?.length) {\n endpoints = endpoints.filter(endpoint => types.includes(endpoint.type as TType))\n }\n\n return endpoints as (TEndpoint & { type: TType })[]\n}\n\n/**\n * Converts a L3 endpoint to CIDR notation.\n *\n * If the endpoint is a hostname, an error is thrown.\n *\n * @param l3Endpoint The L3 endpoint to convert.\n * @returns The CIDR notation of the L3 endpoint.\n */\nexport function l3EndpointToCidr(l3Endpoint: network.L3Endpoint): string {\n switch (l3Endpoint.type) {\n case \"ipv4\":\n return `${l3Endpoint.address}/32`\n case \"ipv6\":\n return `${l3Endpoint.address}/128`\n case \"hostname\":\n throw new Error(\"Cannot convert hostname to CIDR\")\n }\n}\n\nconst udpAppProtocols = [\"dns\", \"dhcp\"]\n\n/**\n * Parses a L7 endpoint from a string.\n *\n * The format is: `appProtocol://endpoint[:port][/resource]`\n *\n * @param l7Endpoint The L7 endpoint string to parse.\n * @returns The parsed L7 endpoint object.\n */\nexport function parseL7Endpoint(l7Endpoint: InputL7Endpoint): network.L7Endpoint {\n if (typeof l7Endpoint === \"object\") {\n return l7Endpoint\n }\n\n const match = l7Endpoint.match(L7_ENDPOINT_RE)\n if (!match) {\n throw new Error(`Invalid L7 endpoint: \"${l7Endpoint}\"`)\n }\n\n const { appProtocol, ipv6, ipv4, hostname, port, resource } = match.groups!\n\n let visibility: network.EndpointVisibility = \"public\"\n\n if (ipv4 && IPV4_PRIVATE_REGEX.test(ipv4)) {\n visibility = \"external\"\n } else if (ipv6 && IPV6_PRIVATE_REGEX.test(ipv6)) {\n visibility = \"external\"\n }\n\n return {\n type: ipv6 ? \"ipv6\" : ipv4 ? \"ipv4\" : \"hostname\",\n visibility,\n address: ipv6 || ipv4,\n hostname: hostname,\n\n // Default port for L7 endpoints (TODO: add more specific defaults for common protocols)\n port: port ? parseInt(port, 10) : 443,\n\n // L7 endpoints typically use TCP, but can also use UDP for specific protocols\n protocol: udpAppProtocols.includes(appProtocol) ? \"udp\" : \"tcp\",\n\n appProtocol,\n resource: resource || \"\",\n } as network.L7Endpoint\n}\n\n/**\n * Updates the endpoints based on the given mode.\n *\n * @param currentEndpoints The current endpoints to update.\n * @param endpoints The new endpoints to add in string format.\n * @param inputEndpoints The input endpoints to add in object format.\n * @param mode The mode to use when updating the endpoints. Can be \"replace\" or \"prepend\". Defaults to \"prepend\".\n * @returns The updated list of endpoints with duplicates removed.\n */\nexport async function updateEndpoints<TEndpoints extends network.L34Endpoint>(\n currentEndpoints: Input<TEndpoints[]>,\n endpoints: string[] | undefined,\n inputEndpoints: Input<TEndpoints[]> | undefined,\n mode: ArrayPatchMode = \"prepend\",\n): Promise<TEndpoints[]> {\n const resolvedCurrentEndpoints = await toPromise(currentEndpoints)\n const newEndpoints = await parseEndpoints(endpoints, inputEndpoints)\n\n if (mode === \"replace\") {\n return newEndpoints as TEndpoints[]\n }\n\n return uniqueBy(\n [...newEndpoints, ...resolvedCurrentEndpoints],\n l34EndpointToString,\n ) as TEndpoints[]\n}\n\n/**\n * Parses a list of endpoints from strings and input objects.\n *\n * @param endpoints The list of endpoint strings to parse.\n * @param inputEndpoints The list of input endpoint objects to use.\n * @returns The parsed list of endpoint objects with duplicates removed.\n */\nexport async function parseEndpoints<TEndpoints extends network.L34Endpoint>(\n endpoints: string[] | undefined,\n inputEndpoints: Input<TEndpoints[]> | undefined,\n): Promise<TEndpoints[]> {\n const resolvedInputEndpoints = await toPromise(inputEndpoints)\n\n return uniqueBy(\n [...(endpoints?.map(parseL34Endpoint) ?? []), ...(resolvedInputEndpoints ?? [])],\n l34EndpointToString,\n ) as TEndpoints[]\n}\n","import type { common, ssh } from \"@highstate/library\"\nimport { homedir } from \"node:os\"\nimport {\n ComponentResource,\n type ComponentResourceOptions,\n type Input,\n type InputOrArray,\n interpolate,\n type Output,\n output,\n toPromise,\n} from \"@highstate/pulumi\"\nimport { sha256 } from \"@noble/hashes/sha2\"\nimport { local, remote, type types } from \"@pulumi/command\"\nimport { flat } from \"remeda\"\nimport { l3EndpointToString } from \"./network\"\n\n/**\n * Creates a connection object for the given SSH credentials.\n *\n * @param ssh The SSH credentials.\n * @returns An output connection object for Pulumi remote commands.\n */\nexport function getServerConnection(\n ssh: Input<ssh.Connection>,\n): Output<types.input.remote.ConnectionArgs> {\n return output(ssh).apply(ssh => ({\n host: l3EndpointToString(ssh.endpoints[0]),\n port: ssh.endpoints[0].port,\n user: ssh.user,\n password: ssh.password,\n privateKey: ssh.keyPair?.privateKey,\n dialErrorLimit: 3,\n hostKey: ssh.hostKey,\n }))\n}\n\nexport type CommandHost = \"local\" | Input<common.Server>\nexport type CommandRunMode = \"auto\" | \"prefer-host\"\n\nexport type CommandArgs = {\n /**\n * The host to run the command on.\n *\n * Can be \"local\" for local execution or a server object for remote execution.\n */\n host: CommandHost\n\n /**\n * The command to run when the resource is created.\n *\n * If an array is provided, it will be joined with spaces.\n */\n create: InputOrArray<string>\n\n /**\n * The command to run when the resource is updated or one of the triggers changes.\n *\n * If not set, the `create` command will be used.\n */\n update?: InputOrArray<string>\n\n /**\n * The command to run when the resource is deleted.\n */\n delete?: InputOrArray<string>\n\n /**\n * The stdin content to pass to the command.\n */\n stdin?: Input<string>\n\n /**\n * The logging level for the command.\n */\n logging?: Input<local.Logging>\n\n /**\n * The triggers for the command.\n *\n * They will be captured in the command's state and will trigger the command to run again\n * if they change.\n */\n triggers?: InputOrArray<unknown>\n\n /**\n * The update triggers for the command.\n *\n * Unlike `triggers`, which replace the entire resource on change, these will only trigger the `update` command.\n *\n * Under the hood, it is implemented using a hash of the provided values and passing it as environment variable.\n * It is recommended to pass only primitive values (strings, numbers, booleans) or small objects/arrays for proper serialization.\n */\n updateTriggers?: InputOrArray<unknown>\n\n /**\n * The working directory for the command.\n *\n * If not set, the command will run in the user's home directory (for both local and remote hosts).\n */\n cwd?: Input<string>\n\n /**\n * The environment variables to set for the command.\n */\n environment?: Input<Record<string, Input<string>>>\n\n /**\n * The run mode for the command.\n *\n * - `auto` (default): if the `image` is set, it will always run in a container, never on the host;\n * otherwise, it will run on the host.\n *\n * - `prefer-host`: it will try to run on the host if the executable is available;\n * otherwise, it will run in a container or throw an error if the `image` is not set.\n */\n runMode?: CommandRunMode\n\n /**\n * The container image to use to run the command.\n */\n image?: Input<string>\n\n /**\n * The paths to mount if the command runs in a container.\n *\n * They will be mounted to the same paths in the container.\n */\n mounts?: InputOrArray<string>\n}\n\nexport type TextFileArgs = {\n /**\n * The host to run the command on.\n */\n host: CommandHost\n\n /**\n * The absolute path to the file on the host.\n */\n path: Input<string>\n\n /**\n * The content to write to the file.\n */\n content: Input<string>\n}\n\nexport type WaitForArgs = CommandArgs & {\n /**\n * The timeout in seconds to wait for the command to complete.\n *\n * Defaults to 5 minutes (300 seconds).\n */\n timeout?: Input<number>\n\n /**\n * The interval in seconds to wait between checks.\n *\n * Defaults to 5 seconds.\n */\n interval?: Input<number>\n}\n\nfunction createCommand(command: string | string[]): string {\n if (Array.isArray(command)) {\n return command.join(\" \")\n }\n\n return command\n}\n\nfunction wrapWithWorkDir(dir?: Input<string>) {\n if (!dir) {\n return (command: string) => output(command)\n }\n\n return (command: string) => interpolate`cd \"${dir}\" && ${command}`\n}\n\nfunction wrapWithEnvironment(environment?: Input<Record<string, Input<string>>>) {\n if (!environment) {\n return (command: string) => output(command)\n }\n\n return (command: string) =>\n output({ command, environment }).apply(({ command, environment }) => {\n if (!environment || Object.keys(environment).length === 0) {\n return command\n }\n\n const envExport = Object.entries(environment)\n .map(([key, value]) => `export ${key}=\"${value}\"`)\n .join(\" && \")\n\n return `${envExport} && ${command}`\n })\n}\n\nfunction wrapWithWaitFor(timeout: Input<number> = 300, interval: Input<number> = 5) {\n return (command: string | string[]) =>\n // TOD: escape the command\n interpolate`timeout ${timeout} bash -c 'while ! ${createCommand(command)}; do sleep ${interval}; done'`\n}\n\nfunction applyUpdateTriggers(\n env: Input<Record<string, Input<string>>> | undefined,\n triggers: InputOrArray<unknown> | undefined,\n) {\n return output({ env, triggers }).apply(({ env, triggers }) => {\n if (!triggers) {\n return env\n }\n\n const hash = sha256(JSON.stringify(triggers))\n const hashHex = Buffer.from(hash).toString(\"hex\")\n\n return {\n ...env,\n HIGHSTATE_UPDATE_TRIGGER_HASH: hashHex,\n }\n })\n}\n\nexport class Command extends ComponentResource {\n public readonly stdout: Output<string>\n public readonly stderr: Output<string>\n\n constructor(name: string, args: CommandArgs, opts?: ComponentResourceOptions) {\n super(\"highstate:common:Command\", name, args, opts)\n\n const environment = applyUpdateTriggers(\n args.environment,\n args.updateTriggers,\n ) as local.CommandArgs[\"environment\"]\n\n const command =\n args.host === \"local\"\n ? new local.Command(\n name,\n {\n create: output(args.create).apply(createCommand),\n update: args.update ? output(args.update).apply(createCommand) : undefined,\n delete: args.delete ? output(args.delete).apply(createCommand) : undefined,\n logging: args.logging,\n triggers: args.triggers ? output(args.triggers).apply(flat) : undefined,\n dir: args.cwd ?? homedir(),\n environment,\n stdin: args.stdin,\n },\n { ...opts, parent: this },\n )\n : new remote.Command(\n name,\n {\n connection: output(args.host).apply(server => {\n if (!server.ssh) {\n throw new Error(`The server \"${server.hostname}\" has no SSH credentials`)\n }\n\n return getServerConnection(server.ssh)\n }),\n\n create: output(args.create)\n .apply(createCommand)\n .apply(wrapWithWorkDir(args.cwd))\n .apply(wrapWithEnvironment(environment)),\n\n update: args.update\n ? output(args.update)\n .apply(createCommand)\n .apply(wrapWithWorkDir(args.cwd))\n .apply(wrapWithEnvironment(environment))\n : undefined,\n\n delete: args.delete\n ? output(args.delete)\n .apply(createCommand)\n .apply(wrapWithWorkDir(args.cwd))\n .apply(wrapWithEnvironment(environment))\n : undefined,\n\n logging: args.logging,\n triggers: args.triggers ? output(args.triggers).apply(flat) : undefined,\n stdin: args.stdin,\n\n addPreviousOutputInEnv: false,\n\n // TODO: does not work if server do not define AcceptEnv\n // environment,\n },\n { ...opts, parent: this },\n )\n\n this.stdout = command.stdout\n this.stderr = command.stderr\n\n this.registerOutputs({\n stdout: this.stdout,\n stderr: this.stderr,\n })\n }\n\n /**\n * Waits for the command to complete and returns its output.\n * The standard output will be returned.\n */\n async wait(): Promise<string> {\n return await toPromise(this.stdout)\n }\n\n /**\n * Creates a command that writes the given content to a file on the host.\n * The file will be created if it does not exist, and overwritten if it does.\n *\n * Use for small text files like configuration files.\n */\n static createTextFile(\n name: string,\n options: TextFileArgs,\n opts?: ComponentResourceOptions,\n ): Command {\n return new Command(\n name,\n {\n host: options.host,\n create: interpolate`mkdir -p $(dirname \"${options.path}\") && cat > ${options.path}`,\n delete: interpolate`rm -rf ${options.path}`,\n stdin: options.content,\n },\n opts,\n )\n }\n\n /**\n * Creates a command that waits for a file to be created and then reads its content.\n * This is useful for waiting for a file to be generated by another process.\n *\n * Use for small text files like configuration files.\n */\n static receiveTextFile(\n name: string,\n options: Omit<TextFileArgs, \"content\">,\n opts?: ComponentResourceOptions,\n ): Command {\n return new Command(\n name,\n {\n host: options.host,\n create: interpolate`while ! test -f \"${options.path}\"; do sleep 1; done; cat \"${options.path}\"`,\n logging: \"stderr\",\n },\n opts,\n )\n }\n\n /**\n * Creates a command that waits for a condition to be met.\n * The command will run until the condition is met or the timeout is reached.\n *\n * The condition is considered met if the command returns a zero exit code.\n *\n * @param name The name of the command resource.\n * @param args The arguments for the command, including the condition to check.\n * @param opts Optional resource options.\n */\n static waitFor(name: string, args: WaitForArgs, opts?: ComponentResourceOptions): Command {\n return new Command(\n name,\n {\n ...args,\n create: output(args.create).apply(wrapWithWaitFor(args.timeout, args.interval)),\n update: args.update\n ? output(args.update).apply(wrapWithWaitFor(args.timeout, args.interval))\n : undefined,\n delete: args.delete\n ? output(args.delete).apply(wrapWithWaitFor(args.timeout, args.interval))\n : undefined,\n },\n opts,\n )\n }\n}\n","import type { z } from \"@highstate/contract\"\nimport type { ImplementationReference } from \"@highstate/library\"\nimport { type Input, type Output, output, toPromise, type Unwrap } from \"@highstate/pulumi\"\n\n/**\n * The ImplementationMediator is used as a contract between the calling code and the implementation.\n *\n * From the calling code perspective, it provides a way to define the input and output schemas for the implementation\n * and call the implementation with the provided input.\n *\n * From the implementation perspective, it provides a way to get zod function with automatic type inference and validation.\n */\nexport class ImplementationMediator<\n TInputSchema extends z.ZodType,\n TOutputSchema extends z.ZodType,\n> {\n constructor(\n readonly path: string,\n private readonly inputSchema: TInputSchema,\n private readonly outputSchema: TOutputSchema,\n ) {}\n\n implement<TDataSchema extends z.ZodType>(\n dataSchema: TDataSchema,\n func: (\n input: z.infer<TInputSchema>,\n data: z.infer<TDataSchema>,\n ) => z.infer<TOutputSchema> | Promise<z.infer<TOutputSchema>>,\n ) {\n return async (\n input: z.infer<TInputSchema>,\n data: z.infer<TDataSchema>,\n ): Promise<z.infer<TOutputSchema>> => {\n const parsedInput = this.inputSchema.safeParse(input)\n if (!parsedInput.success) {\n throw new Error(\n `Invalid input for implementation \"${this.path}\": ${parsedInput.error.message}`,\n )\n }\n\n const parsedData = dataSchema.safeParse(data)\n if (!parsedData.success) {\n throw new Error(\n `Invalid data for implementation \"${this.path}\": ${parsedData.error.message}`,\n )\n }\n\n const result = await func(parsedInput.data, parsedData.data)\n const parsedResult = this.outputSchema.safeParse(result)\n\n if (!parsedResult.success) {\n throw new Error(\n `Invalid output from implementation \"${this.path}\": ${parsedResult.error.message}`,\n )\n }\n\n return parsedResult.data\n }\n }\n\n async call(\n implRef: Input<ImplementationReference>,\n input: Input<z.infer<TInputSchema>>,\n ): Promise<z.infer<TOutputSchema>> {\n const resolvedImplRef = await toPromise(implRef)\n const resolvedInput = await toPromise(input)\n\n const importPath = `${resolvedImplRef.package}/impl/${this.path}`\n\n let impl: Record<string, unknown>\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n impl = await import(importPath)\n } catch (error) {\n throw new Error(`Failed to import module \"${importPath}\" required by implementation.`, {\n cause: error,\n })\n }\n\n const funcs = Object.entries(impl).filter(value => typeof value[1] === \"function\") as [\n string,\n (...args: unknown[]) => unknown,\n ][]\n\n if (funcs.length === 0) {\n throw new Error(`No implementation functions found in module \"${importPath}\".`)\n }\n\n if (funcs.length > 1) {\n throw new Error(\n `Multiple implementation functions found in module \"${importPath}\": ${funcs.map(func => func[0]).join(\", \")}. ` +\n \"Ensure only one function is exported.\",\n )\n }\n\n const [funcName, implFunc] = funcs[0]\n\n let result: unknown\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n result = await implFunc(resolvedInput, resolvedImplRef.data)\n } catch (error) {\n console.error(`Error in implementation function \"${funcName}\":`, error)\n throw new Error(`Implementation function \"${funcName}\" failed`)\n }\n\n const parsedResult = this.outputSchema.safeParse(result)\n if (!parsedResult.success) {\n throw new Error(\n `Implementation function \"${funcName}\" returned invalid result: ${parsedResult.error.message}`,\n )\n }\n\n return parsedResult.data\n }\n\n callOutput(\n implRef: Input<ImplementationReference>,\n input: Input<z.infer<TInputSchema>>,\n ): Output<Unwrap<z.infer<TOutputSchema>>> {\n return output(this.call(implRef, input))\n }\n}\n","import type { ArrayPatchMode, dns, network } from \"@highstate/library\"\nimport { getOrCreate, z } from \"@highstate/contract\"\nimport {\n ComponentResource,\n type Input,\n type InputArray,\n type InputOrArray,\n interpolate,\n normalizeInputsAndMap,\n type Output,\n output,\n type ResourceOptions,\n toPromise,\n type Unwrap,\n} from \"@highstate/pulumi\"\nimport { flat, groupBy, uniqueBy } from \"remeda\"\nimport { Command, type CommandHost } from \"./command\"\nimport { ImplementationMediator } from \"./impl-ref\"\nimport {\n filterEndpoints,\n type InputL3Endpoint,\n l3EndpointToString,\n l34EndpointToString,\n parseL3Endpoint,\n} from \"./network\"\n\nexport const dnsRecordMediator = new ImplementationMediator(\n \"dns-record\",\n z.object({ name: z.string(), args: z.custom<ResolvedDnsRecordArgs>() }),\n z.instanceof(ComponentResource),\n)\n\nexport type DnsRecordArgs = {\n /**\n * The DNS provider to use.\n */\n provider: Input<dns.Provider>\n\n /**\n * The name of the DNS record.\n * If not provided, the name of the resource will be used.\n */\n name?: Input<string>\n\n /**\n * The type of the DNS record.\n *\n * If not provided, will be automatically detected based on the value.\n */\n type?: Input<string>\n\n /**\n * The value of the DNS record.\n */\n value: Input<InputL3Endpoint>\n\n /**\n * Whether the DNS record is proxied (e.g. to provide DDoS protection).\n *\n * Available only for public IPs and some DNS providers like Cloudflare.\n * If not supported, the DNS provider will ignore this value.\n */\n proxied?: Input<boolean>\n\n /**\n * The TTL of the DNS record.\n *\n * If not provided, the DNS provider will use its default value.\n */\n ttl?: Input<number>\n\n /**\n * The priority of the DNS record.\n *\n * Only used for some DNS record types (e.g. MX).\n */\n priority?: Input<number>\n\n /**\n * Wait for the DNS record to be created/updated at the specified environment(s) before continuing.\n */\n waitAt?: InputOrArray<CommandHost>\n}\n\nexport type ResolvedDnsRecordArgs = Pick<DnsRecordArgs, \"name\" | \"priority\" | \"ttl\" | \"proxied\"> & {\n /**\n * The value of the DNS record.\n */\n value: Input<string>\n\n /**\n * The type of the DNS record.\n */\n type: Input<string>\n}\n\nexport type DnsRecordSetArgs = Omit<DnsRecordArgs, \"provider\" | \"value\"> & {\n /**\n * The DNS providers to use to create the DNS records.\n *\n * If multiple providers matched the specified domain, records will be created for each of them.\n */\n providers: Input<dns.Provider[]>\n\n /**\n * The value of the DNS record.\n */\n value?: Input<InputL3Endpoint>\n\n /**\n * The values of the DNS records.\n */\n values?: InputArray<InputL3Endpoint>\n}\n\nfunction getTypeByEndpoint(endpoint: network.L3Endpoint): string {\n switch (endpoint.type) {\n case \"ipv4\":\n return \"A\"\n case \"ipv6\":\n return \"AAAA\"\n case \"hostname\":\n return \"CNAME\"\n }\n}\n\n/**\n * Creates a DNS record for the specified value and waits for it to be resolved.\n *\n * Uses the specified DNS provider to create the record.\n */\nexport class DnsRecord extends ComponentResource {\n /**\n * The underlying dns record resource.\n */\n readonly dnsRecord: Output<ComponentResource>\n\n /**\n * The commands to be executed after the DNS record is created/updated.\n *\n * These commands will wait for the DNS record to be resolved to the specified value.\n */\n readonly waitCommands: Output<Command[]>\n\n constructor(name: string, args: DnsRecordArgs, opts?: ResourceOptions) {\n super(\"highstate:common:DnsRecord\", name, args, opts)\n\n const l3Endpoint = output(args.value).apply(value => parseL3Endpoint(value))\n const resolvedValue = l3Endpoint.apply(l3EndpointToString)\n const resolvedType = args.type ? output(args.type) : l3Endpoint.apply(getTypeByEndpoint)\n\n this.dnsRecord = output(args.provider).apply(provider => {\n return dnsRecordMediator.call(provider.implRef, {\n name,\n args: {\n name: args.name,\n priority: args.priority,\n ttl: args.ttl,\n value: resolvedValue,\n type: resolvedType,\n },\n })\n })\n\n this.waitCommands = output({\n waitAt: args.waitAt,\n resolvedType,\n proxied: args.proxied,\n }).apply(({ waitAt, resolvedType, proxied }) => {\n if (resolvedType === \"CNAME\") {\n // TODO: handle CNAME records\n return []\n }\n\n const resolvedHosts = waitAt ? [waitAt].flat() : []\n\n if (proxied) {\n // for proxied records do not verify the value since we do not know the actual IP addressa\n\n return (resolvedHosts as Unwrap<CommandHost>[]).map(host => {\n const hostname = host === \"local\" ? \"local\" : host.hostname\n\n return new Command(\n `${name}.wait-for-dns.${hostname}`,\n {\n host,\n create: [\n interpolate`while ! getent hosts \"${args.name}\";`,\n interpolate`do echo \"Waiting for DNS record \\\"${args.name}\\\" to be available...\";`,\n `sleep 5;`,\n `done`,\n ],\n },\n { parent: this },\n )\n })\n }\n\n return (resolvedHosts as Unwrap<CommandHost>[]).map(host => {\n const hostname = host === \"local\" ? \"local\" : host.hostname\n\n return new Command(\n `${name}.wait-for-dns.${hostname}`,\n {\n host,\n create: [\n interpolate`while ! getent hosts \"${args.name}\" | grep \"${resolvedValue}\";`,\n interpolate`do echo \"Waiting for DNS record \\\"${args.name}\" to resolve to \"${resolvedValue}\"...\";`,\n `sleep 5;`,\n `done`,\n ],\n },\n { parent: this },\n )\n })\n })\n }\n}\n\n/**\n * Creates a set of DNS records for the specified values and waits for them to be resolved.\n */\nexport class DnsRecordSet extends ComponentResource {\n /**\n * The underlying dns record resources.\n */\n readonly dnsRecords: Output<DnsRecord[]>\n\n /**\n * The flat list of all wait commands for the DNS records.\n */\n readonly waitCommands: Output<Command[]>\n\n constructor(name: string, args: DnsRecordSetArgs, opts?: ResourceOptions) {\n super(\"highstate:common:DnsRecordSet\", name, args, opts)\n\n const matchedProviders = output({\n providers: args.providers,\n name: args.name ?? name,\n }).apply(({ providers }) => {\n const matchedProviders = providers.filter(provider => name.endsWith(provider.domain))\n\n if (matchedProviders.length === 0) {\n throw new Error(`No DNS provider matched the domain \"${name}\"`)\n }\n\n return matchedProviders\n })\n\n this.dnsRecords = normalizeInputsAndMap(args.value, args.values, value => {\n return output({\n name: args.name ?? name,\n providers: matchedProviders,\n }).apply(({ name, providers }) => {\n return providers.flatMap(provider => {\n const l3Endpoint = parseL3Endpoint(value)\n\n return new DnsRecord(\n `${name}.${provider.id}.${l3EndpointToString(l3Endpoint)}`,\n {\n name,\n provider,\n value: l3Endpoint,\n type: args.type ?? getTypeByEndpoint(l3Endpoint),\n proxied: args.proxied,\n ttl: args.ttl,\n priority: args.priority,\n waitAt: args.waitAt,\n },\n { parent: this },\n )\n })\n })\n }).apply(flat)\n\n this.waitCommands = this.dnsRecords\n .apply(records => records.flatMap(record => record.waitCommands))\n .apply(flat)\n }\n\n private static readonly dnsRecordSetCache = new Map<string, DnsRecordSet>()\n\n /**\n * Creates a DNS record set for the specified endpoints and waits for it to be resolved.\n *\n * If a DNS record set with the same name already exists, it will be reused.\n *\n * @param name The name of the DNS record set.\n * @param args The arguments for the DNS record set.\n * @param opts The options for the resource.\n */\n static createOnce(name: string, args: DnsRecordSetArgs, opts?: ResourceOptions): DnsRecordSet {\n return getOrCreate(\n DnsRecordSet.dnsRecordSetCache,\n name,\n () => new DnsRecordSet(name, args, opts),\n )\n }\n}\n\n/**\n * Registers the DNS record set for the given endpoints and prepends the corresponding hostname endpoint to the list.\n *\n * Waits for the DNS record set to be created/updated before continuing.\n *\n * Ignores the \"hostname\" endpoints in the list.\n *\n * @param endpoints The list of endpoints to register. Will be modified in place.\n * @param fqdn The FQDN to register the DNS record set for. If not provided, no DNS record set will be created and array will not be modified.\n * @param fqdnEndpointFilter The filter to apply to the endpoints before passing them to the DNS record set. Does not apply to the resulted endpoint list.\n * @param dnsProviders The DNS providers to use to create the DNS records.\n */\nexport async function updateEndpointsWithFqdn<TEndpoint extends network.L34Endpoint>(\n endpoints: Input<TEndpoint[]>,\n fqdn: string | undefined,\n fqdnEndpointFilter: network.EndpointFilter,\n patchMode: ArrayPatchMode,\n dnsProviders: Input<dns.Provider[]>,\n): Promise<{ endpoints: TEndpoint[]; dnsRecordSet: DnsRecordSet | undefined }> {\n const resolvedEndpoints = await toPromise(endpoints)\n\n if (!fqdn) {\n return {\n endpoints: resolvedEndpoints as TEndpoint[],\n dnsRecordSet: undefined,\n }\n }\n\n const filteredEndpoints = filterEndpoints(resolvedEndpoints, fqdnEndpointFilter)\n\n const dnsRecordSet = new DnsRecordSet(fqdn, {\n providers: dnsProviders,\n values: filteredEndpoints,\n waitAt: \"local\",\n })\n\n const portProtocolGroups = groupBy(filteredEndpoints, endpoint =>\n endpoint.port ? `${endpoint.port}-${endpoint.protocol}` : \"\",\n )\n\n const newEndpoints: TEndpoint[] = []\n\n for (const group of Object.values(portProtocolGroups)) {\n newEndpoints.unshift({\n type: \"hostname\",\n hostname: fqdn,\n visibility: group[0].visibility,\n port: group[0].port,\n protocol: group[0].protocol,\n } as TEndpoint)\n }\n\n await toPromise(\n dnsRecordSet.waitCommands.apply(waitCommands => waitCommands.map(command => command.stdout)),\n )\n\n if (patchMode === \"prepend\") {\n return {\n endpoints: uniqueBy(\n //\n [...newEndpoints, ...(resolvedEndpoints as TEndpoint[])],\n endpoint => l34EndpointToString(endpoint),\n ),\n dnsRecordSet,\n }\n }\n\n return {\n endpoints: newEndpoints,\n dnsRecordSet,\n }\n}\n","import type { TlsCertificate } from \"./tls\"\nimport { z } from \"@highstate/contract\"\nimport { type common, network } from \"@highstate/library\"\nimport {\n ComponentResource,\n type ComponentResourceOptions,\n type Input,\n type Output,\n output,\n Resource,\n} from \"@highstate/pulumi\"\nimport { ImplementationMediator } from \"./impl-ref\"\n\nexport const gatewayRouteMediator = new ImplementationMediator(\n \"gateway-route\",\n z.object({\n name: z.string(),\n spec: z.custom<GatewayRouteSpec>(),\n opts: z.custom<ComponentResourceOptions>().optional(),\n }),\n z.object({\n resource: z.instanceof(Resource),\n endpoints: network.l3EndpointEntity.schema.array(),\n }),\n)\n\nexport type GatewayRouteSpec = {\n /**\n * The FQDN to expose the workload on.\n */\n fqdn?: Input<string>\n\n /**\n * The endpoints of the backend workload to route traffic to.\n */\n endpoints: Input<network.L4Endpoint[]>\n\n /**\n * The native data to pass to the implementation.\n *\n * This is used for data which implementation may natively understand,\n * such as Kubernetes `Service` resources.\n *\n * Implementations may use this data to create more efficient routes\n * using native resources.\n */\n nativeData?: Input<unknown>\n\n /**\n * The TLS certificate to use for the route.\n */\n tlsCertificate?: Input<TlsCertificate | undefined>\n} & (\n | {\n type: \"http\"\n\n /**\n * Whether to expose the workload over plain HTTP.\n *\n * By default, the workload will be exposed over HTTPS.\n */\n insecure?: Input<boolean>\n\n /**\n * The relative path to expose the workload on.\n *\n * By default, the workload will be exposed on the root path (`/`).\n */\n path?: Input<string>\n }\n | {\n type: \"l3\"\n\n /**\n * The ports to request for the workload.\n *\n * The order must match the order of the ports in the service.\n *\n * If not provided, random ports will be assigned.\n */\n ports?: number\n }\n)\n\nexport type GatewayRouteArgs = GatewayRouteSpec & {\n /**\n * The gateway to attach the route to.\n */\n gateway: Input<common.Gateway>\n}\n\nexport class GatewayRoute extends ComponentResource {\n /**\n * The underlying resource created by the implementation.\n */\n readonly resource: Output<Resource>\n\n /**\n * The endpoints of the gateway which serve this route.\n *\n * In most cases, this will be a single endpoint of the gateway shared for all routes.\n */\n readonly endpoints: Output<network.L3Endpoint[]>\n\n constructor(name: string, args: GatewayRouteArgs, opts?: ComponentResourceOptions) {\n super(\"highstate:common:GatewayRoute\", name, args, opts)\n\n const { resource, endpoints } = gatewayRouteMediator.callOutput(output(args.gateway).implRef, {\n name,\n spec: args,\n opts: { ...opts, parent: this },\n })\n\n this.resource = resource\n this.endpoints = endpoints\n }\n}\n","import type { common } from \"@highstate/library\"\nimport { getOrCreate, z } from \"@highstate/contract\"\nimport {\n ComponentResource,\n type ComponentResourceOptions,\n type Input,\n type InputArray,\n normalizeInputs,\n type Output,\n output,\n Resource,\n} from \"@highstate/pulumi\"\nimport { ImplementationMediator } from \"./impl-ref\"\n\nexport const tlsCertificateMediator = new ImplementationMediator(\n \"tls-certificate\",\n z.object({\n name: z.string(),\n spec: z.custom<TlsCertificateSpec>(),\n opts: z.custom<ComponentResourceOptions>().optional(),\n }),\n z.instanceof(Resource),\n)\n\nexport type TlsCertificateSpec = {\n /**\n * The common name for the certificate.\n */\n commonName?: Input<string>\n\n /**\n * The alternative DNS names for the certificate.\n */\n dnsNames?: InputArray<string>\n\n /**\n * The native data to pass to the implementation.\n *\n * This is used for data which implementation may natively understand\n * and may use this data to create certificates using native resources.\n */\n nativeData?: unknown\n}\n\nexport type TlsCertificateArgs = TlsCertificateSpec & {\n /**\n * The issuer to use for the certificate.\n */\n issuer?: Input<common.TlsIssuer>\n\n /**\n * The issuers to use for the certificate.\n *\n * If multiple issuers are provided, the certificate will be created using the first issuer that supports the requested common name.\n */\n issuers?: InputArray<common.TlsIssuer>\n}\n\nexport class TlsCertificate extends ComponentResource {\n /**\n * The underlying resource created by the implementation.\n */\n readonly resource: Output<Resource>\n\n constructor(name: string, args: TlsCertificateArgs, opts?: ComponentResourceOptions) {\n super(\"highstate:common:TlsCertificate\", name, args, opts)\n\n const issuers = normalizeInputs(args.issuer, args.issuers)\n\n this.resource = output({\n issuers,\n commonName: args.commonName,\n dnsNames: args.dnsNames,\n }).apply(async ({ issuers, commonName, dnsNames }) => {\n // for now, we require single issuer to match all requested names\n const matchedIssuer = issuers.find(issuer => {\n if (commonName && !commonName.endsWith(issuer.domain)) {\n return false\n }\n\n if (dnsNames && !dnsNames.every(name => name.endsWith(issuer.domain))) {\n return false\n }\n\n return true\n })\n\n if (!matchedIssuer) {\n throw new Error(\n `No TLS issuer matched the common name \"${commonName}\" and DNS names \"${dnsNames?.join(\", \") ?? \"\"}\"`,\n )\n }\n\n return await tlsCertificateMediator.call(matchedIssuer.implRef, {\n name,\n spec: args,\n })\n })\n }\n\n private static readonly tlsCertificateCache = new Map<string, TlsCertificate>()\n\n /**\n * Creates a TLS certificate for the specified common name and DNS names.\n *\n * If a TLS certificate with the same name already exists, it will be reused.\n *\n * @param name The name of the TLS certificate.\n * @param args The arguments for the TLS certificate.\n * @param opts The options for the resource.\n */\n static createOnce(\n name: string,\n args: TlsCertificateArgs,\n opts?: ComponentResourceOptions,\n ): TlsCertificate {\n return getOrCreate(\n TlsCertificate.tlsCertificateCache,\n name,\n () => new TlsCertificate(name, args, opts),\n )\n }\n}\n","import type { common } from \"@highstate/library\"\nimport type { Except } from \"type-fest\"\nimport {\n ComponentResource,\n type ComponentResourceOptions,\n type Input,\n type Output,\n output,\n toPromise,\n} from \"@highstate/pulumi\"\nimport { DnsRecordSet } from \"./dns\"\nimport { GatewayRoute, type GatewayRouteSpec } from \"./gateway\"\nimport { TlsCertificate } from \"./tls\"\n\nexport type AccessPointRouteArgs = Except<GatewayRouteSpec, \"nativeData\"> & {\n /**\n * The access point to use to expose the route.\n */\n accessPoint: Input<common.AccessPoint>\n\n /**\n * The native data to pass to the gateway route implementation.\n */\n gatewayNativeData?: unknown\n\n /**\n * The native data to pass to the tls ceertificate implementation.\n */\n tlsCertificateNativeData?: unknown\n}\n\nexport class AccessPointRoute extends ComponentResource {\n /**\n * The created gateway route.\n */\n readonly route: GatewayRoute\n\n /**\n * The DNS record set created for the route.\n *\n * May be shared between multiple routes with the same FQDN.\n */\n readonly dnsRecordSet?: Output<DnsRecordSet | undefined>\n\n /**\n * The TLS certificate created for the route.\n *\n * May be shared between multiple routes with the same FQDN.\n */\n readonly tlsCertificate?: Output<TlsCertificate | undefined>\n\n constructor(name: string, args: AccessPointRouteArgs, opts?: ComponentResourceOptions) {\n super(\"highstate:common:AccessPointRoute\", name, args, opts)\n\n // 1. create TLS certificate if the route is HTTPS and the access point has TLS issuers\n if (args.fqdn && args.type === \"http\" && !args.insecure) {\n this.tlsCertificate = output(args.accessPoint).apply(accessPoint => {\n if (accessPoint.tlsIssuers.length === 0) {\n return undefined\n }\n\n return TlsCertificate.createOnce(\n name,\n {\n issuers: accessPoint.tlsIssuers,\n dnsNames: args.fqdn ? [args.fqdn] : [],\n nativeData: args.tlsCertificateNativeData,\n },\n { ...opts, parent: this },\n )\n })\n }\n\n // 2. create the route and resolve the gateway endpoints\n this.route = new GatewayRoute(\n name,\n {\n ...args,\n gateway: output(args.accessPoint).gateway,\n tlsCertificate: this.tlsCertificate,\n nativeData: args.gatewayNativeData,\n },\n { ...opts, parent: this },\n )\n\n // 3. register DNS records if FQDN is provided and the access point has DNS providers\n if (args.fqdn) {\n this.dnsRecordSet = output(args.accessPoint).apply(async accessPoint => {\n if (accessPoint.dnsProviders.length === 0) {\n return undefined\n }\n\n const fqdn = await toPromise(args.fqdn)\n if (!fqdn) {\n return undefined\n }\n\n return DnsRecordSet.createOnce(\n fqdn,\n {\n providers: output(args.accessPoint).dnsProviders,\n values: this.route.endpoints,\n waitAt: \"local\",\n },\n { ...opts, parent: this },\n )\n })\n }\n }\n}\n","import type { common, network } from \"@highstate/library\"\nimport { createHash } from \"node:crypto\"\nimport { createReadStream } from \"node:fs\"\nimport { cp, mkdir, mkdtemp, rename, rm, stat, writeFile } from \"node:fs/promises\"\nimport { tmpdir } from \"node:os\"\nimport { basename, dirname, extname, join } from \"node:path\"\nimport { Readable } from \"node:stream\"\nimport { pipeline } from \"node:stream/promises\"\nimport { type CommonObjectMeta, type File, HighstateSignature } from \"@highstate/contract\"\nimport { asset, toPromise } from \"@highstate/pulumi\"\nimport { minimatch } from \"minimatch\"\nimport * as tar from \"tar\"\nimport unzipper from \"unzipper\"\nimport { type InputL7Endpoint, l7EndpointToString, parseL7Endpoint } from \"./network\"\n\nexport type FolderPackOptions = {\n /**\n * The patterns to include in the packed archive.\n * If not provided, all files and folders will be included.\n */\n include?: string[]\n\n /**\n * The patterns to exclude from the packed archive.\n * Applied after include patterns.\n * If not provided, no files or folders will be excluded.\n */\n exclude?: string[]\n}\n\n/**\n * Creates Pulumi asset from Highstate file.\n *\n * @param file The file entity to create the asset from.\n * @returns The created asset.\n */\nexport function assetFromFile(file: common.File): asset.Asset {\n if (file.content.type === \"remote\") {\n return new asset.RemoteAsset(l7EndpointToString(file.content.endpoint))\n }\n\n if (file.content.type === \"local\") {\n return new asset.FileAsset(file.content.path)\n }\n\n if (file.content.type === \"artifact\") {\n throw new Error(\n \"Artifact-based files cannot be converted to Pulumi assets directly. Use MaterializedFile instead.\",\n )\n }\n\n if (file.content.isBinary) {\n throw new Error(\n \"Cannot create asset from inline binary file content. Please open an issue if you need this feature.\",\n )\n }\n\n return new asset.StringAsset(file.content.value)\n}\n\n/**\n * Creates Pulumi archive from Highstate folder.\n *\n * @param folder The folder entity to create the asset archive from.\n * @returns The created asset archive.\n */\nexport function archiveFromFolder(folder: common.Folder): asset.Archive {\n if (folder.content.type === \"remote\") {\n return new asset.RemoteArchive(l7EndpointToString(folder.content.endpoint))\n }\n\n if (folder.content.type === \"local\") {\n return new asset.FileArchive(folder.content.path)\n }\n\n if (folder.content.type === \"artifact\") {\n throw new Error(\n \"Artifact-based folders cannot be converted to Pulumi assets directly. Use MaterializedFolder instead.\",\n )\n }\n\n const files: Record<string, asset.Asset> = {}\n\n for (const file of folder.content.files) {\n files[file.meta.name] = assetFromFile(file)\n }\n\n for (const subfolder of folder.content.folders) {\n files[subfolder.meta.name] = archiveFromFolder(subfolder)\n }\n\n return new asset.AssetArchive(files)\n}\n\n/**\n * Extracts a tar or zip archive from a stream to a destination directory.\n *\n * @param stream The stream containing the archive data\n * @param destinationPath The path where to extract the archive\n * @param archiveType The type of archive ('tar' or 'zip')\n */\nasync function unarchiveFromStream(\n stream: Readable,\n destinationPath: string,\n archiveType: \"tar\" | \"zip\",\n): Promise<void> {\n await mkdir(destinationPath, { recursive: true })\n\n switch (archiveType) {\n case \"tar\": {\n const extractStream = tar.extract({\n cwd: destinationPath,\n strict: true,\n })\n\n await pipeline(stream, extractStream)\n return\n }\n case \"zip\": {\n // Extract directly from stream using unzipper\n await pipeline(stream, unzipper.Extract({ path: destinationPath }))\n return\n }\n }\n}\n\n/**\n * Determines the archive type based on file extension or content type.\n *\n * @param fileName The name of the file\n * @param contentType Optional content type from HTTP headers\n * @returns The detected archive type or null if not an archive\n */\nfunction detectArchiveType(fileName: string, contentType?: string): \"tar\" | \"zip\" | null {\n const ext = extname(fileName).toLowerCase()\n\n if (ext === \".tar\" || ext === \".tgz\" || ext === \".tar.gz\") {\n return \"tar\"\n }\n\n if (ext === \".zip\") {\n return \"zip\"\n }\n\n // Fallback to content type\n if (contentType) {\n if (contentType.includes(\"tar\") || contentType.includes(\"gzip\")) {\n return \"tar\"\n }\n if (contentType.includes(\"zip\")) {\n return \"zip\"\n }\n }\n\n return null\n}\n\n/**\n * The `MaterializedFile` class represents a file entity that has been materialized\n * to a local filesystem path.\n *\n * It handles creating a temporary directory, writing the file content to that directory,\n * and cleaning up the temporary files when disposed.\n *\n * For improved cleanup reliability, the class will use HIGHSTATE_TEMP_PATH as the base\n * directory for temporary files if available, allowing for centralized cleanup by the runner.\n */\nexport class MaterializedFile implements AsyncDisposable {\n private _tmpPath?: string\n private _path!: string\n private _disposed = false\n\n readonly artifactMeta: CommonObjectMeta\n\n constructor(\n readonly entity: common.File,\n readonly parent?: MaterializedFolder,\n ) {\n this.artifactMeta = {\n title: `Materialized file \"${entity.meta.name}\"`,\n }\n }\n\n get path(): string {\n return this._path\n }\n\n private async _open(): Promise<void> {\n if (this.parent) {\n // if the parent folder is provided, the file path is relative to the parent folder\n this._path = join(this.parent.path, this.entity.meta.name)\n } else {\n // otherwise, the file path is in a temporary directory\n // use HIGHSTATE_TEMP_PATH as base if available for better cleanup reliability\n const tempBase = process.env.HIGHSTATE_TEMP_PATH || tmpdir()\n this._tmpPath = await mkdtemp(join(tempBase, \"highstate-file-\"))\n this._path = join(this._tmpPath, this.entity.meta.name)\n }\n\n switch (this.entity.content.type) {\n case \"embedded\": {\n const content = this.entity.content.isBinary\n ? Buffer.from(this.entity.content.value, \"base64\")\n : this.entity.content.value\n\n await writeFile(this._path, content, { mode: this.entity.meta.mode })\n break\n }\n case \"local\": {\n await cp(this.entity.content.path, this._path, { mode: this.entity.meta.mode })\n break\n }\n case \"remote\": {\n const response = await fetch(l7EndpointToString(this.entity.content.endpoint))\n if (!response.ok) throw new Error(`Failed to fetch: ${response.statusText}`)\n\n const arrayBuffer = await response.arrayBuffer()\n await writeFile(this._path, Buffer.from(arrayBuffer), { mode: this.entity.meta.mode })\n\n break\n }\n case \"artifact\": {\n const artifactPath = process.env.HIGHSTATE_ARTIFACT_READ_PATH\n if (!artifactPath) {\n throw new Error(\n \"HIGHSTATE_ARTIFACT_READ_PATH environment variable is not set but required for artifact content\",\n )\n }\n\n const tgzPath = join(artifactPath, `${this.entity.content.hash}.tgz`)\n\n // extract the tgz file directly to the target path\n const readStream = createReadStream(tgzPath)\n await unarchiveFromStream(readStream, dirname(this._path), \"tar\")\n break\n }\n }\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n if (this._disposed) return\n this._disposed = true\n\n try {\n if (this._tmpPath) {\n // clear the whole temporary directory if it was created\n await rm(this._tmpPath, { recursive: true, force: true })\n } else {\n // otherwise, just remove the file\n await rm(this._path, { force: true })\n }\n } catch (error) {\n // ignore errors during cleanup, as the file might have been already removed\n // or the temporary directory might not exist\n // TODO: centralized logging for unit code\n console.warn(\"failed to clean up materialized file:\", error)\n }\n }\n\n /**\n * Packs the materialized file into an artifact and returns the file entity with artifact content.\n *\n * Creates a tgz archive of the file and stores it in HIGHSTATE_ARTIFACT_WRITE_PATH where it will be collected by Highstate.\n */\n async pack(): Promise<File> {\n const writeDir = process.env.HIGHSTATE_ARTIFACT_WRITE_PATH\n if (!writeDir) {\n throw new Error(\"HIGHSTATE_ARTIFACT_WRITE_PATH environment variable is not set\")\n }\n\n // read actual file stats from filesystem\n const fileStats = await stat(this._path)\n\n // create tgz archive of the file\n const tempBase = process.env.HIGHSTATE_TEMP_PATH || tmpdir()\n const tempArchivePath = join(tempBase, `highstate-pack-${Date.now()}.tgz`)\n\n try {\n await tar.create(\n {\n gzip: true,\n file: tempArchivePath,\n cwd: dirname(this._path),\n noMtime: true, // to reproduce the same archive every time\n },\n [basename(this._path)],\n )\n\n // calculate hash of the archive\n const fileContent = createReadStream(tempArchivePath)\n const hash = createHash(\"sha256\")\n\n for await (const chunk of fileContent) {\n hash.update(chunk as Buffer)\n }\n\n const hashValue = hash.digest(\"hex\")\n\n // move archive to write directory with hash name\n const finalArchivePath = join(writeDir, `${hashValue}.tgz`)\n await rename(tempArchivePath, finalArchivePath)\n\n const newMeta = {\n name: this.entity.meta.name,\n mode: fileStats.mode & 0o777, // extract only permission bits\n size: fileStats.size,\n }\n\n // return file entity with artifact content using actual filesystem stats\n return {\n meta: newMeta,\n content: {\n type: \"artifact\",\n [HighstateSignature.Artifact]: true,\n hash: hashValue,\n meta: await toPromise(this.artifactMeta),\n },\n }\n } finally {\n // clean up temporary archive\n try {\n await rm(tempArchivePath, { force: true })\n } catch {\n // ignore cleanup errors\n }\n }\n }\n\n /**\n * Creates an empty materialized file with the given name.\n *\n * @param name The name of the file to create\n * @param content Optional initial content of the file (default is empty string)\n * @param mode Optional file mode (permissions)\n * @returns A new MaterializedFile instance representing an empty file\n */\n static async create(name: string, content = \"\", mode?: number): Promise<MaterializedFile> {\n const entity: common.File = {\n meta: {\n name,\n mode,\n size: 0,\n },\n content: {\n type: \"embedded\",\n value: content,\n },\n }\n\n const materializedFile = new MaterializedFile(entity)\n\n try {\n await materializedFile._open()\n } catch (error) {\n await materializedFile[Symbol.asyncDispose]()\n throw error\n }\n\n return materializedFile\n }\n\n static async open(file: common.File, parent?: MaterializedFolder): Promise<MaterializedFile> {\n const materializedFile = new MaterializedFile(file, parent)\n\n try {\n await materializedFile._open()\n } catch (error) {\n await materializedFile[Symbol.asyncDispose]()\n throw error\n }\n\n return materializedFile\n }\n}\n\n/**\n * The `MaterializedFolder` class represents a folder entity that has been materialized\n * to a local filesystem path.\n *\n * It handles creating a temporary directory, copying the folder content to that directory,\n * and cleaning up the temporary files when disposed.\n *\n * For improved cleanup reliability, the class will use HIGHSTATE_TEMP_PATH as the base\n * directory for temporary files if available, allowing for centralized cleanup by the runner.\n */\nexport class MaterializedFolder implements AsyncDisposable {\n private _tmpPath?: string\n private _path!: string\n private _disposed = false\n\n private readonly _disposables: AsyncDisposable[] = []\n\n readonly artifactMeta: CommonObjectMeta\n\n constructor(\n readonly entity: common.Folder,\n readonly parent?: MaterializedFolder,\n ) {\n this.artifactMeta = {\n title: `Materialized folder \"${entity.meta.name}\"`,\n }\n }\n\n get path(): string {\n return this._path\n }\n\n private async _open(): Promise<void> {\n if (this.parent) {\n // if the parent folder is provided, the folder path is relative to the parent folder\n this._path = join(this.parent.path, this.entity.meta.name)\n } else {\n // otherwise, the folder path is in a temporary directory\n // use HIGHSTATE_TEMP_PATH as base if available for better cleanup reliability\n const tempBase = process.env.HIGHSTATE_TEMP_PATH || tmpdir()\n this._tmpPath = await mkdtemp(join(tempBase, \"highstate-folder-\"))\n this._path = join(this._tmpPath, this.entity.meta.name)\n }\n\n switch (this.entity.content.type) {\n case \"embedded\": {\n // create the folder itself\n await mkdir(this._path, { mode: this.entity.meta.mode })\n\n for (const file of this.entity.content.files) {\n const materializedFile = await MaterializedFile.open(file, this)\n this._disposables.push(materializedFile)\n }\n\n for (const subfolder of this.entity.content.folders) {\n const materializedFolder = await MaterializedFolder.open(subfolder, this)\n this._disposables.push(materializedFolder)\n }\n\n break\n }\n case \"local\": {\n // Check if the local path is an archive file that needs extraction\n const archiveType = detectArchiveType(this.entity.content.path)\n\n if (archiveType) {\n // Extract archive to the destination path\n const readStream = createReadStream(this.entity.content.path)\n await unarchiveFromStream(readStream, this._path, archiveType)\n } else {\n // Regular directory copy\n await cp(this.entity.content.path, this._path, {\n recursive: true,\n mode: this.entity.meta.mode,\n })\n }\n\n break\n }\n case \"remote\": {\n const response = await fetch(l7EndpointToString(this.entity.content.endpoint))\n if (!response.ok) throw new Error(`Failed to fetch: ${response.statusText}`)\n if (!response.body) throw new Error(\"Response body is empty\")\n\n // Try to detect archive type from URL or content type\n const url = new URL(l7EndpointToString(this.entity.content.endpoint))\n const archiveType = detectArchiveType(\n url.pathname,\n response.headers.get(\"content-type\") || undefined,\n )\n\n if (!archiveType) {\n throw new Error(\"Remote folder content must be an archive (tar, tar.gz, tgz, or zip)\")\n }\n\n if (!response.body) {\n throw new Error(\"Response body is empty\")\n }\n\n const reader = response.body.getReader()\n const stream = new Readable({\n async read() {\n try {\n const { done, value } = await reader.read()\n if (done) {\n this.push(null)\n } else {\n this.push(Buffer.from(value))\n }\n } catch (error) {\n this.destroy(error instanceof Error ? error : new Error(String(error)))\n }\n },\n })\n\n await unarchiveFromStream(stream, this._path, archiveType)\n\n break\n }\n case \"artifact\": {\n const artifactPath = process.env.HIGHSTATE_ARTIFACT_READ_PATH\n\n if (!artifactPath) {\n throw new Error(\n \"HIGHSTATE_ARTIFACT_READ_PATH environment variable is not set but required for artifact content\",\n )\n }\n\n const tgzPath = join(artifactPath, `${this.entity.content.hash}.tgz`)\n\n // extract the tgz file directly to the target path\n const readStream = createReadStream(tgzPath)\n await unarchiveFromStream(readStream, dirname(this._path), \"tar\")\n\n break\n }\n }\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n if (this._disposed) return\n this._disposed = true\n\n try {\n if (this._tmpPath) {\n // clear the whole temporary directory if it was created\n await rm(this._tmpPath, { recursive: true, force: true })\n } else {\n // otherwise, just remove the folder\n await rm(this._path, { recursive: true, force: true })\n }\n } catch (error) {\n // ignore errors during cleanup, as the folder might have been already removed\n // or the temporary directory might not exist\n // TODO: centralized logging for unit code\n console.warn(\"failed to clean up materialized folder:\", error)\n }\n\n // dispose all materialized children\n for (const disposable of this._disposables) {\n await disposable[Symbol.asyncDispose]()\n }\n }\n\n /**\n * Packs the materialized folder into an artifact and returns the folder entity with artifact content.\n *\n * Creates a tgz archive of the entire folder and stores it in HIGHSTATE_ARTIFACT_WRITE_PATH where it will be collected by Highstate.\n */\n async pack({ include, exclude }: FolderPackOptions = {}): Promise<common.Folder> {\n const writeDir = process.env.HIGHSTATE_ARTIFACT_WRITE_PATH\n if (!writeDir) {\n throw new Error(\"HIGHSTATE_ARTIFACT_WRITE_PATH environment variable is not set\")\n }\n\n // read actual folder stats from filesystem\n const folderStats = await stat(this._path)\n\n // create tgz archive of the folder\n const tempBase = process.env.HIGHSTATE_TEMP_PATH || tmpdir()\n const tempArchivePath = join(tempBase, `highstate-pack-${Date.now()}.tgz`)\n\n const entity = this.entity\n\n try {\n await tar.create(\n {\n gzip: true,\n file: tempArchivePath,\n cwd: dirname(this._path),\n\n filter(path) {\n // match without the folder name prefix\n path = path.slice(entity.meta.name.length + 1)\n\n // handle explicit excludes\n for (const pattern of exclude ?? []) {\n if (minimatch(path, pattern)) {\n return false\n }\n }\n\n // try to match include patterns\n for (const pattern of include ?? []) {\n if (minimatch(path, pattern)) {\n return true\n }\n }\n\n // include all files if no include patterns are specified\n return !include || include.length === 0\n },\n\n // to reproduce the same archive every time\n portable: true,\n noMtime: true,\n },\n [basename(this._path)],\n )\n\n // calculate hash of the archive\n const fileContent = createReadStream(tempArchivePath)\n const hash = createHash(\"sha256\")\n\n for await (const chunk of fileContent) {\n hash.update(chunk as Buffer)\n }\n\n const hashValue = hash.digest(\"hex\")\n\n // move archive to write directory with hash name\n const finalArchivePath = join(writeDir, `${hashValue}.tgz`)\n await rename(tempArchivePath, finalArchivePath)\n\n const newMeta = {\n name: this.entity.meta.name,\n mode: folderStats.mode & 0o777, // extract only permission bits\n }\n\n // return folder entity with artifact content using actual filesystem stats\n return {\n meta: newMeta,\n content: {\n [HighstateSignature.Artifact]: true,\n type: \"artifact\",\n hash: hashValue,\n meta: await toPromise(this.artifactMeta),\n },\n }\n } finally {\n // clean up temporary archive\n try {\n await rm(tempArchivePath, { force: true })\n } catch {\n // ignore cleanup errors\n }\n }\n }\n\n /**\n * Creates an empty materialized folder with the given name.\n *\n * @param name The name of the folder to create\n * @param mode Optional folder mode (permissions)\n * @param parent Optional parent folder to create the folder in\n * @returns A new MaterializedFolder instance representing an empty folder\n */\n static async create(\n name: string,\n mode?: number,\n parent?: MaterializedFolder,\n ): Promise<MaterializedFolder> {\n const entity: common.Folder = {\n meta: {\n name,\n mode,\n },\n content: {\n type: \"embedded\",\n files: [],\n folders: [],\n },\n }\n\n const materializedFolder = new MaterializedFolder(entity, parent)\n\n try {\n await materializedFolder._open()\n } catch (error) {\n await materializedFolder[Symbol.asyncDispose]()\n throw error\n }\n\n return materializedFolder\n }\n\n static async open(\n folder: common.Folder,\n parent?: MaterializedFolder,\n ): Promise<MaterializedFolder> {\n const materializedFolder = new MaterializedFolder(folder, parent)\n\n try {\n await materializedFolder._open()\n } catch (error) {\n await materializedFolder[Symbol.asyncDispose]()\n throw error\n }\n\n return materializedFolder\n }\n}\n\n/**\n * Fetches the size of a file from a given L7 endpoint.\n *\n * @param endpoint The L7 endpoint to fetch the file size from.\n * @returns The size of the file in bytes.\n * @throws If the protocol is not HTTP/HTTPS or if the request fails.\n */\nexport async function fetchFileSize(endpoint: network.L7Endpoint): Promise<number> {\n if (endpoint.appProtocol !== \"http\" && endpoint.appProtocol !== \"https\") {\n throw new Error(\n `Unsupported protocol: ${endpoint.appProtocol}. Only HTTP and HTTPS are supported.`,\n )\n }\n\n const url = l7EndpointToString(endpoint)\n const response = await fetch(url, { method: \"HEAD\" })\n\n if (!response.ok) {\n throw new Error(`Failed to fetch file size: ${response.statusText}`)\n }\n\n const contentLength = response.headers.get(\"content-length\")\n if (!contentLength) {\n throw new Error(\"Content-Length header is missing in the response\")\n }\n\n const size = parseInt(contentLength, 10)\n if (Number.isNaN(size)) {\n throw new Error(`Invalid Content-Length value: ${contentLength}`)\n }\n\n return size\n}\n\n/**\n * Extracts the name from an L7 endpoint URL without its file extension.\n */\nexport function getNameByEndpoint(endpoint: InputL7Endpoint): string {\n const parsedEndpoint = parseL7Endpoint(endpoint)\n\n return parsedEndpoint.resource ? basename(parsedEndpoint.resource) : \"\"\n}\n","import { bytesToHex, randomBytes } from \"@noble/hashes/utils\"\nimport { secureMask } from \"micro-key-producer/password.js\"\n\n/**\n * Generates a secure random password strong enough for online use.\n *\n * It uses \"Safari Keychain Secure Password\" format.\n *\n * The approximate entropy is [71 bits](https://support.apple.com/guide/security/automatic-strong-passwords-secc84c811c4/web).\n */\nexport function generatePassword(): string {\n return secureMask.apply(randomBytes(32)).password\n}\n\ntype KeyFormatMap = {\n raw: Uint8Array\n hex: string\n base64: string\n}\n\n/**\n * Generates a secure random key strong enough for offline use such as encryption.\n *\n * The strong entropy is 256 bits.\n *\n * @param format The format of the generated key. By default, it is \"hex\".\n */\nexport function generateKey<TFormat extends keyof KeyFormatMap = \"hex\">(\n format: TFormat = \"hex\" as TFormat,\n): KeyFormatMap[TFormat] {\n const bytes = randomBytes(32)\n\n if (format === \"raw\") {\n return bytes as KeyFormatMap[TFormat]\n }\n\n if (format === \"base64\") {\n return Buffer.from(bytes).toString(\"base64\") as KeyFormatMap[TFormat]\n }\n\n return bytesToHex(bytes) as KeyFormatMap[TFormat]\n}\n","{\n \"terminal-ssh\": {\n \"name\": \"ghcr.io/exeteres/highstate/terminal-ssh\",\n \"tag\": \"latest\",\n \"image\": \"ghcr.io/exeteres/highstate/terminal-ssh:latest@sha256:99380e0405522afa0058eedce124c1970a87408663365b2dbce737801a7cd5d1\"\n }\n}\n","import type { common, network, ssh } from \"@highstate/library\"\nimport { stripNullish, type UnitTerminal } from \"@highstate/contract\"\nimport {\n fileFromString,\n type Input,\n type Output,\n output,\n secret,\n toPromise,\n} from \"@highstate/pulumi\"\nimport { remote } from \"@pulumi/command\"\nimport getKeys, { PrivateExport } from \"micro-key-producer/ssh.js\"\nimport { randomBytes } from \"micro-key-producer/utils.js\"\nimport * as images from \"../../assets/images.json\"\nimport { Command } from \"./command\"\nimport { l3EndpointToL4, l3EndpointToString } from \"./network\"\n\nexport async function createSshTerminal(\n credentials: Input<ssh.Connection>,\n): Promise<Output<UnitTerminal>> {\n const resolvedCredentials = await toPromise(credentials)\n\n const command = [\"ssh\", \"-tt\", \"-o\", \"UserKnownHostsFile=/known_hosts\"]\n\n // TODO: select best endpoint based on the environment\n const endpoint = resolvedCredentials.endpoints[0]\n\n command.push(\"-p\", endpoint.port.toString())\n\n if (resolvedCredentials.keyPair) {\n command.push(\"-i\", \"/private_key\")\n }\n\n command.push(`${resolvedCredentials.user}@${l3EndpointToString(endpoint)}`)\n\n if (resolvedCredentials.password) {\n command.unshift(\"sshpass\", \"-f\", \"/password\")\n }\n\n return output({\n name: \"ssh\",\n\n meta: {\n title: \"Shell\",\n description: \"Connect to the server via SSH.\",\n icon: \"gg:remote\",\n },\n\n spec: {\n image: images[\"terminal-ssh\"].image,\n command,\n\n files: stripNullish({\n \"/password\": resolvedCredentials.password\n ? fileFromString(\"password\", resolvedCredentials.password, { isSecret: true })\n : undefined,\n\n \"/private_key\": resolvedCredentials.keyPair?.privateKey\n ? fileFromString(\"private_key\", resolvedCredentials.keyPair.privateKey, {\n isSecret: true,\n mode: 0o600,\n })\n : undefined,\n\n \"/known_hosts\": fileFromString(\n \"known_hosts\",\n `${l3EndpointToString(endpoint)} ${resolvedCredentials.hostKey}`,\n { mode: 0o644 },\n ),\n }),\n },\n })\n}\n\n/**\n * Generates a secure random SSH private key.\n * The key is generated using the Ed25519 algorithm.\n *\n * @returns The generated SSH private key in PEM format.\n */\nexport function generateSshPrivateKey(): Output<string> {\n const seed = randomBytes(32)\n\n return secret(getKeys(seed).privateKey)\n}\n\n/**\n * Converts a private SSH key string to a KeyPair object.\n *\n * @param privateKeyString The private key string to convert.\n * @returns An Output of the KeyPair object.\n */\nexport function sshPrivateKeyToKeyPair(privateKeyString: Input<string>): Output<ssh.KeyPair> {\n return output(privateKeyString).apply(privateKeyString => {\n const privateKeyStruct = PrivateExport.decode(privateKeyString)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const privKey = privateKeyStruct.keys[0].privKey.privKey as Uint8Array\n\n const { fingerprint, publicKey } = getKeys(privKey.slice(0, 32))\n\n return output({\n type: \"ed25519\" as const,\n fingerprint,\n publicKey,\n privateKey: secret(privateKeyString),\n })\n })\n}\n\nexport type ServerOptions = {\n /**\n * The local name of the server to namespace resources.\n */\n name: string\n\n /**\n * The fallback hostname to use if the server cannot be determined.\n *\n * If not provided, the `name` will be used as the fallback hostname.\n */\n fallbackHostname?: string\n\n /**\n * The L3 endpoints of the server.\n */\n endpoints: network.L3Endpoint[]\n\n /**\n * The arguments for the SSH connection.\n */\n sshArgs?: Partial<ssh.Args>\n\n /**\n * The password for the SSH connection.\n */\n sshPassword?: Input<string>\n\n /**\n * The private key for the SSH connection.\n */\n sshPrivateKey?: Input<string>\n\n /**\n * The SSH key pair for the server.\n * If provided, it will take precedence over the `sshPrivateKey` argument.\n */\n sshKeyPair?: Input<ssh.KeyPair>\n\n /**\n * Whether to wait for the server to respond to a ping command before returning.\n *\n * If true, the command will wait for a successful ping response before proceeding.\n *\n * By default, this is equal to `!waitForSsh`, so when `waitForSsh` is true, no extra ping is performed.\n */\n waitForPing?: boolean\n\n /**\n * The interval in seconds to wait between ping attempts.\n *\n * Only used if `waitForPing` is true.\n * By default, it will wait 5 seconds between attempts.\n */\n pingInterval?: number\n\n /**\n * The timeout in seconds to wait for the server to respond to a ping command.\n *\n * Only used if `waitForPing` is true.\n * By default, it will wait 5 minutes (300 seconds) before timing out.\n */\n pingTimeout?: number\n\n /**\n * Whether to wait for the SSH service to be available before returning.\n *\n * If true, the command will wait for the SSH service to respond before proceeding.\n *\n * By default, this is true if `sshArgs.enabled` is true, otherwise false.\n */\n waitForSsh?: boolean\n\n /**\n * The interval in seconds to wait between SSH connection attempts.\n *\n * Only used if `waitForSsh` is true.\n * By default, it will wait 5 seconds between attempts.\n */\n sshCheckInterval?: number\n\n /**\n * The timeout in seconds to wait for the SSH service to respond.\n *\n * Only used if `waitForSsh` is true.\n * By default, it will wait 5 minutes (300 seconds) before timing out.\n */\n sshCheckTimeout?: number\n}\n\nexport type ServerBundle = {\n /**\n * The server entity created with the provided options.\n */\n server: Output<common.Server>\n\n /**\n * The SSH terminal created for the server.\n */\n terminal?: Output<UnitTerminal>\n}\n\n/**\n * Creates a server entity with the provided options and returns a bundle containing the server entity and terminal.\n *\n * Basically, it just a convenience function that calls `createServerEntity` and `createSshTerminal`.\n *\n * @param options The options for creating the server entity.\n * @returns A promise that resolves to a ServerBundle containing the server entity and terminal.\n */\nexport async function createServerBundle(options: ServerOptions): Promise<ServerBundle> {\n const server = await createServerEntity(options)\n const ssh = await toPromise(server.ssh)\n\n return {\n server,\n terminal: ssh ? await createSshTerminal(ssh) : undefined,\n }\n}\n\n/**\n * Creates a server entity with the provided options.\n * It will create a command to check the SSH service and return the server entity.\n *\n * @param options The options for creating the server entity.\n * @returns A promise that resolves to the created server entity.\n */\nexport async function createServerEntity({\n name,\n fallbackHostname,\n endpoints,\n sshArgs = { enabled: true, port: 22, user: \"root\" },\n sshPassword,\n sshPrivateKey,\n sshKeyPair,\n pingInterval,\n pingTimeout,\n waitForPing,\n waitForSsh,\n sshCheckInterval,\n sshCheckTimeout,\n}: ServerOptions): Promise<Output<common.Server>> {\n if (endpoints.length === 0) {\n throw new Error(\"At least one L3 endpoint is required to create a server entity\")\n }\n\n fallbackHostname ??= name\n waitForSsh ??= sshArgs.enabled\n waitForPing ??= !waitForSsh\n\n if (waitForPing) {\n await Command.waitFor(`${name}.ping`, {\n host: \"local\",\n create: `ping -c 1 ${l3EndpointToString(endpoints[0])}`,\n timeout: pingTimeout ?? 300,\n interval: pingInterval ?? 5,\n triggers: [Date.now()],\n }).wait()\n }\n\n if (!sshArgs.enabled) {\n return output({\n hostname: name,\n endpoints,\n })\n }\n\n const sshHost = sshArgs?.host ?? l3EndpointToString(endpoints[0])\n\n if (waitForSsh) {\n await Command.waitFor(`${name}.ssh`, {\n host: \"local\",\n create: `nc -zv ${sshHost} ${sshArgs.port}`,\n timeout: sshCheckTimeout ?? 300,\n interval: sshCheckInterval ?? 5,\n triggers: [Date.now()],\n }).wait()\n }\n\n const connection = output({\n host: sshHost,\n port: sshArgs.port,\n user: sshArgs.user,\n password: sshPassword,\n privateKey: sshKeyPair ? output(sshKeyPair).privateKey : sshPrivateKey,\n dialErrorLimit: 3,\n })\n\n const hostnameResult = new remote.Command(\"hostname\", {\n connection,\n create: \"hostname\",\n triggers: [Date.now()],\n })\n\n const hostKeyResult = new remote.Command(\"host-key\", {\n connection,\n create: \"cat /etc/ssh/ssh_host_ed25519_key.pub\",\n triggers: [Date.now()],\n })\n\n return output({\n endpoints,\n hostname: hostnameResult.stdout.apply(x => x.trim()),\n ssh: {\n endpoints: [l3EndpointToL4(sshHost, sshArgs.port ?? 22)],\n user: sshArgs.user ?? \"root\",\n hostKey: hostKeyResult.stdout.apply(x => x.trim()),\n password: connection.password,\n keyPair: sshKeyPair\n ? sshKeyPair\n : sshPrivateKey\n ? sshPrivateKeyToKeyPair(sshPrivateKey)\n : undefined,\n },\n })\n}\n"]}