zitejs 0.10.0-start.2 → 0.10.0-start.21
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.
- package/dist/cjs/auth/actions.d.ts +28 -0
- package/dist/cjs/auth/actions.js +93 -0
- package/dist/cjs/auth/client.d.ts +357 -0
- package/dist/cjs/auth/client.js +66 -0
- package/dist/cjs/auth/index.d.ts +2 -249
- package/dist/cjs/auth/index.js +11 -108
- package/dist/cjs/auth/index.test.js +48 -0
- package/dist/cjs/auth/previewClaim.d.ts +7 -0
- package/dist/cjs/auth/previewClaim.js +16 -0
- package/dist/cjs/auth/profileUpdates.d.ts +9 -0
- package/dist/cjs/auth/profileUpdates.js +11 -0
- package/dist/cjs/backend/index.d.ts +121 -3
- package/dist/cjs/backend/index.test.js +58 -0
- package/dist/cjs/bundle/index.d.ts +8 -0
- package/dist/cjs/bundle/index.js +9 -8
- package/dist/cjs/check/index.d.ts +45 -1
- package/dist/cjs/check/index.js +198 -109
- package/dist/cjs/check/start/problem.d.ts +11 -0
- package/dist/cjs/check/start/problem.js +5 -0
- package/dist/cjs/check/start/routeTree.d.ts +9 -0
- package/dist/cjs/check/start/routeTree.js +111 -0
- package/dist/cjs/check/start/sourceRules.d.ts +8 -0
- package/dist/cjs/check/start/sourceRules.js +1159 -0
- package/dist/cjs/check/start/tsgo.d.ts +2 -0
- package/dist/cjs/check/start/tsgo.js +35 -0
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/client/index.d.ts +24 -0
- package/dist/cjs/dev/index.js +14 -4
- package/dist/cjs/integrations/rules.d.ts +13 -0
- package/dist/cjs/integrations/rules.js +31 -0
- package/dist/cjs/integrations/rules.test.js +1 -0
- package/dist/cjs/internal/appMode.d.ts +3 -0
- package/dist/cjs/internal/appMode.js +15 -0
- package/dist/cjs/runtime/index.d.ts +64 -25
- package/dist/cjs/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
- package/dist/cjs/runtime/sendEmailParamsTypes.test-d.js +33 -0
- package/dist/cjs/start/entries.d.ts +10 -4
- package/dist/cjs/start/entries.js +23 -6
- package/dist/cjs/steps/index.d.ts +78 -0
- package/dist/cjs/steps/index.js +507 -0
- package/dist/cjs/steps/index.test.d.ts +1 -0
- package/dist/cjs/steps/index.test.js +635 -0
- package/dist/cjs/sync/index.js +2 -1
- package/dist/cjs/sync/lib.d.ts +10 -3
- package/dist/cjs/sync/lib.js +44 -25
- package/dist/cjs/sync/lib.test.js +116 -36
- package/dist/cjs/types/fields.d.ts +8 -1
- package/dist/cjs/types/fields.js +7 -1
- package/dist/cjs/types/tables.d.ts +16 -0
- package/dist/cjs/upload/index.js +12 -2
- package/dist/cjs/upload/index.test.js +39 -0
- package/dist/cjs/vite/index.js +8 -3
- package/dist/cjs/vite/index.test.js +10 -2
- package/dist/esm/auth/actions.d.ts +28 -0
- package/dist/esm/auth/actions.js +55 -0
- package/dist/esm/auth/client.d.ts +357 -0
- package/dist/esm/auth/client.js +62 -0
- package/dist/esm/auth/index.d.ts +2 -249
- package/dist/esm/auth/index.js +2 -103
- package/dist/esm/auth/index.test.js +48 -0
- package/dist/esm/auth/previewClaim.d.ts +7 -0
- package/dist/esm/auth/previewClaim.js +12 -0
- package/dist/esm/auth/profileUpdates.d.ts +9 -0
- package/dist/esm/auth/profileUpdates.js +6 -0
- package/dist/esm/backend/index.d.ts +121 -3
- package/dist/esm/backend/index.test.js +58 -0
- package/dist/esm/bundle/index.d.ts +8 -0
- package/dist/esm/bundle/index.js +8 -8
- package/dist/esm/check/index.d.ts +45 -1
- package/dist/esm/check/index.js +198 -113
- package/dist/esm/check/start/problem.d.ts +11 -0
- package/dist/esm/check/start/problem.js +1 -0
- package/dist/esm/check/start/routeTree.d.ts +9 -0
- package/dist/esm/check/start/routeTree.js +70 -0
- package/dist/esm/check/start/sourceRules.d.ts +8 -0
- package/dist/esm/check/start/sourceRules.js +1156 -0
- package/dist/esm/check/start/tsgo.d.ts +2 -0
- package/dist/esm/check/start/tsgo.js +29 -0
- package/dist/esm/cli.js +1 -1
- package/dist/esm/client/index.d.ts +24 -0
- package/dist/esm/dev/index.js +16 -6
- package/dist/esm/integrations/rules.d.ts +13 -0
- package/dist/esm/integrations/rules.js +31 -0
- package/dist/esm/integrations/rules.test.js +1 -0
- package/dist/esm/internal/appMode.d.ts +3 -0
- package/dist/esm/internal/appMode.js +10 -0
- package/dist/esm/runtime/index.d.ts +64 -25
- package/dist/esm/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
- package/dist/esm/runtime/sendEmailParamsTypes.test-d.js +31 -0
- package/dist/esm/start/aiUsage.d.ts +23 -0
- package/dist/esm/start/aiUsage.js +146 -0
- package/dist/esm/start/airtable/arrayFields.d.ts +10 -0
- package/dist/esm/start/airtable/arrayFields.js +30 -0
- package/dist/esm/start/airtable/dispatch.d.ts +54 -0
- package/dist/esm/start/airtable/dispatch.js +483 -0
- package/dist/esm/start/airtable/formulas.d.ts +70 -0
- package/dist/esm/start/airtable/formulas.js +260 -0
- package/dist/esm/start/airtable/index.d.ts +8 -0
- package/dist/esm/start/airtable/index.js +54 -0
- package/dist/esm/start/authHooks.d.ts +7 -0
- package/dist/esm/start/authHooks.js +10 -0
- package/dist/esm/start/authHooksModule.d.ts +1 -0
- package/dist/esm/start/authHooksModule.js +3 -0
- package/dist/esm/start/clientErrorMessage.test.d.ts +1 -0
- package/dist/esm/start/clientErrorMessage.test.js +105 -0
- package/dist/esm/start/credentials.d.ts +2 -0
- package/dist/esm/start/credentials.js +2 -0
- package/dist/esm/start/data/baseRunner.d.ts +92 -0
- package/dist/esm/start/data/baseRunner.js +83 -0
- package/dist/esm/start/data/dispatch.d.ts +16 -0
- package/dist/esm/start/data/dispatch.js +198 -0
- package/dist/esm/start/data/index.d.ts +15 -0
- package/dist/esm/start/data/index.js +58 -0
- package/dist/esm/start/data/sqlNameMappings.d.ts +58 -0
- package/dist/esm/start/data/sqlNameMappings.js +92 -0
- package/dist/esm/start/data/transformations.d.ts +97 -0
- package/dist/esm/start/data/transformations.js +262 -0
- package/dist/esm/start/data/types.d.ts +91 -0
- package/dist/esm/start/data/types.js +14 -0
- package/dist/esm/start/describe.d.ts +42 -5
- package/dist/esm/start/describe.js +77 -23
- package/dist/esm/start/entries.d.ts +10 -4
- package/dist/esm/start/entries.js +21 -5
- package/dist/esm/start/errors.d.ts +63 -0
- package/dist/esm/start/errors.js +146 -0
- package/dist/esm/start/errors.test.d.ts +1 -0
- package/dist/esm/start/errors.test.js +23 -0
- package/dist/esm/start/factories.test-d.d.ts +2 -0
- package/dist/esm/start/factories.test-d.js +20 -0
- package/dist/esm/start/host.d.ts +2 -2
- package/dist/esm/start/index.d.ts +32 -27
- package/dist/esm/start/index.js +79 -47
- package/dist/esm/start/instance.d.ts +4 -4
- package/dist/esm/start/instance.js +54 -11
- package/dist/esm/start/outbound.d.ts +11 -0
- package/dist/esm/start/outbound.js +400 -0
- package/dist/esm/start/previewClaim.d.ts +7 -0
- package/dist/esm/start/previewClaim.js +23 -0
- package/dist/esm/start/problems.js +1 -1
- package/dist/esm/start/quiet.d.ts +2 -0
- package/dist/esm/start/quiet.js +27 -0
- package/dist/esm/start/redactSecrets.d.ts +15 -0
- package/dist/esm/start/redactSecrets.js +154 -0
- package/dist/esm/start/redactSecrets.test.d.ts +1 -0
- package/dist/esm/start/redactSecrets.test.js +151 -0
- package/dist/esm/start/registration.d.ts +13 -0
- package/dist/esm/start/registration.js +21 -0
- package/dist/esm/start/registrationHash.d.ts +22 -0
- package/dist/esm/start/registrationHash.js +470 -0
- package/dist/esm/start/router.d.ts +25 -4
- package/dist/esm/start/router.js +169 -11
- package/dist/esm/start/runLog.d.ts +7 -4
- package/dist/esm/start/runLog.js +64 -6
- package/dist/esm/start/scope.d.ts +4 -4
- package/dist/esm/start/server.d.ts +40 -36
- package/dist/esm/start/server.js +322 -49
- package/dist/esm/start/steps.d.ts +28 -0
- package/dist/esm/start/steps.js +97 -0
- package/dist/esm/start/types.d.ts +179 -6
- package/dist/esm/start/version.d.ts +1 -0
- package/dist/esm/start/version.js +2 -0
- package/dist/esm/start/vite.js +91 -14
- package/dist/esm/start/worker.d.ts +6 -0
- package/dist/esm/start/worker.js +12 -0
- package/dist/esm/start/workflow.d.ts +46 -12
- package/dist/esm/start/workflow.js +10 -3
- package/dist/esm/start/workflow.test-d.js +50 -8
- package/dist/esm/start/workflowModules.js +1 -1
- package/dist/esm/start/workflowRun.d.ts +26 -8
- package/dist/esm/start/workflowRun.js +39 -8
- package/dist/esm/steps/index.d.ts +78 -0
- package/dist/esm/steps/index.js +502 -0
- package/dist/esm/steps/index.test.d.ts +1 -0
- package/dist/esm/steps/index.test.js +633 -0
- package/dist/esm/sync/index.js +2 -1
- package/dist/esm/sync/lib.d.ts +10 -3
- package/dist/esm/sync/lib.js +44 -25
- package/dist/esm/sync/lib.test.js +116 -36
- package/dist/esm/types/fields.d.ts +8 -1
- package/dist/esm/types/fields.js +6 -0
- package/dist/esm/types/tables.d.ts +16 -0
- package/dist/esm/upload/index.js +12 -2
- package/dist/esm/upload/index.test.js +39 -0
- package/dist/esm/vite/index.js +8 -3
- package/dist/esm/vite/index.test.js +10 -2
- package/package.json +37 -16
- package/dist/cjs/start/problems.d.ts +0 -19
- package/dist/cjs/start/problems.js +0 -11
package/dist/esm/start/server.js
CHANGED
|
@@ -1,46 +1,169 @@
|
|
|
1
|
+
// For the generated server entry only. Apps never import this.
|
|
2
|
+
import { createServerEntry } from "@tanstack/react-start/server";
|
|
3
|
+
import { createSsrRpc } from "@tanstack/react-start/ssr-rpc";
|
|
4
|
+
import { runWithStartContext } from "@tanstack/start-storage-context";
|
|
5
|
+
import { asZiteError, isZiteErrorCode, ZiteError, ZITE_ERROR_STATUS } from "./errors.js";
|
|
1
6
|
import { describeApp } from "./describe.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
7
|
+
import { runRegistration } from "./registration.js";
|
|
8
|
+
import { isAuthHookName, loadAuthHooks } from "./authHooks.js";
|
|
9
|
+
import { errorOf, preview } from "./runLog.js";
|
|
10
|
+
import { DATA_INTEGRATION_ID, dataContextOf, runDataCall } from "./data/index.js";
|
|
11
|
+
import { airtableSettingsOf, runAirtableCall } from "./airtable/index.js";
|
|
12
|
+
import { withoutConsole } from "./quiet.js";
|
|
13
|
+
import { createOutboundFetch, rememberConnection } from "./outbound.js";
|
|
14
|
+
import { INTEGRATIONS_PLATFORM_ID } from "./credentials.js";
|
|
15
|
+
import { getHost, requireScope, runInScope, runWithHost } from "./scope.js";
|
|
16
|
+
import { ZITEJS_VERSION } from "./version.js";
|
|
17
|
+
import { loadUnfinishedWorkflows, loadWorkflows, loggedInput, runWorkflow } from "./workflowRun.js";
|
|
5
18
|
export { runWithHost } from "./scope.js";
|
|
6
19
|
export { describeApp } from "./describe.js";
|
|
7
20
|
/**
|
|
8
|
-
* Routes every zitejs data, integration and email call
|
|
9
|
-
* inside an access scope. The access kind
|
|
10
|
-
* can record what a page read and
|
|
21
|
+
* Routes every zitejs data, integration and email call to this request's
|
|
22
|
+
* platform, on one session, and only inside an access scope. The access kind
|
|
23
|
+
* travels with the call so the platform can record what a page read and narrow
|
|
24
|
+
* anonymous reads.
|
|
11
25
|
*/
|
|
12
|
-
export function installPlatformTransport(
|
|
13
|
-
const sdkCall = (integrationId, className, methodName, params) => {
|
|
26
|
+
export function installPlatformTransport() {
|
|
27
|
+
const sdkCall = async (integrationId, className, methodName, params) => {
|
|
14
28
|
const scope = requireScope(`${className}.${methodName}`);
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
29
|
+
const host = getHost();
|
|
30
|
+
const getsConnection = integrationId === INTEGRATIONS_PLATFORM_ID && methodName === "get";
|
|
31
|
+
const name = String(params?.name ?? "");
|
|
32
|
+
// Fails closed: no platform means no platform access, never a fallback.
|
|
33
|
+
if (!host?.platform)
|
|
34
|
+
throw new Error("The Zite platform binding is missing");
|
|
35
|
+
host.session ??= Promise.resolve(host.platform.session());
|
|
36
|
+
const session = await host.session;
|
|
37
|
+
if (integrationId === DATA_INTEGRATION_ID) {
|
|
38
|
+
const found = await dataContextOf(session);
|
|
39
|
+
return recordCall(host, { integrationId, className, methodName, params }, () => runDataCall(session, found, host.mode, methodName, params));
|
|
40
|
+
}
|
|
41
|
+
if (!integrationId.startsWith("__")) {
|
|
42
|
+
const airtable = await airtableSettingsOf(session, integrationId);
|
|
43
|
+
if (airtable) {
|
|
44
|
+
return recordCall(host, { integrationId, className, methodName, params }, () => runAirtableCall(host, session, integrationId, airtable, methodName, params, scope.kind));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const result = await session.call({ integrationId, className, methodName, params, access: scope.kind });
|
|
48
|
+
if (getsConnection)
|
|
49
|
+
return connectionAnswer(host, name, result);
|
|
50
|
+
if ("value" in result)
|
|
51
|
+
return result.value;
|
|
52
|
+
const { code, message, userFacingMessage } = result.error;
|
|
53
|
+
throw new ZiteError({ code: isZiteErrorCode(code) ? code : "INTERNAL_ERROR", message, userFacingMessage });
|
|
24
54
|
};
|
|
25
55
|
globalThis.__wrapSdkCall = sdkCall;
|
|
56
|
+
watchOutboundFetches();
|
|
26
57
|
}
|
|
58
|
+
/** `integrations.get`'s answer, whose values then name the calls made with them. */
|
|
59
|
+
const connectionAnswer = (host, name, result) => {
|
|
60
|
+
if ("value" in result) {
|
|
61
|
+
rememberConnection(host, name, result.value);
|
|
62
|
+
return result.value;
|
|
63
|
+
}
|
|
64
|
+
const { code, message, userFacingMessage } = result.error;
|
|
65
|
+
throw new ZiteError({ code: isZiteErrorCode(code) ? code : "INTERNAL_ERROR", message, userFacingMessage });
|
|
66
|
+
};
|
|
67
|
+
/** A data call the app made itself, recorded as the host recorded the ones it made. */
|
|
68
|
+
const recordCall = async (host, call, run) => {
|
|
69
|
+
const at = Date.now();
|
|
70
|
+
const record = {
|
|
71
|
+
integrationId: call.integrationId,
|
|
72
|
+
className: call.className,
|
|
73
|
+
methodName: call.methodName,
|
|
74
|
+
at,
|
|
75
|
+
inputs: preview(call.params),
|
|
76
|
+
};
|
|
77
|
+
try {
|
|
78
|
+
const value = await run();
|
|
79
|
+
(host.calls ??= []).push({ ...record, durationMs: Date.now() - at, outputs: preview(value) });
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
const { code, message } = errorOf(error);
|
|
84
|
+
(host.calls ??= []).push({ ...record, durationMs: Date.now() - at, error: { code, message } });
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
// Keyed on globalThis so two copies of zitejs in one bundle wrap fetch once.
|
|
89
|
+
const WATCHED_KEY = Symbol.for("zitejs:outbound-fetch");
|
|
90
|
+
// Next patches fetch for the same reason: the run log must hear of each.
|
|
91
|
+
const watchOutboundFetches = () => {
|
|
92
|
+
const marks = globalThis;
|
|
93
|
+
if (marks[WATCHED_KEY])
|
|
94
|
+
return;
|
|
95
|
+
marks[WATCHED_KEY] = true;
|
|
96
|
+
globalThis.fetch = createOutboundFetch(globalThis.fetch.bind(globalThis));
|
|
97
|
+
};
|
|
27
98
|
const decodeUser = (value) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0))));
|
|
28
|
-
|
|
29
|
-
|
|
99
|
+
const INVOKE_KINDS = new Set(["webhook", "describe", "workflow", "register", "warm", "authHook", "function"]);
|
|
100
|
+
// What a request without props may ask for: neither runs app code on anyone's behalf.
|
|
101
|
+
const UNHOSTED_INVOKE_KINDS = new Set(["warm", "describe"]);
|
|
102
|
+
/** What the host dispatched this request with. Headers are ignored: props are the only thing it alone can set. */
|
|
103
|
+
export function hostContextFromProps(request, props) {
|
|
104
|
+
return {
|
|
105
|
+
requestId: props.requestId,
|
|
106
|
+
url: request.url,
|
|
107
|
+
user: props.user,
|
|
108
|
+
mode: props.mode,
|
|
109
|
+
invoke: props.invoke,
|
|
110
|
+
appUrl: props.appUrl,
|
|
111
|
+
baseId: props.baseId,
|
|
112
|
+
previewClaim: props.previewClaim,
|
|
113
|
+
env: props.env,
|
|
114
|
+
envConnections: props.envConnections,
|
|
115
|
+
runRoot: props.runRoot,
|
|
116
|
+
runs: [],
|
|
117
|
+
platform: props.platform,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
// Classic sets these per run. Node and workerd both refuse getters on process.env, so each request writes what the
|
|
121
|
+
// host sent, which is the same for every request a build serves: the live URL even on a demo.
|
|
122
|
+
// The connection vars the last request set, so one gone since (an integration removed) doesn't linger.
|
|
123
|
+
let connectionEnvKeys = new Set();
|
|
124
|
+
const setRequestEnv = ({ appUrl, baseId, env: connectionEnv }) => {
|
|
125
|
+
const env = globalThis.process?.env;
|
|
126
|
+
if (!env)
|
|
127
|
+
return;
|
|
128
|
+
if (appUrl)
|
|
129
|
+
env.ZITE_APP_URL = appUrl;
|
|
130
|
+
if (baseId)
|
|
131
|
+
env.ZITE_BASE_ID = baseId;
|
|
132
|
+
if (!connectionEnv)
|
|
133
|
+
return;
|
|
134
|
+
for (const key of connectionEnvKeys)
|
|
135
|
+
if (!Object.hasOwn(connectionEnv, key))
|
|
136
|
+
delete env[key];
|
|
137
|
+
for (const [key, value] of Object.entries(connectionEnv)) {
|
|
138
|
+
if (key.startsWith("ZITE_"))
|
|
139
|
+
env[key] = value;
|
|
140
|
+
}
|
|
141
|
+
connectionEnvKeys = new Set(Object.keys(connectionEnv));
|
|
142
|
+
};
|
|
143
|
+
/**
|
|
144
|
+
* A request the host didn't dispatch: the host's warm-up, `zitejs describe` under `vite preview`, and tests. Only the
|
|
145
|
+
* host can set props, so without them a build answers warm and describe and nobody is signed in. An entry that passes
|
|
146
|
+
* its own platform (tests, local dev) owns its requests and may say who is calling in `x-zite-*` headers.
|
|
147
|
+
*/
|
|
148
|
+
export function hostContextFromRequest(request, platform) {
|
|
30
149
|
const { headers } = request;
|
|
31
|
-
const
|
|
150
|
+
const trusted = platform !== undefined;
|
|
151
|
+
const user = trusted ? headers.get("x-zite-user") : null;
|
|
32
152
|
const [kind, name = ""] = headers.get("x-zite-invoke")?.split(":") ?? [];
|
|
153
|
+
const kinds = trusted ? INVOKE_KINDS : UNHOSTED_INVOKE_KINDS;
|
|
33
154
|
return {
|
|
34
|
-
requestId: headers.get("x-zite-request-id")
|
|
155
|
+
requestId: (trusted && headers.get("x-zite-request-id")) || crypto.randomUUID(),
|
|
35
156
|
url: request.url,
|
|
36
157
|
user: user ? decodeUser(user) : null,
|
|
37
|
-
|
|
158
|
+
mode: "live",
|
|
159
|
+
invoke: kinds.has(kind) ? { kind: kind, name } : null,
|
|
38
160
|
runs: [],
|
|
161
|
+
platform,
|
|
39
162
|
};
|
|
40
163
|
}
|
|
41
164
|
/** Every server function TanStack compiled, written in by `zite()` at build. Empty in dev, where TanStack doesn't call its id hook. */
|
|
42
165
|
export const builtFunctionIds = () => "__ZITE_FN_IDS__".split(",").filter((id) => id && !id.startsWith("__ZITE"));
|
|
43
|
-
const
|
|
166
|
+
const parseBuiltJson = (json) => {
|
|
44
167
|
try {
|
|
45
168
|
return JSON.parse(json);
|
|
46
169
|
}
|
|
@@ -49,17 +172,54 @@ const parseDescriptions = (json) => {
|
|
|
49
172
|
}
|
|
50
173
|
};
|
|
51
174
|
/** Each server function's `description` option, written in by `zite()` at build. */
|
|
52
|
-
export const builtFunctionDescriptions = () =>
|
|
175
|
+
export const builtFunctionDescriptions = () => parseBuiltJson("__ZITE_FN_DESCRIPTIONS__");
|
|
176
|
+
/** Each route's file, by route id, written in by `zite()` at build. */
|
|
177
|
+
export const builtRouteFiles = () => parseBuiltJson("__ZITE_ROUTE_FILES__");
|
|
178
|
+
/** Each provider trigger's registration hash, by automation id, written in by `zite()` at build from its source. */
|
|
179
|
+
export const builtRegistrationHashes = () => parseBuiltJson("__ZITE_REGISTRATION_HASHES__");
|
|
53
180
|
// Server functions also run while a streamed page renders, so the run log is
|
|
54
|
-
// complete only once the body
|
|
181
|
+
// complete only once the body ends: read to the end, cancelled by the reader or
|
|
182
|
+
// failed. A TransformStream's flush hears only the first.
|
|
55
183
|
const onBodyEnd = (response, done) => {
|
|
56
184
|
if (!response.body) {
|
|
57
185
|
done();
|
|
58
186
|
return response;
|
|
59
187
|
}
|
|
60
|
-
|
|
188
|
+
const reader = response.body.getReader();
|
|
189
|
+
let ended = false;
|
|
190
|
+
const end = () => {
|
|
191
|
+
if (ended)
|
|
192
|
+
return;
|
|
193
|
+
ended = true;
|
|
194
|
+
done();
|
|
195
|
+
};
|
|
196
|
+
const body = new ReadableStream({
|
|
197
|
+
async pull(controller) {
|
|
198
|
+
try {
|
|
199
|
+
const { done: finished, value } = await reader.read();
|
|
200
|
+
if (finished) {
|
|
201
|
+
end();
|
|
202
|
+
controller.close();
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
controller.enqueue(value);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
end();
|
|
210
|
+
controller.error(error);
|
|
211
|
+
}
|
|
212
|
+
},
|
|
213
|
+
cancel(reason) {
|
|
214
|
+
end();
|
|
215
|
+
return reader.cancel(reason);
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
return new Response(body, response);
|
|
61
219
|
};
|
|
62
220
|
const INVOKE_PATH = "/_zite/invoke";
|
|
221
|
+
/** On describe's answer: the zitejs this build's server code was bundled from. */
|
|
222
|
+
export const RUNTIME_VERSION_HEADER = "x-zitejs-version";
|
|
63
223
|
// The host sends `{ input }`; a platform-fired run's input carries the runner's
|
|
64
224
|
// `__cron`, `__poll` or `__webhook` state, exactly as for classic endpoints.
|
|
65
225
|
async function invokeWorkflow(request, host, workflows) {
|
|
@@ -71,7 +231,7 @@ async function invokeWorkflow(request, host, workflows) {
|
|
|
71
231
|
return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `No workflow named ${name}` } }, { status: 404 });
|
|
72
232
|
const input = (await request.json().catch(() => ({})))?.input;
|
|
73
233
|
const startedAt = Date.now();
|
|
74
|
-
const result = await runWorkflow(found.workflow, input);
|
|
234
|
+
const result = await runWorkflow(found.workflow, input, { resuming: host.runRoot !== undefined });
|
|
75
235
|
host.runs.push({
|
|
76
236
|
fn: `workflow:${found.id}`,
|
|
77
237
|
name: found.id,
|
|
@@ -80,47 +240,160 @@ async function invokeWorkflow(request, host, workflows) {
|
|
|
80
240
|
durationMs: Date.now() - startedAt,
|
|
81
241
|
input: preview(loggedInput(input)),
|
|
82
242
|
...(result.ok ? { output: preview(result.output) } : { error: result.error }),
|
|
243
|
+
...(result.steps ? { steps: result.steps } : {}),
|
|
244
|
+
...(!result.ok && result.failedStep !== undefined ? { failedStep: result.failedStep } : {}),
|
|
83
245
|
});
|
|
84
246
|
return Response.json(result, { status: result.ok ? 200 : 500 });
|
|
85
247
|
}
|
|
248
|
+
// The host sends `{ input }`, an editor's test run of a server function. It runs
|
|
249
|
+
// as a call from a page would on the server: its own middleware decides access
|
|
250
|
+
// for the user the host dispatched with, validates the input and records the run.
|
|
251
|
+
async function invokeFunction(request, options) {
|
|
252
|
+
if (request.method !== "POST" || new URL(request.url).pathname !== INVOKE_PATH)
|
|
253
|
+
return new Response("Not found", { status: 404 });
|
|
254
|
+
const id = getHost()?.invoke?.name ?? "";
|
|
255
|
+
if (!builtFunctionIds().includes(id)) {
|
|
256
|
+
return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `No server function ${id}` } }, { status: 404 });
|
|
257
|
+
}
|
|
258
|
+
const input = (await request.json().catch(() => ({})))?.input;
|
|
259
|
+
const startContext = {
|
|
260
|
+
request,
|
|
261
|
+
getRouter: options.getRouter,
|
|
262
|
+
startOptions: (await options.startInstance.getOptions()) ?? {},
|
|
263
|
+
executedRequestMiddlewares: new Set(),
|
|
264
|
+
contextAfterGlobalMiddlewares: {},
|
|
265
|
+
handlerType: "serverFn",
|
|
266
|
+
};
|
|
267
|
+
// In TanStack's request event too, which the function's own status setting reads.
|
|
268
|
+
return createServerEntry({
|
|
269
|
+
fetch: async () => {
|
|
270
|
+
try {
|
|
271
|
+
const answer = (await runWithStartContext(startContext, () => createSsrRpc(id)({ data: input, context: {} })));
|
|
272
|
+
if ("error" in answer)
|
|
273
|
+
throw answer.error;
|
|
274
|
+
return Response.json({ ok: true, output: answer.result ?? null });
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
return Response.json({ ok: false, error: errorOf(error) }, { status: 500 });
|
|
278
|
+
}
|
|
279
|
+
},
|
|
280
|
+
}).fetch(request, undefined);
|
|
281
|
+
}
|
|
282
|
+
// The host sends `{ op, input }`: `subscribe` with the platform's notification
|
|
283
|
+
// URL and secret, or `unsubscribe` with what `subscribe` returned.
|
|
284
|
+
async function invokeRegistration(request, host, workflows) {
|
|
285
|
+
if (request.method !== "POST" || new URL(request.url).pathname !== INVOKE_PATH)
|
|
286
|
+
return new Response("Not found", { status: 404 });
|
|
287
|
+
const name = host.invoke?.name ?? "";
|
|
288
|
+
const body = (await request.json().catch(() => null));
|
|
289
|
+
const result = await runRegistration(workflows, name, body?.op, body?.input);
|
|
290
|
+
if (!result) {
|
|
291
|
+
return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `${name} has no ${String(body?.op)}` } }, { status: 404 });
|
|
292
|
+
}
|
|
293
|
+
return Response.json(result, { status: result.ok ? 200 : 500 });
|
|
294
|
+
}
|
|
295
|
+
// The host sends `{ input }`, the same fields classic hooks get. A hook runs as
|
|
296
|
+
// a workflow does: no user, and the app's data and integrations through its platform.
|
|
297
|
+
async function invokeAuthHook(request, host) {
|
|
298
|
+
if (request.method !== "POST" || new URL(request.url).pathname !== INVOKE_PATH)
|
|
299
|
+
return new Response("Not found", { status: 404 });
|
|
300
|
+
const name = host.invoke?.name ?? "";
|
|
301
|
+
const hook = isAuthHookName(name) ? (await loadAuthHooks())[name] : undefined;
|
|
302
|
+
if (!hook) {
|
|
303
|
+
return Response.json({ ok: false, error: { code: "NOT_FOUND", message: `No auth hook named ${name}` } }, { status: 404 });
|
|
304
|
+
}
|
|
305
|
+
const input = (await request.json().catch(() => ({})))?.input ?? {};
|
|
306
|
+
const startedAt = Date.now();
|
|
307
|
+
try {
|
|
308
|
+
const output = await runInScope({ kind: "workflow", user: null }, () => hook(input));
|
|
309
|
+
host.runs.push({ fn: `authHook:${name}`, name, nested: false, startedAt, durationMs: Date.now() - startedAt, input: preview(input), output: preview(output) });
|
|
310
|
+
return Response.json({ ok: true, output: output ?? null });
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
const failed = errorOf(error);
|
|
314
|
+
host.runs.push({ fn: `authHook:${name}`, name, nested: false, startedAt, durationMs: Date.now() - startedAt, input: preview(input), error: failed });
|
|
315
|
+
return Response.json({ ok: false, error: failed }, { status: 500 });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
// TanStack renders any loader error as a 500. A page refused with a ZiteError
|
|
319
|
+
// (a missing role, a record that isn't there) answers with that error's status.
|
|
320
|
+
const pageStatus = (host) => {
|
|
321
|
+
const matches = host.router?.state?.matches;
|
|
322
|
+
const failed = asZiteError(matches?.find((match) => match.status === "error")?.error);
|
|
323
|
+
return failed ? ZITE_ERROR_STATUS[failed.code] : undefined;
|
|
324
|
+
};
|
|
86
325
|
/**
|
|
87
|
-
* The
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
326
|
+
* The handlers of a Start app's server entry. A request the host dispatched
|
|
327
|
+
* carries its identity and platform in props; anything else (describe under
|
|
328
|
+
* `vite preview`, tests) reads `x-zite-*` headers and uses `platform` if one
|
|
329
|
+
* is given.
|
|
91
330
|
*/
|
|
92
|
-
export function
|
|
93
|
-
|
|
94
|
-
// Fails closed: no binding means no platform access, never a fallback.
|
|
95
|
-
const platform = () => {
|
|
96
|
-
if (!binding)
|
|
97
|
-
throw new Error("The Zite platform binding is missing");
|
|
98
|
-
return binding;
|
|
99
|
-
};
|
|
100
|
-
installPlatformTransport((call) => platform().call(call));
|
|
331
|
+
export function createZiteHandlers(options) {
|
|
332
|
+
installPlatformTransport();
|
|
101
333
|
// Loaded on first use, so a page request never pays for importing workflow modules.
|
|
102
334
|
let workflows;
|
|
103
335
|
const loadedWorkflows = () => (workflows ??= loadWorkflows());
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
336
|
+
const serve = async (request, ctx) => {
|
|
337
|
+
const host = ctx?.props?.platform
|
|
338
|
+
? hostContextFromProps(request, ctx.props)
|
|
339
|
+
: hostContextFromRequest(request, options.platform);
|
|
340
|
+
setRequestEnv(host);
|
|
341
|
+
// Starting this isolate was the point: the platform warms a build before its
|
|
342
|
+
// first visitors, and no app code runs.
|
|
343
|
+
if (host.invoke?.kind === "warm")
|
|
344
|
+
return new Response(null, { status: 204 });
|
|
345
|
+
if (host.invoke?.kind === "describe") {
|
|
107
346
|
return Response.json(await describeApp({
|
|
108
347
|
fnIds: builtFunctionIds(),
|
|
109
348
|
descriptions: builtFunctionDescriptions(),
|
|
349
|
+
routeFiles: builtRouteFiles(),
|
|
350
|
+
registrationHashes: builtRegistrationHashes(),
|
|
110
351
|
getRouter: options.getRouter,
|
|
111
352
|
request,
|
|
112
353
|
workflows: await loadedWorkflows(),
|
|
113
|
-
|
|
354
|
+
unfinishedWorkflows: await loadUnfinishedWorkflows(),
|
|
355
|
+
}), { headers: { [RUNTIME_VERSION_HEADER]: ZITEJS_VERSION } });
|
|
114
356
|
}
|
|
115
|
-
|
|
116
|
-
|
|
357
|
+
let response = await runWithHost(host, async () => host.invoke?.kind === "workflow"
|
|
358
|
+
? invokeWorkflow(request, host, await loadedWorkflows())
|
|
359
|
+
: host.invoke?.kind === "function"
|
|
360
|
+
? invokeFunction(request, options)
|
|
361
|
+
: host.invoke?.kind === "register"
|
|
362
|
+
? withoutConsole(async () => invokeRegistration(request, host, await loadedWorkflows()))
|
|
363
|
+
: host.invoke?.kind === "authHook"
|
|
364
|
+
? invokeAuthHook(request, host)
|
|
365
|
+
: options.handler.fetch(request));
|
|
366
|
+
const status = response.status === 500 ? pageStatus(host) : undefined;
|
|
367
|
+
if (status)
|
|
368
|
+
response = new Response(response.body, { status, headers: response.headers });
|
|
117
369
|
return onBodyEnd(response, () => {
|
|
118
|
-
|
|
370
|
+
const { platform } = host;
|
|
371
|
+
if ((!host.runs.length && !host.calls?.length && !host.fetches?.length && !host.pending?.length) || !platform)
|
|
119
372
|
return;
|
|
120
|
-
|
|
373
|
+
// On the request's session when it has one: one call, not another binding round trip.
|
|
374
|
+
const flushed = (async () => {
|
|
375
|
+
await Promise.all(host.pending ?? []);
|
|
376
|
+
if (!host.runs.length && !host.calls?.length && !host.fetches?.length)
|
|
377
|
+
return;
|
|
378
|
+
const batch = {
|
|
379
|
+
runs: host.runs,
|
|
380
|
+
...(host.calls?.length && { calls: host.calls }),
|
|
381
|
+
...(host.fetches?.length && { fetches: host.fetches }),
|
|
382
|
+
};
|
|
383
|
+
// Only a session takes fetches.
|
|
384
|
+
if (host.fetches?.length)
|
|
385
|
+
host.session ??= Promise.resolve(platform.session());
|
|
386
|
+
const session = host.session ? await host.session : undefined;
|
|
387
|
+
await (session ? session.runs(batch) : platform.runs(batch));
|
|
388
|
+
})().catch((error) => {
|
|
121
389
|
console.error("[zite] couldn't record runs", error);
|
|
122
390
|
});
|
|
123
|
-
|
|
391
|
+
ctx?.waitUntil(flushed);
|
|
124
392
|
});
|
|
125
393
|
};
|
|
394
|
+
return { fetch: (request, ...rest) => serve(request, rest[1]) };
|
|
395
|
+
}
|
|
396
|
+
/** The fetch handler alone, for the Node entry. */
|
|
397
|
+
export function createZiteFetch(options) {
|
|
398
|
+
return createZiteHandlers(options).fetch;
|
|
126
399
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ZiteStep } from "../backend/index.js";
|
|
2
|
+
/** What a workflow's handler gets as `step`. */
|
|
3
|
+
export type StartStep = Pick<ZiteStep, "run">;
|
|
4
|
+
export type StepLog = {
|
|
5
|
+
name: string;
|
|
6
|
+
status: "ran" | "memoized" | "failed";
|
|
7
|
+
durationMs?: number;
|
|
8
|
+
at: number;
|
|
9
|
+
};
|
|
10
|
+
type SdkCall = (integrationId: string, className: string, methodName: string, params: unknown) => Promise<unknown>;
|
|
11
|
+
export declare const STEP_RESULT_MAX_BYTES: number;
|
|
12
|
+
/**
|
|
13
|
+
* Each completed step's result is saved before the code after it runs, so a
|
|
14
|
+
* resumed run gets it back instead of running the step's side effects again.
|
|
15
|
+
* Only a resumed run reads saved results, once, at its first step.
|
|
16
|
+
*/
|
|
17
|
+
export declare function createSteps({ call, resuming, now }: {
|
|
18
|
+
call: SdkCall;
|
|
19
|
+
resuming: boolean;
|
|
20
|
+
now?: () => number;
|
|
21
|
+
}): {
|
|
22
|
+
step: StartStep;
|
|
23
|
+
log: StepLog[];
|
|
24
|
+
failedStep: () => string | undefined;
|
|
25
|
+
/** A step that throws inside `Promise.all` ends the run while its siblings still save. */
|
|
26
|
+
settle: () => Promise<void>;
|
|
27
|
+
};
|
|
28
|
+
export {};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
const STEPS_INTEGRATION_ID = "__steps__";
|
|
2
|
+
export const STEP_RESULT_MAX_BYTES = 256 * 1024;
|
|
3
|
+
const MAX_STEPS = 512;
|
|
4
|
+
const plain = (name, value) => {
|
|
5
|
+
let json;
|
|
6
|
+
try {
|
|
7
|
+
json = JSON.stringify(value);
|
|
8
|
+
}
|
|
9
|
+
catch (err) {
|
|
10
|
+
throw new Error(`step "${name}" returned a value that cannot be saved for retries: ${err instanceof Error ? err.message : String(err)}. Return plain JSON data from steps.`);
|
|
11
|
+
}
|
|
12
|
+
if (json === undefined)
|
|
13
|
+
return null;
|
|
14
|
+
if (new TextEncoder().encode(json).length > STEP_RESULT_MAX_BYTES) {
|
|
15
|
+
throw new Error(`step "${name}" returned more than ${STEP_RESULT_MAX_BYTES / 1024}KB. Store large data elsewhere and return a reference to it.`);
|
|
16
|
+
}
|
|
17
|
+
return JSON.parse(json);
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Each completed step's result is saved before the code after it runs, so a
|
|
21
|
+
* resumed run gets it back instead of running the step's side effects again.
|
|
22
|
+
* Only a resumed run reads saved results, once, at its first step.
|
|
23
|
+
*/
|
|
24
|
+
export function createSteps({ call, resuming, now = Date.now }) {
|
|
25
|
+
const seen = new Set();
|
|
26
|
+
const inFlight = new Set();
|
|
27
|
+
const log = [];
|
|
28
|
+
let failedStep;
|
|
29
|
+
let saved;
|
|
30
|
+
const savedResults = () => (saved ??= resuming
|
|
31
|
+
? call(STEPS_INTEGRATION_ID, "Steps", "load", {}).catch((err) => {
|
|
32
|
+
throw new Error(`Could not read this run's saved steps (${err instanceof Error ? err.message : String(err)}); nothing ran again. Resume it once more.`);
|
|
33
|
+
})
|
|
34
|
+
: Promise.resolve(Object.create(null)));
|
|
35
|
+
const failed = (name, err, startedAt) => {
|
|
36
|
+
failedStep ??= name;
|
|
37
|
+
log.push({ name, status: "failed", durationMs: now() - startedAt, at: now() });
|
|
38
|
+
return err;
|
|
39
|
+
};
|
|
40
|
+
const body = async (name, fn) => {
|
|
41
|
+
const startedAt = now();
|
|
42
|
+
let value;
|
|
43
|
+
try {
|
|
44
|
+
value = plain(name, await fn());
|
|
45
|
+
}
|
|
46
|
+
catch (err) {
|
|
47
|
+
throw failed(name, err, startedAt);
|
|
48
|
+
}
|
|
49
|
+
// Awaited before the step returns: a crash after this never repeats it.
|
|
50
|
+
try {
|
|
51
|
+
await call(STEPS_INTEGRATION_ID, "Steps", "persist", { name, value, durationMs: now() - startedAt });
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
throw failed(name, new Error(`Saving the result of step "${name}" failed (${err instanceof Error ? err.message : String(err)}). The step itself completed; nothing is wrong with the code — run again.`), startedAt);
|
|
55
|
+
}
|
|
56
|
+
log.push({ name, status: "ran", durationMs: now() - startedAt, at: now() });
|
|
57
|
+
return value;
|
|
58
|
+
};
|
|
59
|
+
const step = {
|
|
60
|
+
run: async (name, fn) => {
|
|
61
|
+
if (typeof name !== "string" || name.length === 0 || name.length > 255) {
|
|
62
|
+
throw new Error("step.run needs a stable name of 1 to 255 characters as its first argument");
|
|
63
|
+
}
|
|
64
|
+
if (seen.size >= MAX_STEPS)
|
|
65
|
+
throw new Error(`a run can take at most ${MAX_STEPS} steps — batch work inside fewer steps`);
|
|
66
|
+
if (typeof fn !== "function")
|
|
67
|
+
throw new Error(`step.run("${name}") needs a function as its second argument`);
|
|
68
|
+
if (seen.has(name)) {
|
|
69
|
+
throw new Error(`step.run was called twice with the name "${name}" in one run. Each step needs its own stable name so a retry can match saved results to steps.`);
|
|
70
|
+
}
|
|
71
|
+
seen.add(name);
|
|
72
|
+
const results = await savedResults();
|
|
73
|
+
if (Object.prototype.hasOwnProperty.call(results, name)) {
|
|
74
|
+
log.push({ name, status: "memoized", at: now() });
|
|
75
|
+
return results[name];
|
|
76
|
+
}
|
|
77
|
+
const settled = body(name, fn);
|
|
78
|
+
inFlight.add(settled);
|
|
79
|
+
try {
|
|
80
|
+
return (await settled);
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
inFlight.delete(settled);
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
return {
|
|
88
|
+
step,
|
|
89
|
+
log,
|
|
90
|
+
failedStep: () => failedStep,
|
|
91
|
+
/** A step that throws inside `Promise.all` ends the run while its siblings still save. */
|
|
92
|
+
settle: async () => {
|
|
93
|
+
if (inFlight.size > 0)
|
|
94
|
+
await Promise.allSettled([...inFlight]);
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|