@restatedev/restate-sdk 1.18.0 → 1.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/common_api.d.cts.map +1 -1
  2. package/dist/common_api.d.ts.map +1 -1
  3. package/dist/context.d.cts +3 -0
  4. package/dist/context.d.cts.map +1 -1
  5. package/dist/context.d.ts +3 -0
  6. package/dist/context.d.ts.map +1 -1
  7. package/dist/context.js.map +1 -1
  8. package/dist/context_impl.cjs +8 -3
  9. package/dist/context_impl.js +8 -3
  10. package/dist/context_impl.js.map +1 -1
  11. package/dist/endpoint/connect/env.cjs +208 -0
  12. package/dist/endpoint/connect/env.js +201 -0
  13. package/dist/endpoint/connect/env.js.map +1 -0
  14. package/dist/endpoint/connect/index.cjs +113 -0
  15. package/dist/endpoint/connect/index.d.cts +41 -0
  16. package/dist/endpoint/connect/index.d.cts.map +1 -0
  17. package/dist/endpoint/connect/index.d.ts +41 -0
  18. package/dist/endpoint/connect/index.d.ts.map +1 -0
  19. package/dist/endpoint/connect/index.js +114 -0
  20. package/dist/endpoint/connect/index.js.map +1 -0
  21. package/dist/endpoint/connect/key.cjs +62 -0
  22. package/dist/endpoint/connect/key.js +62 -0
  23. package/dist/endpoint/connect/key.js.map +1 -0
  24. package/dist/endpoint/tunnel/backoff.cjs +37 -0
  25. package/dist/endpoint/tunnel/backoff.js +36 -0
  26. package/dist/endpoint/tunnel/backoff.js.map +1 -0
  27. package/dist/endpoint/tunnel/connection.cjs +604 -0
  28. package/dist/endpoint/tunnel/connection.js +600 -0
  29. package/dist/endpoint/tunnel/connection.js.map +1 -0
  30. package/dist/endpoint/tunnel/draining.cjs +40 -0
  31. package/dist/endpoint/tunnel/draining.js +40 -0
  32. package/dist/endpoint/tunnel/draining.js.map +1 -0
  33. package/dist/endpoint/tunnel/engine.cjs +264 -0
  34. package/dist/endpoint/tunnel/engine.d.cts +1 -0
  35. package/dist/endpoint/tunnel/engine.d.ts +1 -0
  36. package/dist/endpoint/tunnel/engine.js +265 -0
  37. package/dist/endpoint/tunnel/engine.js.map +1 -0
  38. package/dist/endpoint/tunnel/forwarded.cjs +34 -0
  39. package/dist/endpoint/tunnel/forwarded.js +34 -0
  40. package/dist/endpoint/tunnel/forwarded.js.map +1 -0
  41. package/dist/endpoint/tunnel/handshake.cjs +98 -0
  42. package/dist/endpoint/tunnel/handshake.js +97 -0
  43. package/dist/endpoint/tunnel/handshake.js.map +1 -0
  44. package/dist/endpoint/tunnel/index.d.cts +3 -0
  45. package/dist/endpoint/tunnel/index.d.ts +3 -0
  46. package/dist/endpoint/tunnel/options.cjs +168 -0
  47. package/dist/endpoint/tunnel/options.d.cts +2 -0
  48. package/dist/endpoint/tunnel/options.d.ts +2 -0
  49. package/dist/endpoint/tunnel/options.js +161 -0
  50. package/dist/endpoint/tunnel/options.js.map +1 -0
  51. package/dist/endpoint/tunnel/supervisor.cjs +180 -0
  52. package/dist/endpoint/tunnel/supervisor.js +181 -0
  53. package/dist/endpoint/tunnel/supervisor.js.map +1 -0
  54. package/dist/endpoint/tunnel/targets.cjs +110 -0
  55. package/dist/endpoint/tunnel/targets.js +107 -0
  56. package/dist/endpoint/tunnel/targets.js.map +1 -0
  57. package/dist/endpoint/tunnel/types.d.cts +269 -0
  58. package/dist/endpoint/tunnel/types.d.cts.map +1 -0
  59. package/dist/endpoint/tunnel/types.d.ts +269 -0
  60. package/dist/endpoint/tunnel/types.d.ts.map +1 -0
  61. package/dist/endpoint/tunnel/util.cjs +67 -0
  62. package/dist/endpoint/tunnel/util.js +65 -0
  63. package/dist/endpoint/tunnel/util.js.map +1 -0
  64. package/dist/index.cjs +2 -0
  65. package/dist/index.d.cts +3 -1
  66. package/dist/index.d.ts +3 -1
  67. package/dist/index.js +2 -1
  68. package/dist/node.cjs +2 -0
  69. package/dist/node.d.cts +4 -1
  70. package/dist/node.d.cts.map +1 -1
  71. package/dist/node.d.ts +4 -1
  72. package/dist/node.d.ts.map +1 -1
  73. package/dist/node.js +2 -1
  74. package/dist/node.js.map +1 -1
  75. package/dist/package.cjs +1 -1
  76. package/dist/package.js +1 -1
  77. package/dist/package.js.map +1 -1
  78. package/dist/types/rpc.d.ts.map +1 -1
  79. package/package.json +2 -2
@@ -0,0 +1,201 @@
1
+ import { requireHeaderSafe, srvNameForRegionDomain } from "../tunnel/options.js";
2
+ import { parseCloudKey } from "./key.js";
3
+ import * as fs from "node:fs";
4
+
5
+ //#region src/endpoint/connect/env.ts
6
+ /** The Cloud UI, for the deep links below. */
7
+ const CLOUD_UI_URL = "https://cloud.restate.dev";
8
+ /** Where to get a connect key (Development → Configure SDK), linked in every error. */
9
+ const CONNECT_KEY_URL = `${CLOUD_UI_URL}/to/developers/integration#configure-sdk`;
10
+ /** The deployment name, in resolution order. */
11
+ const CONNECT_NAME_ENVS = [
12
+ "RESTATE_CONNECT_NAME",
13
+ "RESTATE_INPROC_TUNNEL_NAME",
14
+ "RESTATE_TUNNEL_NAME"
15
+ ];
16
+ /** The connect key. */
17
+ const CONNECT_KEY_ENV = "RESTATE_CONNECT_KEY";
18
+ const ENVIRONMENT_ID_ENVS = ["RESTATE_ENVIRONMENT_ID", "RESTATE_INPROC_ENVIRONMENT_ID"];
19
+ const AUTH_TOKEN_ENVS = ["RESTATE_AUTH_TOKEN"];
20
+ /** A file holding the token, re-read on every reconnect (a mounted Secret). */
21
+ const AUTH_TOKEN_FILE_ENVS = ["RESTATE_INPROC_AUTH_TOKEN_FILE"];
22
+ const CLOUD_REGION_ENVS = ["RESTATE_CLOUD_REGION", "RESTATE_INPROC_CLOUD_REGION"];
23
+ const TUNNEL_SERVERS_SRV_ENVS = ["RESTATE_TUNNEL_SERVERS_SRV"];
24
+ const TUNNEL_SERVERS_ENVS = ["RESTATE_TUNNEL_SERVERS"];
25
+ const SIGNING_PUBLIC_KEY_ENVS = ["RESTATE_SIGNING_PUBLIC_KEY", "RESTATE_INPROC_SIGNING_PUBLIC_KEY"];
26
+ /** The query parameters a connect key may carry; anything else is ignored with a warning. */
27
+ const KNOWN_KEY_PARAMS = [
28
+ "envid",
29
+ "apikey",
30
+ "region",
31
+ "signingkey"
32
+ ];
33
+ /** A region domain: lowercase labels of [a-z0-9-], dot-separated, none empty. */
34
+ const REGION_DOMAIN = /^[a-z0-9-]+(\.[a-z0-9-]+)*$/;
35
+ /** An env var set to the empty string is treated as unset. */
36
+ function readEnv(name) {
37
+ const value = process.env[name];
38
+ return value === void 0 || value === "" ? void 0 : value;
39
+ }
40
+ /** The first set variable among `names`, with its name. */
41
+ function readFirstEnv(names) {
42
+ for (const name of names) {
43
+ const value = readEnv(name);
44
+ if (value !== void 0) return {
45
+ value,
46
+ name
47
+ };
48
+ }
49
+ }
50
+ function given(value) {
51
+ return value !== void 0 && value !== "";
52
+ }
53
+ /**
54
+ * The deployment name: option → `RESTATE_CONNECT_NAME` →
55
+ * `RESTATE_INPROC_TUNNEL_NAME` → `RESTATE_TUNNEL_NAME` → error. No inference:
56
+ * an unnamed deployment is a mistake, and the error says what to set.
57
+ */
58
+ function resolveName(option) {
59
+ const name = given(option) ? option : readFirstEnv(CONNECT_NAME_ENVS)?.value;
60
+ if (name === void 0) throw new Error(`connect(): the deployment needs a name — pass { name: "greeter-v1" } or set ${CONNECT_NAME_ENVS[0]}. Replicas of one deployment share the name; it is what you register (connect://<name>).`);
61
+ if (!/^[A-Za-z0-9._-]+$/.test(name)) throw new Error(`connect(): invalid deployment name ${JSON.stringify(name)} — use letters, digits, '.', '_' or '-'`);
62
+ return name;
63
+ }
64
+ /**
65
+ * The coordinates for `connect()`: `key` option → `RESTATE_CONNECT_KEY` →
66
+ * the expanded variables → error naming the variable and the Cloud UI page.
67
+ * Explicit `identityKeys` and discovery options win over the key's.
68
+ */
69
+ function resolveCoordinates(options, warn) {
70
+ if (given(options.key)) return coordinatesFromKey(parseCloudKey(options.key, "the `key` option", CONNECT_KEY_URL), options, warn);
71
+ const fromEnv = readEnv(CONNECT_KEY_ENV);
72
+ if (fromEnv !== void 0) return coordinatesFromKey(parseCloudKey(fromEnv, CONNECT_KEY_ENV, CONNECT_KEY_URL), options, warn);
73
+ if (readFirstEnv(ENVIRONMENT_ID_ENVS) === void 0) throw new Error(`connect(): no Restate Cloud connect key — set ${CONNECT_KEY_ENV} (create one at ${CONNECT_KEY_URL}) or pass { key }`);
74
+ return coordinatesFromExpanded(options);
75
+ }
76
+ function coordinatesFromKey(key, options, warn) {
77
+ const params = /* @__PURE__ */ new Map();
78
+ const unknown = [];
79
+ for (const [name, value] of key) if (!KNOWN_KEY_PARAMS.includes(name)) unknown.push(name);
80
+ else if (params.has(name)) fail(`the connect key is malformed — copy it again from ${CONNECT_KEY_URL}`);
81
+ else params.set(name, value);
82
+ if (unknown.length > 0) warn(`connect(): the connect key carries data this SDK version does not understand (${unknown.map((n) => JSON.stringify(n)).join(", ")}); ignoring it — a newer SDK may need it`);
83
+ const incomplete = () => fail(`the connect key is incomplete — copy it again from ${CONNECT_KEY_URL}`);
84
+ const malformed = () => fail(`the connect key is malformed — copy it again from ${CONNECT_KEY_URL}`);
85
+ const environmentId = params.get("envid") ?? incomplete();
86
+ if (!/^env_[A-Za-z0-9_-]+$/.test(environmentId)) malformed();
87
+ const injected = readFirstEnv(ENVIRONMENT_ID_ENVS);
88
+ if (injected !== void 0 && injected.value !== environmentId) warn(`connect(): the connect key is for environment ${environmentId} but ${injected.name} is set to ${injected.value}; the key wins`);
89
+ const identityKeys = resolveIdentityKeys(options.identityKeys, params.get("signingkey"), `the connect key carries no signing key and no identityKeys were given — this is an ingress key or an incomplete paste; copy a connect key from ${CONNECT_KEY_URL}`);
90
+ const apiKey = params.get("apikey");
91
+ const authToken = apiKey !== void 0 && apiKey !== "" ? constantToken(apiKey, "the connect key's API key") : tokenFromEnv() ?? fail(`the connect key carries no API key and no token is configured in ${AUTH_TOKEN_ENVS[0]} or a file in ${AUTH_TOKEN_FILE_ENVS[0]}`);
92
+ const regionDomain = params.get("region") ?? incomplete();
93
+ if (!REGION_DOMAIN.test(regionDomain)) malformed();
94
+ const override = pickDiscovery(options);
95
+ const discovery = override ?? { srvName: srvNameForRegionDomain(regionDomain) };
96
+ return {
97
+ environmentId,
98
+ authToken,
99
+ identityKeys,
100
+ discovery,
101
+ regionLabel: override === void 0 ? regionDomain : discoveryLabel(discovery)
102
+ };
103
+ }
104
+ /**
105
+ * The coordinates from the expanded variables (`RESTATE_<X>`, then
106
+ * `RESTATE_INPROC_<X>`), each missing piece an error naming its variable.
107
+ * Explicit `identityKeys` and discovery options win over the environment.
108
+ */
109
+ function coordinatesFromExpanded(o) {
110
+ const environmentId = requireHeaderSafe(readFirstEnv(ENVIRONMENT_ID_ENVS)?.value ?? fail(`environmentId is required — set ${ENVIRONMENT_ID_ENVS[0]} (or ${CONNECT_KEY_ENV} from ${CONNECT_KEY_URL})`), "environmentId");
111
+ if (!/^env_[A-Za-z0-9_-]+$/.test(environmentId)) throw new Error(`connect(): environmentId must be \`env_\` followed by alphanumerics (e.g. env_201k0yd4...), got ${JSON.stringify(environmentId)}`);
112
+ const authToken = tokenFromEnv() ?? fail(`authToken is required — set ${AUTH_TOKEN_ENVS[0]} or a token file in ${AUTH_TOKEN_FILE_ENVS[0]} (or ${CONNECT_KEY_ENV} from ${CONNECT_KEY_URL})`);
113
+ const identityKeys = resolveIdentityKeys(o.identityKeys, readFirstEnv(SIGNING_PUBLIC_KEY_ENVS)?.value, `signingPublicKey is required — set ${SIGNING_PUBLIC_KEY_ENVS[0]} (or ${CONNECT_KEY_ENV} from ${CONNECT_KEY_URL})`);
114
+ let discovery = pickDiscovery(o);
115
+ let regionLabel;
116
+ if (discovery === void 0) {
117
+ const region = readEnv(CLOUD_REGION_ENVS[0]);
118
+ const srv = readFirstEnv(TUNNEL_SERVERS_SRV_ENVS)?.value;
119
+ const servers = readFirstEnv(TUNNEL_SERVERS_ENVS)?.value;
120
+ const inproc = readEnv(CLOUD_REGION_ENVS[1]);
121
+ if (region !== void 0 || srv === void 0 && servers === void 0) {
122
+ const value = region ?? inproc;
123
+ if (value === void 0) throw new Error(`connect(): no Restate Cloud region — set ${CLOUD_REGION_ENVS[0]} (or ${CONNECT_KEY_ENV} from ${CONNECT_KEY_URL})`);
124
+ const domain = regionDomainForRegion(value);
125
+ discovery = { srvName: srvNameForRegionDomain(domain) };
126
+ regionLabel = domain;
127
+ } else if (srv !== void 0) discovery = { srvName: srv };
128
+ else discovery = { servers: splitList(servers) };
129
+ }
130
+ return {
131
+ environmentId,
132
+ authToken,
133
+ identityKeys,
134
+ discovery,
135
+ regionLabel: regionLabel ?? discoveryLabel(discovery)
136
+ };
137
+ }
138
+ function fail(message) {
139
+ throw new Error(`connect(): ${message}`);
140
+ }
141
+ function resolveIdentityKeys(option, signingKey, missing) {
142
+ if (option !== void 0 && option.length > 0) return option;
143
+ if (signingKey === void 0) fail(missing);
144
+ if (!signingKey.startsWith("publickeyv1_")) fail(`the signing key must be a request-identity public key (publickeyv1_...), got ${JSON.stringify(signingKey)}`);
145
+ return [signingKey];
146
+ }
147
+ function constantToken(token, what) {
148
+ requireHeaderSafe(token, what);
149
+ return () => token;
150
+ }
151
+ /** `RESTATE_AUTH_TOKEN`, then the file named by `RESTATE_INPROC_AUTH_TOKEN_FILE`. */
152
+ function tokenFromEnv() {
153
+ const token = readFirstEnv(AUTH_TOKEN_ENVS);
154
+ if (token !== void 0) return constantToken(token.value, token.name);
155
+ const file = readFirstEnv(AUTH_TOKEN_FILE_ENVS);
156
+ if (file === void 0) return void 0;
157
+ const tokenFile = file.value;
158
+ const readToken = () => {
159
+ const stat = fs.statSync(tokenFile);
160
+ if (!stat.isFile()) throw new Error(`connect(): token file ${tokenFile} (${file.name}) is not a regular file`);
161
+ if (stat.size > 64 * 1024) throw new Error(`connect(): token file ${tokenFile} (${file.name}) is implausibly large for a token (${stat.size} bytes)`);
162
+ const token$1 = fs.readFileSync(tokenFile, "utf8").trim();
163
+ if (token$1 === "") throw new Error(`connect(): token file ${tokenFile} (${file.name}) is empty`);
164
+ return requireHeaderSafe(token$1, `token file ${tokenFile}`);
165
+ };
166
+ readToken();
167
+ return readToken;
168
+ }
169
+ function pickDiscovery(o) {
170
+ if (given(o.serversSrv) && o.servers !== void 0) throw new Error("connect(): specify at most one of `serversSrv` and `servers`");
171
+ if (given(o.serversSrv)) return { srvName: o.serversSrv };
172
+ if (o.servers !== void 0) {
173
+ if (o.servers.length === 0) throw new Error("connect(): `servers` must not be empty");
174
+ return { servers: o.servers };
175
+ }
176
+ }
177
+ /** A region (`us`, `eu`, `<slug>.byoc`) is the labels before `.restate.cloud`. */
178
+ function regionDomainForRegion(region) {
179
+ if (!REGION_DOMAIN.test(region)) throw new Error(`connect(): invalid region ${JSON.stringify(region)}`);
180
+ return `${region}.restate.cloud`;
181
+ }
182
+ /** Human-readable discovery target for the banner. */
183
+ function discoveryLabel(discovery) {
184
+ if ("srvName" in discovery) return discovery.srvName.replace(/^tunnel\./, "");
185
+ return discovery.servers.join(",");
186
+ }
187
+ function splitList(value) {
188
+ return value.split(",").map((s) => s.trim()).filter((s) => s !== "");
189
+ }
190
+ /** The registration identifier the CLI and the Cloud UI accept. */
191
+ function registrationIdentifier(name) {
192
+ return `connect://${name}`;
193
+ }
194
+ /** The Cloud UI deep link that opens the register dialog pre-filled. */
195
+ function registrationDeepLink(name) {
196
+ return `${CLOUD_UI_URL}/to/overview?register-deployment=${registrationIdentifier(name)}`;
197
+ }
198
+
199
+ //#endregion
200
+ export { CONNECT_KEY_ENV, CONNECT_KEY_URL, CONNECT_NAME_ENVS, registrationDeepLink, registrationIdentifier, resolveCoordinates, resolveName };
201
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","names":["unknown: string[]","regionLabel: string | undefined","token"],"sources":["../../../src/endpoint/connect/env.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n// Resolving the identity of a connected deployment.\n// =============================================================================\n//\n// Two inputs, read from the options and then the process environment (never a\n// file; the SDK reads `process.env` only):\n//\n// name option → RESTATE_CONNECT_NAME → RESTATE_INPROC_TUNNEL_NAME\n// → RESTATE_TUNNEL_NAME → error\n// key option → RESTATE_CONNECT_KEY → the expanded variables → error\n//\n// The key is one opaque `rstcloudv1_…` string from the Cloud UI (Development →\n// Configure SDK); its format is documented in `key.ts` only. The expanded\n// variables are the older spelling of the same coordinates, kept\n// for the restate-operator (`RESTATE_INPROC_*`) and the standalone tunnel\n// container (`RESTATE_*`): environment id, token or token file, region or\n// SRV / servers, signing key.\n\nimport * as fs from \"node:fs\";\nimport { parseCloudKey } from \"./key.js\";\nimport {\n requireHeaderSafe,\n srvNameForRegionDomain,\n} from \"../tunnel/options.js\";\nimport type { EngineOptions } from \"../tunnel/types.js\";\n\n/** The Cloud UI, for the deep links below. */\nexport const CLOUD_UI_URL = \"https://cloud.restate.dev\";\n/** Where to get a connect key (Development → Configure SDK), linked in every error. */\nexport const CONNECT_KEY_URL = `${CLOUD_UI_URL}/to/developers/integration#configure-sdk`;\n\n/** The deployment name, in resolution order. */\nexport const CONNECT_NAME_ENVS = [\n \"RESTATE_CONNECT_NAME\",\n \"RESTATE_INPROC_TUNNEL_NAME\",\n \"RESTATE_TUNNEL_NAME\",\n] as const;\n/** The connect key. */\nexport const CONNECT_KEY_ENV = \"RESTATE_CONNECT_KEY\";\n\n// The expanded variables, each in resolution order.\nexport const ENVIRONMENT_ID_ENVS = [\n \"RESTATE_ENVIRONMENT_ID\",\n \"RESTATE_INPROC_ENVIRONMENT_ID\",\n] as const;\nexport const AUTH_TOKEN_ENVS = [\"RESTATE_AUTH_TOKEN\"] as const;\n/** A file holding the token, re-read on every reconnect (a mounted Secret). */\nexport const AUTH_TOKEN_FILE_ENVS = [\"RESTATE_INPROC_AUTH_TOKEN_FILE\"] as const;\nexport const CLOUD_REGION_ENVS = [\n \"RESTATE_CLOUD_REGION\",\n \"RESTATE_INPROC_CLOUD_REGION\",\n] as const;\nexport const TUNNEL_SERVERS_SRV_ENVS = [\"RESTATE_TUNNEL_SERVERS_SRV\"] as const;\nexport const TUNNEL_SERVERS_ENVS = [\"RESTATE_TUNNEL_SERVERS\"] as const;\nexport const SIGNING_PUBLIC_KEY_ENVS = [\n \"RESTATE_SIGNING_PUBLIC_KEY\",\n \"RESTATE_INPROC_SIGNING_PUBLIC_KEY\",\n] as const;\n\n/** The query parameters a connect key may carry; anything else is ignored with a warning. */\nconst KNOWN_KEY_PARAMS = [\"envid\", \"apikey\", \"region\", \"signingkey\"];\n\n/** A region domain: lowercase labels of [a-z0-9-], dot-separated, none empty. */\nconst REGION_DOMAIN = /^[a-z0-9-]+(\\.[a-z0-9-]+)*$/;\n\n/** An env var set to the empty string is treated as unset. */\nfunction readEnv(name: string): string | undefined {\n const value = process.env[name];\n return value === undefined || value === \"\" ? undefined : value;\n}\n\n/** The first set variable among `names`, with its name. */\nfunction readFirstEnv(\n names: readonly string[]\n): { value: string; name: string } | undefined {\n for (const name of names) {\n const value = readEnv(name);\n if (value !== undefined) return { value, name };\n }\n return undefined;\n}\n\nfunction given(value: string | undefined): value is string {\n return value !== undefined && value !== \"\";\n}\n\n/**\n * The deployment name: option → `RESTATE_CONNECT_NAME` →\n * `RESTATE_INPROC_TUNNEL_NAME` → `RESTATE_TUNNEL_NAME` → error. No inference:\n * an unnamed deployment is a mistake, and the error says what to set.\n */\nexport function resolveName(option: string | undefined): string {\n const name = given(option) ? option : readFirstEnv(CONNECT_NAME_ENVS)?.value;\n if (name === undefined) {\n throw new Error(\n `connect(): the deployment needs a name — pass { name: \"greeter-v1\" } or set ${CONNECT_NAME_ENVS[0]}. Replicas of one deployment share the name; it is what you register (connect://<name>).`\n );\n }\n if (!/^[A-Za-z0-9._-]+$/.test(name)) {\n throw new Error(\n `connect(): invalid deployment name ${JSON.stringify(name)} — use letters, digits, '.', '_' or '-'`\n );\n }\n return name;\n}\n\n/** The resolved coordinates: everything but the name and the tuning. */\nexport type Coordinates = Pick<\n EngineOptions,\n \"environmentId\" | \"authToken\" | \"identityKeys\" | \"discovery\"\n> & {\n /** For the banner: the region domain, or what stands in for it. */\n regionLabel: string;\n};\n\n/** Discovery overrides from the options (at most one). */\nexport interface DiscoveryOverrides {\n serversSrv?: string;\n servers?: string[];\n}\n\n/**\n * The coordinates for `connect()`: `key` option → `RESTATE_CONNECT_KEY` →\n * the expanded variables → error naming the variable and the Cloud UI page.\n * Explicit `identityKeys` and discovery options win over the key's.\n */\nexport function resolveCoordinates(\n options: {\n key?: string;\n identityKeys?: string[];\n } & DiscoveryOverrides,\n warn: (message: string) => void\n): Coordinates {\n if (given(options.key)) {\n return coordinatesFromKey(\n parseCloudKey(options.key, \"the `key` option\", CONNECT_KEY_URL),\n options,\n warn\n );\n }\n const fromEnv = readEnv(CONNECT_KEY_ENV);\n if (fromEnv !== undefined) {\n return coordinatesFromKey(\n parseCloudKey(fromEnv, CONNECT_KEY_ENV, CONNECT_KEY_URL),\n options,\n warn\n );\n }\n if (readFirstEnv(ENVIRONMENT_ID_ENVS) === undefined) {\n throw new Error(\n `connect(): no Restate Cloud connect key — set ${CONNECT_KEY_ENV} (create one at ${CONNECT_KEY_URL}) or pass { key }`\n );\n }\n return coordinatesFromExpanded(options);\n}\n\nfunction coordinatesFromKey(\n key: Array<[name: string, value: string]>,\n options: { identityKeys?: string[] } & DiscoveryOverrides,\n warn: (message: string) => void\n): Coordinates {\n const params = new Map<string, string>();\n const unknown: string[] = [];\n for (const [name, value] of key) {\n if (!KNOWN_KEY_PARAMS.includes(name)) {\n unknown.push(name);\n } else if (params.has(name)) {\n fail(\n `the connect key is malformed — copy it again from ${CONNECT_KEY_URL}`\n );\n } else {\n params.set(name, value);\n }\n }\n if (unknown.length > 0) {\n warn(\n `connect(): the connect key carries data this SDK version does not understand (${unknown.map((n) => JSON.stringify(n)).join(\", \")}); ignoring it — a newer SDK may need it`\n );\n }\n\n // A missing or malformed piece is a bad paste, never explained further:\n // the key is opaque to the user, the fix is always a fresh copy.\n const incomplete = (): never =>\n fail(\n `the connect key is incomplete — copy it again from ${CONNECT_KEY_URL}`\n );\n const malformed = (): never =>\n fail(\n `the connect key is malformed — copy it again from ${CONNECT_KEY_URL}`\n );\n\n const environmentId = params.get(\"envid\") ?? incomplete();\n if (!/^env_[A-Za-z0-9_-]+$/.test(environmentId)) malformed();\n\n // A key for one environment next to an operator's variables for another\n // is almost certainly a stray developer key: say so.\n const injected = readFirstEnv(ENVIRONMENT_ID_ENVS);\n if (injected !== undefined && injected.value !== environmentId) {\n warn(\n `connect(): the connect key is for environment ${environmentId} but ${injected.name} is set to ${injected.value}; the key wins`\n );\n }\n\n const identityKeys = resolveIdentityKeys(\n options.identityKeys,\n params.get(\"signingkey\"),\n `the connect key carries no signing key and no identityKeys were given — this is an ingress key or an incomplete paste; copy a connect key from ${CONNECT_KEY_URL}`\n );\n\n const apiKey = params.get(\"apikey\");\n const authToken =\n apiKey !== undefined && apiKey !== \"\"\n ? constantToken(apiKey, \"the connect key's API key\")\n : (tokenFromEnv() ??\n fail(\n `the connect key carries no API key and no token is configured in ${AUTH_TOKEN_ENVS[0]} or a file in ${AUTH_TOKEN_FILE_ENVS[0]}`\n ));\n\n const regionDomain = params.get(\"region\") ?? incomplete();\n if (!REGION_DOMAIN.test(regionDomain)) malformed();\n\n // Discovery: explicit options, else the region's SRV name.\n const override = pickDiscovery(options);\n const discovery = override ?? {\n srvName: srvNameForRegionDomain(regionDomain),\n };\n\n return {\n environmentId,\n authToken,\n identityKeys,\n discovery,\n regionLabel:\n override === undefined ? regionDomain : discoveryLabel(discovery),\n };\n}\n\n/**\n * The coordinates from the expanded variables (`RESTATE_<X>`, then\n * `RESTATE_INPROC_<X>`), each missing piece an error naming its variable.\n * Explicit `identityKeys` and discovery options win over the environment.\n */\nexport function coordinatesFromExpanded(\n o: DiscoveryOverrides & { identityKeys?: string[] }\n): Coordinates {\n const environmentId = requireHeaderSafe(\n readFirstEnv(ENVIRONMENT_ID_ENVS)?.value ??\n fail(\n `environmentId is required — set ${ENVIRONMENT_ID_ENVS[0]} (or ${CONNECT_KEY_ENV} from ${CONNECT_KEY_URL})`\n ),\n \"environmentId\"\n );\n if (!/^env_[A-Za-z0-9_-]+$/.test(environmentId)) {\n throw new Error(\n `connect(): environmentId must be \\`env_\\` followed by alphanumerics (e.g. env_201k0yd4...), got ${JSON.stringify(environmentId)}`\n );\n }\n\n const authToken =\n tokenFromEnv() ??\n fail(\n `authToken is required — set ${AUTH_TOKEN_ENVS[0]} or a token file in ${AUTH_TOKEN_FILE_ENVS[0]} (or ${CONNECT_KEY_ENV} from ${CONNECT_KEY_URL})`\n );\n\n const identityKeys = resolveIdentityKeys(\n o.identityKeys,\n readFirstEnv(SIGNING_PUBLIC_KEY_ENVS)?.value,\n `signingPublicKey is required — set ${SIGNING_PUBLIC_KEY_ENVS[0]} (or ${CONNECT_KEY_ENV} from ${CONNECT_KEY_URL})`\n );\n\n // Discovery: the options, else the environment: RESTATE_CLOUD_REGION →\n // RESTATE_TUNNEL_SERVERS_SRV → RESTATE_TUNNEL_SERVERS →\n // RESTATE_INPROC_CLOUD_REGION.\n let discovery = pickDiscovery(o);\n let regionLabel: string | undefined;\n if (discovery === undefined) {\n const region = readEnv(CLOUD_REGION_ENVS[0]);\n const srv = readFirstEnv(TUNNEL_SERVERS_SRV_ENVS)?.value;\n const servers = readFirstEnv(TUNNEL_SERVERS_ENVS)?.value;\n const inproc = readEnv(CLOUD_REGION_ENVS[1]);\n if (region !== undefined || (srv === undefined && servers === undefined)) {\n const value = region ?? inproc;\n if (value === undefined) {\n throw new Error(\n `connect(): no Restate Cloud region — set ${CLOUD_REGION_ENVS[0]} (or ${CONNECT_KEY_ENV} from ${CONNECT_KEY_URL})`\n );\n }\n const domain = regionDomainForRegion(value);\n discovery = { srvName: srvNameForRegionDomain(domain) };\n regionLabel = domain;\n } else if (srv !== undefined) {\n discovery = { srvName: srv };\n } else {\n discovery = { servers: splitList(servers!) };\n }\n }\n\n return {\n environmentId,\n authToken,\n identityKeys,\n discovery,\n regionLabel: regionLabel ?? discoveryLabel(discovery),\n };\n}\n\nfunction fail(message: string): never {\n throw new Error(`connect(): ${message}`);\n}\n\nfunction resolveIdentityKeys(\n option: string[] | undefined,\n signingKey: string | undefined,\n missing: string\n): string[] {\n if (option !== undefined && option.length > 0) return option;\n if (signingKey === undefined) fail(missing);\n if (!signingKey.startsWith(\"publickeyv1_\")) {\n fail(\n `the signing key must be a request-identity public key (publickeyv1_...), got ${JSON.stringify(signingKey)}`\n );\n }\n return [signingKey];\n}\n\nfunction constantToken(token: string, what: string): () => string {\n requireHeaderSafe(token, what);\n return () => token;\n}\n\n/** `RESTATE_AUTH_TOKEN`, then the file named by `RESTATE_INPROC_AUTH_TOKEN_FILE`. */\nfunction tokenFromEnv(): (() => string) | undefined {\n const token = readFirstEnv(AUTH_TOKEN_ENVS);\n if (token !== undefined) return constantToken(token.value, token.name);\n const file = readFirstEnv(AUTH_TOKEN_FILE_ENVS);\n if (file === undefined) return undefined;\n const tokenFile = file.value;\n const readToken = () => {\n // Guard before reading: this runs synchronously on the redial path, so a\n // FIFO (blocks forever) or an unbounded device file (reads forever) would\n // freeze the event loop — and with it every other live connection.\n const stat = fs.statSync(tokenFile);\n if (!stat.isFile()) {\n throw new Error(\n `connect(): token file ${tokenFile} (${file.name}) is not a regular file`\n );\n }\n if (stat.size > 64 * 1024) {\n throw new Error(\n `connect(): token file ${tokenFile} (${file.name}) is implausibly large for a token (${stat.size} bytes)`\n );\n }\n // Trimmed because mounted secrets routinely carry a trailing newline.\n const token = fs.readFileSync(tokenFile, \"utf8\").trim();\n if (token === \"\") {\n throw new Error(\n `connect(): token file ${tokenFile} (${file.name}) is empty`\n );\n }\n return requireHeaderSafe(token, `token file ${tokenFile}`);\n };\n // A bad path or token must throw at configuration time like every other\n // misconfiguration, not look like a transient failure mid-redial.\n readToken();\n return readToken;\n}\n\nfunction pickDiscovery(\n o: DiscoveryOverrides\n): EngineOptions[\"discovery\"] | undefined {\n if (given(o.serversSrv) && o.servers !== undefined) {\n throw new Error(\n \"connect(): specify at most one of `serversSrv` and `servers`\"\n );\n }\n if (given(o.serversSrv)) return { srvName: o.serversSrv };\n if (o.servers !== undefined) {\n if (o.servers.length === 0) {\n throw new Error(\"connect(): `servers` must not be empty\");\n }\n return { servers: o.servers };\n }\n return undefined;\n}\n\n/** A region (`us`, `eu`, `<slug>.byoc`) is the labels before `.restate.cloud`. */\nfunction regionDomainForRegion(region: string): string {\n // Each label lowercase [a-z0-9-], dot-separated, no empty labels.\n if (!REGION_DOMAIN.test(region)) {\n throw new Error(`connect(): invalid region ${JSON.stringify(region)}`);\n }\n return `${region}.restate.cloud`;\n}\n\n/** Human-readable discovery target for the banner. */\nfunction discoveryLabel(discovery: EngineOptions[\"discovery\"]): string {\n if (\"srvName\" in discovery) {\n return discovery.srvName.replace(/^tunnel\\./, \"\");\n }\n return discovery.servers.join(\",\");\n}\n\nfunction splitList(value: string): string[] {\n return value\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s !== \"\");\n}\n\n/** The registration identifier the CLI and the Cloud UI accept. */\nexport function registrationIdentifier(name: string): string {\n return `connect://${name}`;\n}\n\n/** The Cloud UI deep link that opens the register dialog pre-filled. */\nexport function registrationDeepLink(name: string): string {\n return `${CLOUD_UI_URL}/to/overview?register-deployment=${registrationIdentifier(name)}`;\n}\n"],"mappings":";;;;;;AAqCA,MAAa,eAAe;;AAE5B,MAAa,kBAAkB,GAAG,aAAa;;AAG/C,MAAa,oBAAoB;CAC/B;CACA;CACA;CACD;;AAED,MAAa,kBAAkB;AAG/B,MAAa,sBAAsB,CACjC,0BACA,gCACD;AACD,MAAa,kBAAkB,CAAC,qBAAqB;;AAErD,MAAa,uBAAuB,CAAC,iCAAiC;AACtE,MAAa,oBAAoB,CAC/B,wBACA,8BACD;AACD,MAAa,0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AA6B,KAAK,UAAU,OAAO,GAAG;AAExE,QAAO,GAAG,OAAO;;;AAInB,SAAS,eAAe,WAA+C;AACrE,KAAI,aAAa,UACf,QAAO,UAAU,QAAQ,QAAQ,aAAa,GAAG;AAEnD,QAAO,UAAU,QAAQ,KAAK,IAAI;;AAGpC,SAAS,UAAU,OAAyB;AAC1C,QAAO,MACJ,MAAM,IAAI,CACV,KAAK,MAAM,EAAE,MAAM,CAAC,CACpB,QAAQ,MAAM,MAAM,GAAG;;;AAI5B,SAAgB,uBAAuB,MAAsB;AAC3D,QAAO,aAAa;;;AAItB,SAAgB,qBAAqB,MAAsB;AACzD,QAAO,GAAG,aAAa,mCAAmC,uBAAuB,KAAK"}
@@ -0,0 +1,113 @@
1
+ const require_logger_transport = require('../../logging/logger_transport.cjs');
2
+ const require_console_logger_transport = require('../../logging/console_logger_transport.cjs');
3
+ const require_logger = require('../../logging/logger.cjs');
4
+ const require_engine = require('../tunnel/engine.cjs');
5
+ const require_env = require('./env.cjs');
6
+
7
+ //#region src/endpoint/connect/index.ts
8
+ /**
9
+ * Connect your services to Restate Cloud and serve them over the connection.
10
+ *
11
+ * ```ts
12
+ * import * as restate from "@restatedev/restate-sdk";
13
+ *
14
+ * restate.connect({ services: [greeter], name: "greeter-v1" });
15
+ * ```
16
+ *
17
+ * The connection needs two things:
18
+ *
19
+ * - a **name** for the deployment (`name` option, or `RESTATE_CONNECT_NAME`):
20
+ * the identity you register, shared by replicas of the same deployment;
21
+ * - a **connect key** (`RESTATE_CONNECT_KEY`): one string you can obtain from
22
+ * Cloud UI -> Development → Configure SDK.
23
+ *
24
+ * Both are read from the process environment; the SDK never reads a file.
25
+ *
26
+ * Once connected, the SDK logs how to register the deployment, once:
27
+ *
28
+ * ```
29
+ * Connecting to Restate Cloud environment env_201k… (eu.restate.cloud)
30
+ * Connected as "greeter-v1"
31
+ * Register it once:
32
+ * restate deployments register connect://greeter-v1
33
+ * or open https://cloud.restate.dev/to/overview?register-deployment=connect://greeter-v1
34
+ * ```
35
+ *
36
+ * The returned {@link Connection} reconnects in the background until closed.
37
+ *
38
+ * @param options the services, the name and the tuning, see {@link ConnectOptions}
39
+ * @returns the connection handle
40
+ */
41
+ function connect(options) {
42
+ const handle = connectEngine(options);
43
+ const settled = async (done) => {
44
+ await done;
45
+ if (handle.error !== void 0) throw handle.error;
46
+ };
47
+ return {
48
+ ready: handle.ready,
49
+ name: handle.name,
50
+ close: () => settled(handle.close()),
51
+ shutdown: (opts) => settled(handle.shutdown(opts))
52
+ };
53
+ }
54
+ /**
55
+ * `connect()` without the projection: the engine handle, with the connection
56
+ * count and the fatal error. Internal (tests).
57
+ */
58
+ function connectEngine(options) {
59
+ const { name: nameOption, key, identityKeys, connection = {},...endpointOptions } = options;
60
+ const { serversSrv, servers,...tuning } = connection;
61
+ const rlog = require_logger.createLogger(options.logger ?? require_console_logger_transport.defaultLoggerTransport, require_logger_transport.LogSource.SYSTEM);
62
+ const name = require_env.resolveName(nameOption);
63
+ const coordinates = require_env.resolveCoordinates({
64
+ key,
65
+ identityKeys,
66
+ serversSrv,
67
+ servers
68
+ }, (message) => rlog.warn(message));
69
+ return start({
70
+ ...endpointOptions,
71
+ ...tuning
72
+ }, name, coordinates, rlog);
73
+ }
74
+ /**
75
+ * Start the engine with the resolved identity and log the banner on ready.
76
+ */
77
+ function start(rest, name, coordinates, rlog) {
78
+ const { regionLabel,...engineCoordinates } = coordinates;
79
+ const connection = require_engine.startEngine({
80
+ ...rest,
81
+ name,
82
+ ...engineCoordinates,
83
+ onFatal: (error) => {
84
+ for (const line of explainFatal(error, name, coordinates.environmentId)) rlog.error(line);
85
+ }
86
+ });
87
+ rlog.info(`Connecting to Restate Cloud environment ${coordinates.environmentId} (${regionLabel})`);
88
+ connection.ready.then(() => {
89
+ rlog.debug(`Deployment URL: ${connection.deploymentUrl ?? "?"}`);
90
+ rlog.info(`Connected as "${name}"`);
91
+ rlog.info("Register it once:");
92
+ rlog.info(` restate deployments register ${require_env.registrationIdentifier(name)}`);
93
+ rlog.info(` or open ${require_env.registrationDeepLink(name)}`);
94
+ }, () => {});
95
+ return connection;
96
+ }
97
+ /**
98
+ * A non-retryable stop, in plain words: what Restate Cloud said, what it
99
+ * means, what to do. The engine's own `tunnel: FATAL — …` line stays at debug.
100
+ */
101
+ function explainFatal(error, name, environmentId) {
102
+ const reason = error.message.replace(/^tunnel: /, "");
103
+ const lines = [];
104
+ if (reason.includes("tunnel-status: unauthorized")) lines.push(`Restate Cloud rejected the connect key for environment ${environmentId}: it is invalid, revoked, or for another environment.`, `Create a new key at ${require_env.CONNECT_KEY_URL} and set ${require_env.CONNECT_KEY_ENV}.`);
105
+ else if (reason.includes("tunnel-status: bad-tunnel-name") || reason.startsWith("tunnel-name mismatch")) lines.push(`Restate Cloud rejected the deployment name "${name}" (${reason}).`, `Use letters, digits, '.', '_' or '-' — ${require_env.CONNECT_NAME_ENVS[0]} or the name option.`);
106
+ else if (reason.startsWith("gave up reconnecting")) lines.push(`Could not reach Restate Cloud for environment ${environmentId}: ${reason}.`, `Check the network, and that the key's region is right (${require_env.CONNECT_KEY_ENV}).`);
107
+ else lines.push(`The connection to Restate Cloud stopped: ${reason}`);
108
+ lines.push("Not retrying. Fix the configuration and restart.");
109
+ return lines;
110
+ }
111
+
112
+ //#endregion
113
+ exports.connect = connect;
@@ -0,0 +1,41 @@
1
+ import { ConnectOptions, Connection } from "../tunnel/types.cjs";
2
+
3
+ //#region src/endpoint/connect/index.d.ts
4
+
5
+ /**
6
+ * Connect your services to Restate Cloud and serve them over the connection.
7
+ *
8
+ * ```ts
9
+ * import * as restate from "@restatedev/restate-sdk";
10
+ *
11
+ * restate.connect({ services: [greeter], name: "greeter-v1" });
12
+ * ```
13
+ *
14
+ * The connection needs two things:
15
+ *
16
+ * - a **name** for the deployment (`name` option, or `RESTATE_CONNECT_NAME`):
17
+ * the identity you register, shared by replicas of the same deployment;
18
+ * - a **connect key** (`RESTATE_CONNECT_KEY`): one string you can obtain from
19
+ * Cloud UI -> Development → Configure SDK.
20
+ *
21
+ * Both are read from the process environment; the SDK never reads a file.
22
+ *
23
+ * Once connected, the SDK logs how to register the deployment, once:
24
+ *
25
+ * ```
26
+ * Connecting to Restate Cloud environment env_201k… (eu.restate.cloud)
27
+ * Connected as "greeter-v1"
28
+ * Register it once:
29
+ * restate deployments register connect://greeter-v1
30
+ * or open https://cloud.restate.dev/to/overview?register-deployment=connect://greeter-v1
31
+ * ```
32
+ *
33
+ * The returned {@link Connection} reconnects in the background until closed.
34
+ *
35
+ * @param options the services, the name and the tuning, see {@link ConnectOptions}
36
+ * @returns the connection handle
37
+ */
38
+ declare function connect(options: ConnectOptions): Connection;
39
+ //#endregion
40
+ export { connect };
41
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/endpoint/connect/index.ts"],"sourcesContent":[],"mappings":";;;;;;AAiEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,OAAA,UAAiB,iBAAiB"}
@@ -0,0 +1,41 @@
1
+ import { ConnectOptions, Connection } from "../tunnel/types.js";
2
+
3
+ //#region src/endpoint/connect/index.d.ts
4
+
5
+ /**
6
+ * Connect your services to Restate Cloud and serve them over the connection.
7
+ *
8
+ * ```ts
9
+ * import * as restate from "@restatedev/restate-sdk";
10
+ *
11
+ * restate.connect({ services: [greeter], name: "greeter-v1" });
12
+ * ```
13
+ *
14
+ * The connection needs two things:
15
+ *
16
+ * - a **name** for the deployment (`name` option, or `RESTATE_CONNECT_NAME`):
17
+ * the identity you register, shared by replicas of the same deployment;
18
+ * - a **connect key** (`RESTATE_CONNECT_KEY`): one string you can obtain from
19
+ * Cloud UI -> Development → Configure SDK.
20
+ *
21
+ * Both are read from the process environment; the SDK never reads a file.
22
+ *
23
+ * Once connected, the SDK logs how to register the deployment, once:
24
+ *
25
+ * ```
26
+ * Connecting to Restate Cloud environment env_201k… (eu.restate.cloud)
27
+ * Connected as "greeter-v1"
28
+ * Register it once:
29
+ * restate deployments register connect://greeter-v1
30
+ * or open https://cloud.restate.dev/to/overview?register-deployment=connect://greeter-v1
31
+ * ```
32
+ *
33
+ * The returned {@link Connection} reconnects in the background until closed.
34
+ *
35
+ * @param options the services, the name and the tuning, see {@link ConnectOptions}
36
+ * @returns the connection handle
37
+ */
38
+ declare function connect(options: ConnectOptions): Connection;
39
+ //#endregion
40
+ export { connect };
41
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/endpoint/connect/index.ts"],"sourcesContent":[],"mappings":";;;;;;AAiEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,OAAA,UAAiB,iBAAiB"}
@@ -0,0 +1,114 @@
1
+ import { LogSource } from "../../logging/logger_transport.js";
2
+ import { defaultLoggerTransport } from "../../logging/console_logger_transport.js";
3
+ import { createLogger } from "../../logging/logger.js";
4
+ import { startEngine } from "../tunnel/engine.js";
5
+ import { CONNECT_KEY_ENV, CONNECT_KEY_URL, CONNECT_NAME_ENVS, registrationDeepLink, registrationIdentifier, resolveCoordinates, resolveName } from "./env.js";
6
+
7
+ //#region src/endpoint/connect/index.ts
8
+ /**
9
+ * Connect your services to Restate Cloud and serve them over the connection.
10
+ *
11
+ * ```ts
12
+ * import * as restate from "@restatedev/restate-sdk";
13
+ *
14
+ * restate.connect({ services: [greeter], name: "greeter-v1" });
15
+ * ```
16
+ *
17
+ * The connection needs two things:
18
+ *
19
+ * - a **name** for the deployment (`name` option, or `RESTATE_CONNECT_NAME`):
20
+ * the identity you register, shared by replicas of the same deployment;
21
+ * - a **connect key** (`RESTATE_CONNECT_KEY`): one string you can obtain from
22
+ * Cloud UI -> Development → Configure SDK.
23
+ *
24
+ * Both are read from the process environment; the SDK never reads a file.
25
+ *
26
+ * Once connected, the SDK logs how to register the deployment, once:
27
+ *
28
+ * ```
29
+ * Connecting to Restate Cloud environment env_201k… (eu.restate.cloud)
30
+ * Connected as "greeter-v1"
31
+ * Register it once:
32
+ * restate deployments register connect://greeter-v1
33
+ * or open https://cloud.restate.dev/to/overview?register-deployment=connect://greeter-v1
34
+ * ```
35
+ *
36
+ * The returned {@link Connection} reconnects in the background until closed.
37
+ *
38
+ * @param options the services, the name and the tuning, see {@link ConnectOptions}
39
+ * @returns the connection handle
40
+ */
41
+ function connect(options) {
42
+ const handle = connectEngine(options);
43
+ const settled = async (done) => {
44
+ await done;
45
+ if (handle.error !== void 0) throw handle.error;
46
+ };
47
+ return {
48
+ ready: handle.ready,
49
+ name: handle.name,
50
+ close: () => settled(handle.close()),
51
+ shutdown: (opts) => settled(handle.shutdown(opts))
52
+ };
53
+ }
54
+ /**
55
+ * `connect()` without the projection: the engine handle, with the connection
56
+ * count and the fatal error. Internal (tests).
57
+ */
58
+ function connectEngine(options) {
59
+ const { name: nameOption, key, identityKeys, connection = {},...endpointOptions } = options;
60
+ const { serversSrv, servers,...tuning } = connection;
61
+ const rlog = createLogger(options.logger ?? defaultLoggerTransport, LogSource.SYSTEM);
62
+ const name = resolveName(nameOption);
63
+ const coordinates = resolveCoordinates({
64
+ key,
65
+ identityKeys,
66
+ serversSrv,
67
+ servers
68
+ }, (message) => rlog.warn(message));
69
+ return start({
70
+ ...endpointOptions,
71
+ ...tuning
72
+ }, name, coordinates, rlog);
73
+ }
74
+ /**
75
+ * Start the engine with the resolved identity and log the banner on ready.
76
+ */
77
+ function start(rest, name, coordinates, rlog) {
78
+ const { regionLabel,...engineCoordinates } = coordinates;
79
+ const connection = startEngine({
80
+ ...rest,
81
+ name,
82
+ ...engineCoordinates,
83
+ onFatal: (error) => {
84
+ for (const line of explainFatal(error, name, coordinates.environmentId)) rlog.error(line);
85
+ }
86
+ });
87
+ rlog.info(`Connecting to Restate Cloud environment ${coordinates.environmentId} (${regionLabel})`);
88
+ connection.ready.then(() => {
89
+ rlog.debug(`Deployment URL: ${connection.deploymentUrl ?? "?"}`);
90
+ rlog.info(`Connected as "${name}"`);
91
+ rlog.info("Register it once:");
92
+ rlog.info(` restate deployments register ${registrationIdentifier(name)}`);
93
+ rlog.info(` or open ${registrationDeepLink(name)}`);
94
+ }, () => {});
95
+ return connection;
96
+ }
97
+ /**
98
+ * A non-retryable stop, in plain words: what Restate Cloud said, what it
99
+ * means, what to do. The engine's own `tunnel: FATAL — …` line stays at debug.
100
+ */
101
+ function explainFatal(error, name, environmentId) {
102
+ const reason = error.message.replace(/^tunnel: /, "");
103
+ const lines = [];
104
+ if (reason.includes("tunnel-status: unauthorized")) lines.push(`Restate Cloud rejected the connect key for environment ${environmentId}: it is invalid, revoked, or for another environment.`, `Create a new key at ${CONNECT_KEY_URL} and set ${CONNECT_KEY_ENV}.`);
105
+ else if (reason.includes("tunnel-status: bad-tunnel-name") || reason.startsWith("tunnel-name mismatch")) lines.push(`Restate Cloud rejected the deployment name "${name}" (${reason}).`, `Use letters, digits, '.', '_' or '-' — ${CONNECT_NAME_ENVS[0]} or the name option.`);
106
+ else if (reason.startsWith("gave up reconnecting")) lines.push(`Could not reach Restate Cloud for environment ${environmentId}: ${reason}.`, `Check the network, and that the key's region is right (${CONNECT_KEY_ENV}).`);
107
+ else lines.push(`The connection to Restate Cloud stopped: ${reason}`);
108
+ lines.push("Not retrying. Fix the configuration and restart.");
109
+ return lines;
110
+ }
111
+
112
+ //#endregion
113
+ export { connect };
114
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["lines: string[]"],"sources":["../../../src/endpoint/connect/index.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\nimport { startEngine } from \"../tunnel/engine.js\";\nimport type {\n Connection,\n ConnectOptions,\n EngineHandle,\n EngineOptions,\n} from \"../tunnel/types.js\";\nimport {\n CONNECT_KEY_ENV,\n CONNECT_KEY_URL,\n CONNECT_NAME_ENVS,\n type Coordinates,\n registrationDeepLink,\n registrationIdentifier,\n resolveCoordinates,\n resolveName,\n} from \"./env.js\";\nimport { createLogger, type Logger } from \"../../logging/logger.js\";\nimport { LogSource } from \"../../logging/logger_transport.js\";\nimport { defaultLoggerTransport } from \"../../logging/console_logger_transport.js\";\n\n/**\n * Connect your services to Restate Cloud and serve them over the connection.\n *\n * ```ts\n * import * as restate from \"@restatedev/restate-sdk\";\n *\n * restate.connect({ services: [greeter], name: \"greeter-v1\" });\n * ```\n *\n * The connection needs two things:\n *\n * - a **name** for the deployment (`name` option, or `RESTATE_CONNECT_NAME`):\n * the identity you register, shared by replicas of the same deployment;\n * - a **connect key** (`RESTATE_CONNECT_KEY`): one string you can obtain from\n * Cloud UI -> Development → Configure SDK.\n *\n * Both are read from the process environment; the SDK never reads a file.\n *\n * Once connected, the SDK logs how to register the deployment, once:\n *\n * ```\n * Connecting to Restate Cloud environment env_201k… (eu.restate.cloud)\n * Connected as \"greeter-v1\"\n * Register it once:\n * restate deployments register connect://greeter-v1\n * or open https://cloud.restate.dev/to/overview?register-deployment=connect://greeter-v1\n * ```\n *\n * The returned {@link Connection} reconnects in the background until closed.\n *\n * @param options the services, the name and the tuning, see {@link ConnectOptions}\n * @returns the connection handle\n */\nexport function connect(options: ConnectOptions): Connection {\n const handle = connectEngine(options);\n // The fatal error is on the handle; surface it where the caller waits.\n const settled = async (done: Promise<void>): Promise<void> => {\n await done;\n if (handle.error !== undefined) throw handle.error;\n };\n return {\n ready: handle.ready,\n name: handle.name,\n close: () => settled(handle.close()),\n shutdown: (opts) => settled(handle.shutdown(opts)),\n };\n}\n\n/**\n * `connect()` without the projection: the engine handle, with the connection\n * count and the fatal error. Internal (tests).\n */\nexport function connectEngine(options: ConnectOptions): EngineHandle {\n const {\n name: nameOption,\n key,\n identityKeys,\n connection = {},\n ...endpointOptions\n } = options;\n const { serversSrv, servers, ...tuning } = connection;\n const rlog = createLogger(\n options.logger ?? defaultLoggerTransport,\n LogSource.SYSTEM\n );\n const name = resolveName(nameOption);\n const coordinates = resolveCoordinates(\n { key, identityKeys, serversSrv, servers },\n (message) => rlog.warn(message)\n );\n return start({ ...endpointOptions, ...tuning }, name, coordinates, rlog);\n}\n\n/**\n * Start the engine with the resolved identity and log the banner on ready.\n */\nfunction start(\n rest: Omit<\n EngineOptions,\n \"name\" | \"environmentId\" | \"authToken\" | \"identityKeys\" | \"discovery\"\n >,\n name: string,\n coordinates: Coordinates,\n rlog: Logger\n): EngineHandle {\n const { regionLabel, ...engineCoordinates } = coordinates;\n // startEngine validates the tuning synchronously; log only once it did.\n const connection = startEngine({\n ...rest,\n name,\n ...engineCoordinates,\n onFatal: (error) => {\n for (const line of explainFatal(error, name, coordinates.environmentId)) {\n rlog.error(line);\n }\n },\n });\n rlog.info(\n `Connecting to Restate Cloud environment ${coordinates.environmentId} (${regionLabel})`\n );\n connection.ready.then(\n () => {\n rlog.debug(`Deployment URL: ${connection.deploymentUrl ?? \"?\"}`);\n rlog.info(`Connected as \"${name}\"`);\n rlog.info(\"Register it once:\");\n rlog.info(\n ` restate deployments register ${registrationIdentifier(name)}`\n );\n rlog.info(` or open ${registrationDeepLink(name)}`);\n },\n () => {\n // Explained by onFatal above (or a plain close() before the first handshake).\n }\n );\n return connection;\n}\n\n/**\n * A non-retryable stop, in plain words: what Restate Cloud said, what it\n * means, what to do. The engine's own `tunnel: FATAL — …` line stays at debug.\n */\nfunction explainFatal(\n error: Error,\n name: string,\n environmentId: string\n): string[] {\n const reason = error.message.replace(/^tunnel: /, \"\");\n const lines: string[] = [];\n if (reason.includes(\"tunnel-status: unauthorized\")) {\n lines.push(\n `Restate Cloud rejected the connect key for environment ${environmentId}: it is invalid, revoked, or for another environment.`,\n `Create a new key at ${CONNECT_KEY_URL} and set ${CONNECT_KEY_ENV}.`\n );\n } else if (\n reason.includes(\"tunnel-status: bad-tunnel-name\") ||\n reason.startsWith(\"tunnel-name mismatch\")\n ) {\n lines.push(\n `Restate Cloud rejected the deployment name \"${name}\" (${reason}).`,\n `Use letters, digits, '.', '_' or '-' — ${CONNECT_NAME_ENVS[0]} or the name option.`\n );\n } else if (reason.startsWith(\"gave up reconnecting\")) {\n lines.push(\n `Could not reach Restate Cloud for environment ${environmentId}: ${reason}.`,\n `Check the network, and that the key's region is right (${CONNECT_KEY_ENV}).`\n );\n } else {\n lines.push(`The connection to Restate Cloud stopped: ${reason}`);\n }\n lines.push(\"Not retrying. Fix the configuration and restart.\");\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAgB,QAAQ,SAAqC;CAC3D,MAAM,SAAS,cAAc,QAAQ;CAErC,MAAM,UAAU,OAAO,SAAuC;AAC5D,QAAM;AACN,MAAI,OAAO,UAAU,OAAW,OAAM,OAAO;;AAE/C,QAAO;EACL,OAAO,OAAO;EACd,MAAM,OAAO;EACb,aAAa,QAAQ,OAAO,OAAO,CAAC;EACpC,WAAW,SAAS,QAAQ,OAAO,SAAS,KAAK,CAAC;EACnD;;;;;;AAOH,SAAgB,cAAc,SAAuC;CACnE,MAAM,EACJ,MAAM,YACN,KACA,cACA,aAAa,EAAE,CACf,GAAG,oBACD;CACJ,MAAM,EAAE,YAAY,QAAS,GAAG,WAAW;CAC3C,MAAM,OAAO,aACX,QAAQ,UAAU,wBAClB,UAAU,OACX;CACD,MAAM,OAAO,YAAY,WAAW;CACpC,MAAM,cAAc,mBAClB;EAAE;EAAK;EAAc;EAAY;EAAS,GACzC,YAAY,KAAK,KAAK,QAAQ,CAChC;AACD,QAAO,MAAM;EAAE,GAAG;EAAiB,GAAG;EAAQ,EAAE,MAAM,aAAa,KAAK;;;;;AAM1E,SAAS,MACP,MAIA,MACA,aACA,MACc;CACd,MAAM,EAAE,YAAa,GAAG,sBAAsB;CAE9C,MAAM,aAAa,YAAY;EAC7B,GAAG;EACH;EACA,GAAG;EACH,UAAU,UAAU;AAClB,QAAK,MAAM,QAAQ,aAAa,OAAO,MAAM,YAAY,cAAc,CACrE,MAAK,MAAM,KAAK;;EAGrB,CAAC;AACF,MAAK,KACH,2CAA2C,YAAY,cAAc,IAAI,YAAY,GACtF;AACD,YAAW,MAAM,WACT;AACJ,OAAK,MAAM,mBAAmB,WAAW,iBAAiB,MAAM;AAChE,OAAK,KAAK,iBAAiB,KAAK,GAAG;AACnC,OAAK,KAAK,oBAAoB;AAC9B,OAAK,KACH,kCAAkC,uBAAuB,KAAK,GAC/D;AACD,OAAK,KAAK,aAAa,qBAAqB,KAAK,GAAG;UAEhD,GAGP;AACD,QAAO;;;;;;AAOT,SAAS,aACP,OACA,MACA,eACU;CACV,MAAM,SAAS,MAAM,QAAQ,QAAQ,aAAa,GAAG;CACrD,MAAMA,QAAkB,EAAE;AAC1B,KAAI,OAAO,SAAS,8BAA8B,CAChD,OAAM,KACJ,0DAA0D,cAAc,wDACxE,uBAAuB,gBAAgB,WAAW,gBAAgB,GACnE;UAED,OAAO,SAAS,iCAAiC,IACjD,OAAO,WAAW,uBAAuB,CAEzC,OAAM,KACJ,+CAA+C,KAAK,KAAK,OAAO,KAChE,0CAA0C,kBAAkB,GAAG,sBAChE;UACQ,OAAO,WAAW,uBAAuB,CAClD,OAAM,KACJ,iDAAiD,cAAc,IAAI,OAAO,IAC1E,0DAA0D,gBAAgB,IAC3E;KAED,OAAM,KAAK,4CAA4C,SAAS;AAElE,OAAM,KAAK,mDAAmD;AAC9D,QAAO"}
@@ -0,0 +1,62 @@
1
+
2
+ //#region src/endpoint/connect/key.ts
3
+ /** The prefix every Restate Cloud key starts with. */
4
+ const CLOUD_KEY_PREFIX = "rstcloudv1_";
5
+ /** The shape shown in errors. */
6
+ const CLOUD_KEY_SHAPE = `${CLOUD_KEY_PREFIX}<base58>`;
7
+ const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
8
+ /**
9
+ * Parse a Restate Cloud key (`rstcloudv1_<base58>`) into its query parameters,
10
+ * in order. Throws an `Error` whose message starts with `what` (the variable
11
+ * or option the value came from) when the string does not follow the format;
12
+ * the message says what is wrong, shows the expected shape and links `help`.
13
+ *
14
+ * @param value the key string
15
+ * @param what how to call the value in errors, e.g. `RESTATE_CONNECT_KEY`
16
+ * @param help where to get a fresh key, linked in every error
17
+ */
18
+ function parseCloudKey(value, what, help) {
19
+ const fail = (reason) => {
20
+ throw new Error(`${what} is not a Restate Cloud key (${reason}); expected ${CLOUD_KEY_SHAPE} — copy it again from ${help}`);
21
+ };
22
+ const trimmed = value.trim();
23
+ if (!trimmed.startsWith(CLOUD_KEY_PREFIX)) return fail(`it does not start with ${CLOUD_KEY_PREFIX}`);
24
+ const encoded = trimmed.slice(11);
25
+ const corrupted = () => fail("it is truncated or corrupted");
26
+ if (encoded === "") return corrupted();
27
+ let query;
28
+ try {
29
+ query = new TextDecoder("utf-8", { fatal: true }).decode(base58Decode(encoded));
30
+ } catch {
31
+ return corrupted();
32
+ }
33
+ if (!/^[\x21-\x7e]+$/.test(query)) return corrupted();
34
+ const params = [...new URLSearchParams(query).entries()];
35
+ if (params.some(([name]) => name === "")) return corrupted();
36
+ return params;
37
+ }
38
+ /** Decode base58 (Bitcoin alphabet); throws on a character outside it. */
39
+ function base58Decode(text) {
40
+ const digits = [];
41
+ for (const char of text) {
42
+ let carry = BASE58_ALPHABET.indexOf(char);
43
+ if (carry < 0) throw new Error(`not base58: ${JSON.stringify(char)}`);
44
+ for (let i = 0; i < digits.length; i++) {
45
+ carry += digits[i] * 58;
46
+ digits[i] = carry & 255;
47
+ carry >>= 8;
48
+ }
49
+ while (carry > 0) {
50
+ digits.push(carry & 255);
51
+ carry >>= 8;
52
+ }
53
+ }
54
+ let zeros = 0;
55
+ while (zeros < text.length && text[zeros] === "1") zeros++;
56
+ const out = new Uint8Array(zeros + digits.length);
57
+ for (let i = 0; i < digits.length; i++) out[zeros + i] = digits[digits.length - 1 - i];
58
+ return out;
59
+ }
60
+
61
+ //#endregion
62
+ exports.parseCloudKey = parseCloudKey;