@zerodot/apify 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +60 -2
- package/apify.svg +5 -0
- package/dist/index.cjs +1425 -0
- package/package.json +46 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1425 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let zod = require("zod");
|
|
3
|
+
let _zerodot_node_sdk = require("@zerodot/node-sdk");
|
|
4
|
+
let node_crypto = require("node:crypto");
|
|
5
|
+
// src/api.ts
|
|
6
|
+
const APIFY_API_CREDENTIAL = "apify.apiKey";
|
|
7
|
+
const APIFY_OAUTH2_CREDENTIAL = "apify.oauth2";
|
|
8
|
+
const APIFY_CONSOLE_URL = "https://console.apify.com";
|
|
9
|
+
/** The standby endpoint of the Web Fetch Actor. */
|
|
10
|
+
const WEB_FETCH_URL = "https://web-fetch.apify.actor";
|
|
11
|
+
/** The states in which a run is over. */
|
|
12
|
+
const TERMINAL_RUN_STATUSES = [
|
|
13
|
+
"SUCCEEDED",
|
|
14
|
+
"FAILED",
|
|
15
|
+
"TIMED-OUT",
|
|
16
|
+
"ABORTED"
|
|
17
|
+
];
|
|
18
|
+
/** A dataset can be big and slow to send. */
|
|
19
|
+
const DATASET_TIMEOUT_MS = 6e5;
|
|
20
|
+
const WEB_FETCH_TIMEOUT_MS = 6e5;
|
|
21
|
+
/** Apify answers a Server Actor request with 504 after 300 seconds. Wait a little more. */
|
|
22
|
+
const SERVER_ACTOR_TIMEOUT_MS = 31e4;
|
|
23
|
+
/** Extra time after the timeout of the run, while the node waits for the run to end. */
|
|
24
|
+
const POLL_BUFFER_MS = 3e5;
|
|
25
|
+
/** The longest wait for a run that has no timeout of its own. */
|
|
26
|
+
const POLL_MAX_MS = 864e5;
|
|
27
|
+
/** The most tries of one call. Wait 1, 2, 4, and 8 seconds between tries. */
|
|
28
|
+
const TRIES = 5;
|
|
29
|
+
const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : null;
|
|
30
|
+
const isObject$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
31
|
+
/** The token of a credential: an API token or the access token of an OAuth2 sign-in. */
|
|
32
|
+
function apifyAccess(credential) {
|
|
33
|
+
if (credential?.type === "apify.apiKey") {
|
|
34
|
+
const token = text(credential.data.apiKey);
|
|
35
|
+
if (!token) throw new Error("The credential has no \"apiKey\"");
|
|
36
|
+
return { token };
|
|
37
|
+
}
|
|
38
|
+
if (credential?.type === "apify.oauth2") {
|
|
39
|
+
const token = text(credential.data.accessToken);
|
|
40
|
+
if (!token) throw new Error("The Apify credential is not connected to an account yet");
|
|
41
|
+
return { token };
|
|
42
|
+
}
|
|
43
|
+
throw new Error("The node needs an Apify credential");
|
|
44
|
+
}
|
|
45
|
+
/** An error that Apify gave, or an error of the node. */
|
|
46
|
+
var ApifyError = class extends Error {
|
|
47
|
+
status;
|
|
48
|
+
/** The `type` of the error that Apify gave, such as `unknown-build-tag`. */
|
|
49
|
+
type;
|
|
50
|
+
data;
|
|
51
|
+
constructor(message, status, type, data) {
|
|
52
|
+
super(message);
|
|
53
|
+
this.name = "ApifyError";
|
|
54
|
+
this.status = status;
|
|
55
|
+
this.type = type;
|
|
56
|
+
this.data = data;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
/** Short help for the statuses that people see most. */
|
|
60
|
+
const HINTS = {
|
|
61
|
+
401: "Apify did not accept the token",
|
|
62
|
+
402: "The account has no credit or no plan for this call",
|
|
63
|
+
403: "The token cannot use this resource",
|
|
64
|
+
404: "Apify did not find the resource. Check the IDs",
|
|
65
|
+
429: "Apify limits the requests. Try again later"
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* The message and the type in an error body. Apify gives `{ error: { type, message } }`. Web Fetch
|
|
69
|
+
* gives `{ error, code }`. Some answers have `{ message }` or plain text.
|
|
70
|
+
*/
|
|
71
|
+
function errorFromBody(answer) {
|
|
72
|
+
if (typeof answer === "string") return { message: text(answer)?.slice(0, 1e3) ?? void 0 };
|
|
73
|
+
if (!isObject$2(answer)) return {};
|
|
74
|
+
const body = answer;
|
|
75
|
+
const detail = isObject$2(body.error) ? body.error : {};
|
|
76
|
+
const message = text(detail.message) ?? text(body.error) ?? text(body.message) ?? text(answer.detail);
|
|
77
|
+
const type = text(detail.type) ?? text(body.code);
|
|
78
|
+
return {
|
|
79
|
+
message: message?.slice(0, 1e3),
|
|
80
|
+
type: type ?? void 0
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** The error for an answer with an error status. The text never has the token. */
|
|
84
|
+
function apifyErrorOf(label, status, answer) {
|
|
85
|
+
const { message, type } = errorFromBody(answer);
|
|
86
|
+
const parts = [`Apify ${label} failed (${status})`];
|
|
87
|
+
if (message) parts.push(message);
|
|
88
|
+
const hint = HINTS[status];
|
|
89
|
+
if (hint) parts.push(hint);
|
|
90
|
+
return new ApifyError(parts.join(". "), status, type, answer);
|
|
91
|
+
}
|
|
92
|
+
/** An ID or a key in a path is one segment. `.` and `..` are never valid. */
|
|
93
|
+
function segment(value, name) {
|
|
94
|
+
const clean = value.trim();
|
|
95
|
+
if (clean === "" || clean === "." || clean === "..") throw new Error(`Apify: "${name}" is not valid`);
|
|
96
|
+
return encodeURIComponent(clean);
|
|
97
|
+
}
|
|
98
|
+
/** The token goes only to the API of Apify and to the hosts of Actors. */
|
|
99
|
+
function checkOrigin(origin) {
|
|
100
|
+
const url = new URL(origin);
|
|
101
|
+
if (!(url.origin === "https://api.apify.com" || url.protocol === "https:" && url.hostname.endsWith(".apify.actor"))) throw new Error("Apify: the token can go only to api.apify.com or an Actor host");
|
|
102
|
+
return url;
|
|
103
|
+
}
|
|
104
|
+
/** The full address of a call. A value that is undefined or empty is not sent. */
|
|
105
|
+
function urlOf(call) {
|
|
106
|
+
const base = checkOrigin(call.origin ?? "https://api.apify.com");
|
|
107
|
+
if (call.path.includes("\\") || call.path.startsWith("//") || !call.path.startsWith("/")) throw new Error("Apify: the path is not valid");
|
|
108
|
+
const url = new URL(call.path, base.origin);
|
|
109
|
+
if (url.origin !== base.origin || url.pathname.startsWith("//")) throw new Error("Apify: the path is not valid");
|
|
110
|
+
checkOrigin(url.origin);
|
|
111
|
+
for (const [key, value] of Object.entries(call.query ?? {})) {
|
|
112
|
+
if (value === void 0 || value === "") continue;
|
|
113
|
+
url.searchParams.set(key, String(value));
|
|
114
|
+
}
|
|
115
|
+
return url;
|
|
116
|
+
}
|
|
117
|
+
/** Waits. It stops with an error when the signal aborts. */
|
|
118
|
+
const defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
119
|
+
if (signal.aborted) return reject(signal.reason);
|
|
120
|
+
const timer = setTimeout(() => {
|
|
121
|
+
signal.removeEventListener("abort", onAbort);
|
|
122
|
+
resolve();
|
|
123
|
+
}, ms);
|
|
124
|
+
const onAbort = () => {
|
|
125
|
+
clearTimeout(timer);
|
|
126
|
+
reject(signal.reason);
|
|
127
|
+
};
|
|
128
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
129
|
+
});
|
|
130
|
+
/** The label of a call for an error message. It has no ID and no query. */
|
|
131
|
+
const labelOf = (call) => `${call.method} ${call.path.split("/").slice(0, 3).join("/").replace(/^\/+/, "")}`;
|
|
132
|
+
/**
|
|
133
|
+
* One call with tries. It tries again after a 429 or a 5xx, and, for a GET, after a network
|
|
134
|
+
* error. It gives back the answer of each other status, so the caller can read it.
|
|
135
|
+
*/
|
|
136
|
+
async function sendApify(access, call, options) {
|
|
137
|
+
const url = urlOf(call);
|
|
138
|
+
const sleep = options.sleep ?? ((ms) => defaultSleep(ms, options.signal));
|
|
139
|
+
const tries = call.noRetry ? 1 : TRIES;
|
|
140
|
+
for (let attempt = 0;; attempt++) {
|
|
141
|
+
const last = attempt >= tries - 1;
|
|
142
|
+
try {
|
|
143
|
+
const response = await fetch(url, {
|
|
144
|
+
method: call.method,
|
|
145
|
+
headers: {
|
|
146
|
+
authorization: `Bearer ${access.token}`,
|
|
147
|
+
accept: "*/*",
|
|
148
|
+
"x-apify-integration-platform": "zerodot",
|
|
149
|
+
...call.body === void 0 ? {} : { "content-type": "application/json" }
|
|
150
|
+
},
|
|
151
|
+
body: call.body === void 0 ? void 0 : JSON.stringify(call.body),
|
|
152
|
+
redirect: "error",
|
|
153
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(call.timeoutMs ?? 6e4)])
|
|
154
|
+
});
|
|
155
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
156
|
+
const answer = {
|
|
157
|
+
status: response.status,
|
|
158
|
+
contentType: (response.headers.get("content-type") ?? "").split(";")[0]?.trim() ?? "",
|
|
159
|
+
bytes
|
|
160
|
+
};
|
|
161
|
+
if (!(response.status === 429 || response.status >= 500 && !call.retryRateLimitOnly) || last) return answer;
|
|
162
|
+
} catch (error) {
|
|
163
|
+
if (options.signal.aborted || call.method !== "GET" || last) throw error;
|
|
164
|
+
}
|
|
165
|
+
await sleep(1e3 * 2 ** attempt);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/** The body of an answer, as JSON when it is JSON. */
|
|
169
|
+
function decodeBody(answer) {
|
|
170
|
+
if (answer.bytes.length === 0) return null;
|
|
171
|
+
const content = new TextDecoder().decode(answer.bytes);
|
|
172
|
+
try {
|
|
173
|
+
return JSON.parse(content);
|
|
174
|
+
} catch {
|
|
175
|
+
return content;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/** An Actor that needs a permission approval gives a link. The message names the link. */
|
|
179
|
+
function approvalOf(error) {
|
|
180
|
+
if (error.type !== "full-permission-actor-not-approved") return error;
|
|
181
|
+
const body = isObject$2(error.data) ? error.data : {};
|
|
182
|
+
const detail = isObject$2(body.error) ? body.error : {};
|
|
183
|
+
const link = text(detail.data?.approvalUrl);
|
|
184
|
+
if (!link || !/^https?:\/\//.test(link)) return error;
|
|
185
|
+
return new ApifyError(`${error.message}. Approve the permissions of the Actor at ${link}, then run it again`, error.status, error.type, error.data);
|
|
186
|
+
}
|
|
187
|
+
/** One call that gives JSON. */
|
|
188
|
+
async function callApify(access, call, options) {
|
|
189
|
+
const answer = await sendApify(access, call, options);
|
|
190
|
+
const body = decodeBody(answer);
|
|
191
|
+
if (answer.status >= 400) throw approvalOf(apifyErrorOf(labelOf(call), answer.status, body));
|
|
192
|
+
return body;
|
|
193
|
+
}
|
|
194
|
+
/** The `data` of an Apify answer, such as the run of a run call. */
|
|
195
|
+
function dataOf(answer) {
|
|
196
|
+
const data = isObject$2(answer) ? answer.data : void 0;
|
|
197
|
+
return isObject$2(data) ? data : {};
|
|
198
|
+
}
|
|
199
|
+
/** Reads the run until it ends. The wait ends at the timeout of the run plus 5 minutes. */
|
|
200
|
+
async function pollRun(access, runId, options) {
|
|
201
|
+
const sleep = options.sleep ?? ((ms) => defaultSleep(ms, options.signal));
|
|
202
|
+
const now = options.now ?? Date.now;
|
|
203
|
+
const startedAt = now();
|
|
204
|
+
let limit = POLL_MAX_MS;
|
|
205
|
+
let checked = false;
|
|
206
|
+
for (;;) {
|
|
207
|
+
const run = dataOf(await callApify(access, {
|
|
208
|
+
method: "GET",
|
|
209
|
+
path: `/v2/actor-runs/${segment(runId, "runId")}`
|
|
210
|
+
}, options));
|
|
211
|
+
if (TERMINAL_RUN_STATUSES.includes(String(run.status))) return run;
|
|
212
|
+
if (!checked) {
|
|
213
|
+
const runOptions = isObject$2(run.options) ? run.options : {};
|
|
214
|
+
const seconds = Number(runOptions.timeoutSecs);
|
|
215
|
+
if (Number.isFinite(seconds) && seconds > 0) limit = seconds * 1e3 + POLL_BUFFER_MS;
|
|
216
|
+
checked = true;
|
|
217
|
+
}
|
|
218
|
+
const elapsed = now() - startedAt;
|
|
219
|
+
if (elapsed > limit) throw new ApifyError(`Timed out after ${Math.round(elapsed / 1e3)} seconds while it waited for run ${runId}. The last status was ${String(run.status ?? "unknown")}`);
|
|
220
|
+
await sleep(options.intervalMs ?? 1e3);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// src/icon.ts
|
|
224
|
+
const APIFY_ICON = (0, _zerodot_node_sdk.fileIcon)(require("url").pathToFileURL(__filename).href, "../apify.svg");
|
|
225
|
+
// src/credential.ts
|
|
226
|
+
const TIMEOUT_MS$1 = 1e4;
|
|
227
|
+
/** Apify sign-in. The client sends its ID and secret in a header. The flow uses PKCE. */
|
|
228
|
+
const APIFY_OAUTH2 = {
|
|
229
|
+
authUrl: "https://console.apify.com/authorize/oauth",
|
|
230
|
+
tokenUrl: "https://console-backend.apify.com/oauth/apps/token",
|
|
231
|
+
scopes: ["profile", "full_api_access"],
|
|
232
|
+
authentication: "header",
|
|
233
|
+
pkce: true
|
|
234
|
+
};
|
|
235
|
+
/** Fields that only the server writes, after the user connects the account. */
|
|
236
|
+
const OAUTH2_TOKEN_FIELDS = [
|
|
237
|
+
"accessToken",
|
|
238
|
+
"refreshToken",
|
|
239
|
+
"expiresAt",
|
|
240
|
+
"tokenType",
|
|
241
|
+
"grantedScope"
|
|
242
|
+
];
|
|
243
|
+
/** Asks Apify who the account is. A 401 throws with the text of Apify. */
|
|
244
|
+
async function check(credential) {
|
|
245
|
+
await callApify(apifyAccess(credential), {
|
|
246
|
+
method: "GET",
|
|
247
|
+
path: "/v2/users/me"
|
|
248
|
+
}, { signal: AbortSignal.timeout(TIMEOUT_MS$1) });
|
|
249
|
+
}
|
|
250
|
+
const apifyApiCredential = {
|
|
251
|
+
type: APIFY_API_CREDENTIAL,
|
|
252
|
+
label: "Apify API key",
|
|
253
|
+
fields: zod.z.object({
|
|
254
|
+
/** From Apify Console: Settings, API & Integrations. Apify shows a new token one time only. */
|
|
255
|
+
apiKey: zod.z.string().min(1).meta({ placeholder: "Your Apify API token" }) }),
|
|
256
|
+
secretFields: ["apiKey"],
|
|
257
|
+
icon: "Globe02Icon",
|
|
258
|
+
iconUrl: APIFY_ICON,
|
|
259
|
+
test: check
|
|
260
|
+
};
|
|
261
|
+
const apifyOAuth2Credential = {
|
|
262
|
+
type: APIFY_OAUTH2_CREDENTIAL,
|
|
263
|
+
label: "Apify OAuth2",
|
|
264
|
+
fields: zod.z.object({
|
|
265
|
+
clientId: zod.z.string().min(1),
|
|
266
|
+
/** A PKCE client can work without a secret. */
|
|
267
|
+
clientSecret: zod.z.string().min(1).optional(),
|
|
268
|
+
accessToken: zod.z.string().min(1).optional(),
|
|
269
|
+
refreshToken: zod.z.string().min(1).optional(),
|
|
270
|
+
/** ISO 8601 time. */
|
|
271
|
+
expiresAt: zod.z.iso.datetime().optional(),
|
|
272
|
+
tokenType: zod.z.string().min(1).optional(),
|
|
273
|
+
grantedScope: zod.z.string().optional()
|
|
274
|
+
}),
|
|
275
|
+
secretFields: [
|
|
276
|
+
"clientSecret",
|
|
277
|
+
"accessToken",
|
|
278
|
+
"refreshToken"
|
|
279
|
+
],
|
|
280
|
+
serverFields: [...OAUTH2_TOKEN_FIELDS],
|
|
281
|
+
oauth2: APIFY_OAUTH2,
|
|
282
|
+
icon: "Globe02Icon",
|
|
283
|
+
iconUrl: APIFY_ICON,
|
|
284
|
+
test: check
|
|
285
|
+
};
|
|
286
|
+
// src/config.ts
|
|
287
|
+
const AUTHENTICATIONS = ["apifyApi", "apifyOAuth2Api"];
|
|
288
|
+
const AUTHENTICATION_LABELS = {
|
|
289
|
+
apifyApi: "API Key",
|
|
290
|
+
apifyOAuth2Api: "OAuth2"
|
|
291
|
+
};
|
|
292
|
+
const RESOURCES = [
|
|
293
|
+
"actor",
|
|
294
|
+
"actorRun",
|
|
295
|
+
"actorTask",
|
|
296
|
+
"dataset",
|
|
297
|
+
"keyValueStore"
|
|
298
|
+
];
|
|
299
|
+
const OPERATIONS_OF = {
|
|
300
|
+
actor: [
|
|
301
|
+
"run",
|
|
302
|
+
"runAndGetDataset",
|
|
303
|
+
"sendServerActorRequest",
|
|
304
|
+
"webFetch",
|
|
305
|
+
"getLastRun"
|
|
306
|
+
],
|
|
307
|
+
actorRun: [
|
|
308
|
+
"get",
|
|
309
|
+
"getMany",
|
|
310
|
+
"getManyForActor",
|
|
311
|
+
"abort"
|
|
312
|
+
],
|
|
313
|
+
actorTask: ["run", "runAndGetDataset"],
|
|
314
|
+
dataset: ["getItems"],
|
|
315
|
+
keyValueStore: ["getRecord"]
|
|
316
|
+
};
|
|
317
|
+
const ALL_OPERATIONS = [...new Set(Object.values(OPERATIONS_OF).flat())];
|
|
318
|
+
const RUN_STATUSES = [
|
|
319
|
+
"ABORTED",
|
|
320
|
+
"ABORTING",
|
|
321
|
+
"FAILED",
|
|
322
|
+
"READY",
|
|
323
|
+
"RUNNING",
|
|
324
|
+
"SUCCEEDED",
|
|
325
|
+
"TIMED-OUT",
|
|
326
|
+
"TIMING-OUT"
|
|
327
|
+
];
|
|
328
|
+
const HTTP_METHODS = [
|
|
329
|
+
"GET",
|
|
330
|
+
"POST",
|
|
331
|
+
"PUT",
|
|
332
|
+
"PATCH",
|
|
333
|
+
"DELETE"
|
|
334
|
+
];
|
|
335
|
+
const WEB_FETCH_FORMATS = [
|
|
336
|
+
"html",
|
|
337
|
+
"links",
|
|
338
|
+
"markdown",
|
|
339
|
+
"raw",
|
|
340
|
+
"text"
|
|
341
|
+
];
|
|
342
|
+
const MEMORY_OPTIONS = [
|
|
343
|
+
"128",
|
|
344
|
+
"256",
|
|
345
|
+
"512",
|
|
346
|
+
"1024",
|
|
347
|
+
"2048",
|
|
348
|
+
"4096",
|
|
349
|
+
"8192",
|
|
350
|
+
"16384",
|
|
351
|
+
"32768"
|
|
352
|
+
];
|
|
353
|
+
const MEMORY_LABELS = {
|
|
354
|
+
"128": "128 MB",
|
|
355
|
+
"256": "256 MB",
|
|
356
|
+
"512": "512 MB",
|
|
357
|
+
"1024": "1024 MB (1 GB)",
|
|
358
|
+
"2048": "2048 MB (2 GB)",
|
|
359
|
+
"4096": "4096 MB (4 GB)",
|
|
360
|
+
"8192": "8192 MB (8 GB)",
|
|
361
|
+
"16384": "16384 MB (16 GB)",
|
|
362
|
+
"32768": "32768 MB (32 GB)"
|
|
363
|
+
};
|
|
364
|
+
/** Show a field for these operations of these resources. */
|
|
365
|
+
const on = (operations) => ({ showWhen: Object.entries(operations).map(([resource, ops]) => ({
|
|
366
|
+
resource: [resource],
|
|
367
|
+
operation: [...ops ?? []]
|
|
368
|
+
})) });
|
|
369
|
+
const runsActor = on({ actor: ["run", "runAndGetDataset"] });
|
|
370
|
+
const startsRun = on({
|
|
371
|
+
actor: ["run", "runAndGetDataset"],
|
|
372
|
+
actorTask: ["run", "runAndGetDataset"]
|
|
373
|
+
});
|
|
374
|
+
const waits = on({
|
|
375
|
+
actor: ["run"],
|
|
376
|
+
actorTask: ["run"]
|
|
377
|
+
});
|
|
378
|
+
const serverRequest = {
|
|
379
|
+
resource: ["actor"],
|
|
380
|
+
operation: ["sendServerActorRequest"]
|
|
381
|
+
};
|
|
382
|
+
const pagesRuns = on({ actorRun: ["getMany", "getManyForActor"] });
|
|
383
|
+
const pages = on({
|
|
384
|
+
actorRun: ["getMany", "getManyForActor"],
|
|
385
|
+
dataset: ["getItems"]
|
|
386
|
+
});
|
|
387
|
+
const RUN_STATUS_LABELS = Object.fromEntries(RUN_STATUSES.map((status) => [status, status]));
|
|
388
|
+
const apifyConfig = zod.z.object({
|
|
389
|
+
authentication: zod.z.enum(AUTHENTICATIONS).default("apifyApi").meta({
|
|
390
|
+
title: "Authentication",
|
|
391
|
+
description: "Choose which authentication method to use",
|
|
392
|
+
labels: AUTHENTICATION_LABELS,
|
|
393
|
+
hints: {
|
|
394
|
+
apifyApi: "Use an API token from Apify Console",
|
|
395
|
+
apifyOAuth2Api: "Sign in with an Apify account"
|
|
396
|
+
}
|
|
397
|
+
}),
|
|
398
|
+
resource: zod.z.enum(RESOURCES).default("actor").meta({
|
|
399
|
+
labels: {
|
|
400
|
+
actor: "Actor",
|
|
401
|
+
actorRun: "Actor Run",
|
|
402
|
+
actorTask: "Actor Task",
|
|
403
|
+
dataset: "Dataset",
|
|
404
|
+
keyValueStore: "Key-Value Store"
|
|
405
|
+
},
|
|
406
|
+
hints: {
|
|
407
|
+
actor: "Run an Actor, call a Server Actor, or fetch a web page",
|
|
408
|
+
actorRun: "Get or abort the runs of Actors",
|
|
409
|
+
actorTask: "Run a saved task of an Actor",
|
|
410
|
+
dataset: "Get the items of a dataset",
|
|
411
|
+
keyValueStore: "Get a record of a key-value store"
|
|
412
|
+
}
|
|
413
|
+
}),
|
|
414
|
+
operation: zod.z.enum(ALL_OPERATIONS).default("run").meta({
|
|
415
|
+
labels: {
|
|
416
|
+
run: "Run",
|
|
417
|
+
runAndGetDataset: "Run and Get Dataset",
|
|
418
|
+
sendServerActorRequest: "Send Server Actor Request",
|
|
419
|
+
webFetch: "Web Fetch",
|
|
420
|
+
getLastRun: "Get Last Run",
|
|
421
|
+
get: "Get",
|
|
422
|
+
getMany: "Get Many",
|
|
423
|
+
getManyForActor: "Get Many for Actor",
|
|
424
|
+
abort: "Abort",
|
|
425
|
+
getItems: "Get Items",
|
|
426
|
+
getRecord: "Get Record"
|
|
427
|
+
},
|
|
428
|
+
hints: {
|
|
429
|
+
run: "Run an Actor or a task, and get the run",
|
|
430
|
+
runAndGetDataset: "Run an Actor or a task, wait for it to finish, and get the dataset items",
|
|
431
|
+
sendServerActorRequest: "Send one HTTP request to a Server Actor, without a run. The request can cost money",
|
|
432
|
+
webFetch: "Get the content of one URL as markdown, HTML, text, links, or raw",
|
|
433
|
+
getLastRun: "Get the most recent run of an Actor",
|
|
434
|
+
get: "Get one run by its ID",
|
|
435
|
+
getMany: "Get the runs of the account",
|
|
436
|
+
getManyForActor: "Get the runs of one Actor",
|
|
437
|
+
abort: "Abort a run that is running",
|
|
438
|
+
getItems: "Get items from a dataset",
|
|
439
|
+
getRecord: "Get the value stored under a key"
|
|
440
|
+
}
|
|
441
|
+
}),
|
|
442
|
+
actorId: zod.z.string().optional().meta({
|
|
443
|
+
showWhen: [{
|
|
444
|
+
resource: ["actor"],
|
|
445
|
+
operation: [
|
|
446
|
+
"run",
|
|
447
|
+
"runAndGetDataset",
|
|
448
|
+
"sendServerActorRequest"
|
|
449
|
+
]
|
|
450
|
+
}],
|
|
451
|
+
title: "Actor",
|
|
452
|
+
description: "The ID of the Actor, as \"username~actor-name\" (for example \"apify~web-scraper\") or a plain Actor ID. A URL from Apify Console works too. Find Actors at https://apify.com/store",
|
|
453
|
+
placeholder: "janedoe~my-actor"
|
|
454
|
+
}),
|
|
455
|
+
userActorId: zod.z.string().optional().meta({
|
|
456
|
+
showWhen: [{
|
|
457
|
+
resource: ["actor"],
|
|
458
|
+
operation: ["getLastRun"]
|
|
459
|
+
}, {
|
|
460
|
+
resource: ["actorRun"],
|
|
461
|
+
operation: ["getManyForActor"]
|
|
462
|
+
}],
|
|
463
|
+
title: "Actor",
|
|
464
|
+
description: "The ID of the Actor, as \"username~actor-name\" or a plain Actor ID. A URL from Apify Console works too",
|
|
465
|
+
placeholder: "janedoe~my-actor"
|
|
466
|
+
}),
|
|
467
|
+
actorTaskId: zod.z.string().optional().meta({
|
|
468
|
+
...on({ actorTask: ["run", "runAndGetDataset"] }),
|
|
469
|
+
title: "Actor Task",
|
|
470
|
+
description: "The ID of the task, as \"username~task-name\" or a plain task ID. A URL from Apify Console works too. Manage tasks at https://console.apify.com",
|
|
471
|
+
placeholder: "janedoe~my-task"
|
|
472
|
+
}),
|
|
473
|
+
useCustomBody: zod.z.boolean().default(false).meta({
|
|
474
|
+
...on({ actorTask: ["run", "runAndGetDataset"] }),
|
|
475
|
+
description: "Replace the saved input of the task with the JSON below"
|
|
476
|
+
}),
|
|
477
|
+
customBody: zod.z.string().default("{}").meta({
|
|
478
|
+
showWhen: [...runsActor.showWhen, {
|
|
479
|
+
resource: ["actorTask"],
|
|
480
|
+
operation: ["run", "runAndGetDataset"],
|
|
481
|
+
useCustomBody: [true]
|
|
482
|
+
}],
|
|
483
|
+
title: "Input JSON",
|
|
484
|
+
ui: "code",
|
|
485
|
+
description: "The input of the Actor, as a JSON object. The fields depend on the Actor. A web scraper often has \"startUrls\" (a list of {\"url\": \"...\"}), \"maxCrawlPages\", and \"proxyConfiguration\". A field that you leave out uses the default of the input schema of the Actor. For a task, this input replaces the fields of the saved input"
|
|
486
|
+
}),
|
|
487
|
+
waitForFinish: zod.z.boolean().default(true).meta({
|
|
488
|
+
...waits,
|
|
489
|
+
description: "Wait until the run is over (it can succeed or fail) before the next node starts. Off: get the run right after it starts"
|
|
490
|
+
}),
|
|
491
|
+
timeout: zod.z.number().int().min(0).optional().meta({
|
|
492
|
+
...startsRun,
|
|
493
|
+
description: "The time limit of the run, in seconds. Empty: the run uses the time limit of the Actor or the task"
|
|
494
|
+
}),
|
|
495
|
+
memory: zod.z.enum(MEMORY_OPTIONS).default("1024").meta({
|
|
496
|
+
...startsRun,
|
|
497
|
+
description: "The memory limit of the run, in megabytes",
|
|
498
|
+
labels: MEMORY_LABELS
|
|
499
|
+
}),
|
|
500
|
+
maxTotalChargeUsd: zod.z.number().min(0).optional().meta({
|
|
501
|
+
...startsRun,
|
|
502
|
+
title: "Maximum Cost per Run (USD)",
|
|
503
|
+
description: "The most that the run may cost, in USD. It works for Actors with pay-per-event or pay-per-result prices. The run aborts at the limit. Empty or 0: no limit"
|
|
504
|
+
}),
|
|
505
|
+
build: zod.z.string().optional().meta({
|
|
506
|
+
...startsRun,
|
|
507
|
+
title: "Build Tag",
|
|
508
|
+
description: "The build tag of the Actor to run, such as latest. Empty: the default build of the Actor or the task"
|
|
509
|
+
}),
|
|
510
|
+
endpointMethod: zod.z.enum(HTTP_METHODS).default("GET").meta({
|
|
511
|
+
showWhen: serverRequest,
|
|
512
|
+
title: "Method",
|
|
513
|
+
labels: Object.fromEntries(HTTP_METHODS.map((method) => [method, method]))
|
|
514
|
+
}),
|
|
515
|
+
endpointPath: zod.z.string().default("/").meta({
|
|
516
|
+
showWhen: serverRequest,
|
|
517
|
+
title: "Path",
|
|
518
|
+
description: "The path on the server of the Actor. It starts with /",
|
|
519
|
+
placeholder: "/search"
|
|
520
|
+
}),
|
|
521
|
+
endpointQuery: zod.z.string().default("{}").meta({
|
|
522
|
+
showWhen: serverRequest,
|
|
523
|
+
title: "Query Parameters",
|
|
524
|
+
ui: "code",
|
|
525
|
+
description: "The query parameters as a JSON object, such as {\"limit\": 10}"
|
|
526
|
+
}),
|
|
527
|
+
endpointBody: zod.z.string().default("{}").meta({
|
|
528
|
+
showWhen: {
|
|
529
|
+
...serverRequest,
|
|
530
|
+
endpointMethod: [
|
|
531
|
+
"POST",
|
|
532
|
+
"PUT",
|
|
533
|
+
"PATCH",
|
|
534
|
+
"DELETE"
|
|
535
|
+
]
|
|
536
|
+
},
|
|
537
|
+
title: "Body",
|
|
538
|
+
ui: "code",
|
|
539
|
+
description: "The request body as JSON"
|
|
540
|
+
}),
|
|
541
|
+
url: zod.z.string().optional().meta({
|
|
542
|
+
showWhen: {
|
|
543
|
+
resource: ["actor"],
|
|
544
|
+
operation: ["webFetch"]
|
|
545
|
+
},
|
|
546
|
+
title: "URL",
|
|
547
|
+
description: "The URL to fetch. It must start with http:// or https://",
|
|
548
|
+
placeholder: "https://docs.apify.com/academy/web-scraping-for-beginners"
|
|
549
|
+
}),
|
|
550
|
+
formats: zod.z.array(zod.z.enum(WEB_FETCH_FORMATS)).min(1).default(["markdown"]).meta({
|
|
551
|
+
showWhen: {
|
|
552
|
+
resource: ["actor"],
|
|
553
|
+
operation: ["webFetch"]
|
|
554
|
+
},
|
|
555
|
+
description: "The formats to return. The answer has only the formats that you select",
|
|
556
|
+
labels: {
|
|
557
|
+
html: "HTML",
|
|
558
|
+
links: "Links",
|
|
559
|
+
markdown: "Markdown",
|
|
560
|
+
raw: "Raw",
|
|
561
|
+
text: "Text"
|
|
562
|
+
},
|
|
563
|
+
hints: {
|
|
564
|
+
html: "Raw HTML. Best for code that reads the page",
|
|
565
|
+
links: "The links of the page, without duplicates. Good for a crawl queue",
|
|
566
|
+
markdown: "Clean markdown. Best for AI agents and LLMs",
|
|
567
|
+
raw: "The original body. It is base64 for binary content",
|
|
568
|
+
text: "Plain text, without formatting"
|
|
569
|
+
}
|
|
570
|
+
}),
|
|
571
|
+
headers: zod.z.string().default("{}").meta({
|
|
572
|
+
showWhen: {
|
|
573
|
+
resource: ["actor"],
|
|
574
|
+
operation: ["webFetch"]
|
|
575
|
+
},
|
|
576
|
+
ui: "code",
|
|
577
|
+
description: "Headers to send to the URL, as a JSON object, such as {\"Accept-Language\": \"fr-FR\"}. {} sends none"
|
|
578
|
+
}),
|
|
579
|
+
status: zod.z.enum(RUN_STATUSES).optional().meta({
|
|
580
|
+
showWhen: [{
|
|
581
|
+
resource: ["actor"],
|
|
582
|
+
operation: ["getLastRun"]
|
|
583
|
+
}, {
|
|
584
|
+
resource: ["actorRun"],
|
|
585
|
+
operation: ["getMany", "getManyForActor"]
|
|
586
|
+
}],
|
|
587
|
+
description: "Get only runs with this status. Empty: the status SUCCEEDED for Get Last Run and Get Many, and all statuses for Get Many for Actor",
|
|
588
|
+
labels: RUN_STATUS_LABELS
|
|
589
|
+
}),
|
|
590
|
+
runId: zod.z.string().optional().meta({
|
|
591
|
+
showWhen: {
|
|
592
|
+
resource: ["actorRun"],
|
|
593
|
+
operation: ["get"]
|
|
594
|
+
},
|
|
595
|
+
title: "Run ID",
|
|
596
|
+
description: "The ID of the run. A URL from Apify Console works too"
|
|
597
|
+
}),
|
|
598
|
+
abortRunId: zod.z.string().optional().meta({
|
|
599
|
+
showWhen: {
|
|
600
|
+
resource: ["actorRun"],
|
|
601
|
+
operation: ["abort"]
|
|
602
|
+
},
|
|
603
|
+
title: "Run ID",
|
|
604
|
+
description: "The ID of the run to abort"
|
|
605
|
+
}),
|
|
606
|
+
gracefully: zod.z.boolean().default(false).meta({
|
|
607
|
+
showWhen: {
|
|
608
|
+
resource: ["actorRun"],
|
|
609
|
+
operation: ["abort"]
|
|
610
|
+
},
|
|
611
|
+
title: "Graceful",
|
|
612
|
+
description: "Give the Actor time to finish its current work before it stops. Off: the run stops at once"
|
|
613
|
+
}),
|
|
614
|
+
desc: zod.z.boolean().default(true).meta({
|
|
615
|
+
...pagesRuns,
|
|
616
|
+
title: "Desc",
|
|
617
|
+
description: "Sort the runs by the start time, newest first. Off: the oldest run is first"
|
|
618
|
+
}),
|
|
619
|
+
datasetId: zod.z.string().optional().meta({
|
|
620
|
+
showWhen: {
|
|
621
|
+
resource: ["dataset"],
|
|
622
|
+
operation: ["getItems"]
|
|
623
|
+
},
|
|
624
|
+
title: "Dataset ID",
|
|
625
|
+
description: "The ID of the dataset, or username~dataset-name"
|
|
626
|
+
}),
|
|
627
|
+
options: zod.z.object({
|
|
628
|
+
fields: zod.z.string().meta({ description: "Field names with commas between. Only these fields are in the items" }),
|
|
629
|
+
omit: zod.z.string().meta({ description: "Field names with commas between. These fields are not in the items. A field in Fields and in Omit is left out" })
|
|
630
|
+
}).partial().default({}).meta({
|
|
631
|
+
showWhen: {
|
|
632
|
+
resource: ["dataset"],
|
|
633
|
+
operation: ["getItems"]
|
|
634
|
+
},
|
|
635
|
+
title: "Options"
|
|
636
|
+
}),
|
|
637
|
+
storeId: zod.z.string().optional().meta({
|
|
638
|
+
showWhen: {
|
|
639
|
+
resource: ["keyValueStore"],
|
|
640
|
+
operation: ["getRecord"]
|
|
641
|
+
},
|
|
642
|
+
title: "Key-Value Store ID",
|
|
643
|
+
description: "The ID of the key-value store"
|
|
644
|
+
}),
|
|
645
|
+
recordKey: zod.z.string().optional().meta({
|
|
646
|
+
showWhen: {
|
|
647
|
+
resource: ["keyValueStore"],
|
|
648
|
+
operation: ["getRecord"]
|
|
649
|
+
},
|
|
650
|
+
title: "Key-Value Store Record Key",
|
|
651
|
+
description: "The key of the record",
|
|
652
|
+
placeholder: "RECORD_KEY"
|
|
653
|
+
}),
|
|
654
|
+
offset: zod.z.number().int().min(0).default(0).meta({
|
|
655
|
+
...pages,
|
|
656
|
+
description: "The number of items to skip at the start"
|
|
657
|
+
}),
|
|
658
|
+
limit: zod.z.number().int().min(1).default(50).meta({
|
|
659
|
+
...pages,
|
|
660
|
+
description: "The most items to return"
|
|
661
|
+
})
|
|
662
|
+
}).superRefine((config, context) => {
|
|
663
|
+
if (!OPERATIONS_OF[config.resource].includes(config.operation)) context.addIssue({
|
|
664
|
+
code: "custom",
|
|
665
|
+
path: ["operation"],
|
|
666
|
+
message: `"${config.operation}" is not an operation of "${config.resource}"`
|
|
667
|
+
});
|
|
668
|
+
});
|
|
669
|
+
// src/request.ts
|
|
670
|
+
const need = (value, name, operation) => {
|
|
671
|
+
if (value === void 0 || value === null || typeof value === "string" && value.trim() === "") throw new Error(`Apify ${operation} needs "${name}"`);
|
|
672
|
+
return value;
|
|
673
|
+
};
|
|
674
|
+
/** Where an ID is in a URL of Apify Console. */
|
|
675
|
+
const CONSOLE_PATTERNS = {
|
|
676
|
+
actor: /^https:\/\/console\.apify\.com\/actors\/(?!tasks\/|runs\/)([A-Za-z0-9]+)(?:[/?#].*)?$/,
|
|
677
|
+
actorTask: /^https:\/\/console\.apify\.com\/actors\/tasks\/([A-Za-z0-9]+)(?:[/?#].*)?$/,
|
|
678
|
+
run: /^https:\/\/console\.apify\.com\/actors(?:\/[A-Za-z0-9]+)?\/runs\/([A-Za-z0-9]+)(?:[/?#].*)?$/
|
|
679
|
+
};
|
|
680
|
+
/** An ID as one path segment. A URL of Apify Console gives its ID. */
|
|
681
|
+
function id(value, name, operation, kind) {
|
|
682
|
+
const text = need(value, name, operation).trim();
|
|
683
|
+
return segment((kind ? CONSOLE_PATTERNS[kind].exec(text)?.[1] : void 0) ?? text, name);
|
|
684
|
+
}
|
|
685
|
+
/** The plain ID, before it goes in a path. */
|
|
686
|
+
const rawId = (value, name, operation, kind) => decodeURIComponent(id(value, name, operation, kind));
|
|
687
|
+
const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
688
|
+
/** A JSON text that must be an object (or, with `allowArray`, an array). Empty text is `{}`. */
|
|
689
|
+
function parseJson(raw, label, operation, allowArray = false) {
|
|
690
|
+
const content = (raw ?? "").trim();
|
|
691
|
+
if (content === "") return {};
|
|
692
|
+
let value;
|
|
693
|
+
try {
|
|
694
|
+
value = JSON.parse(content);
|
|
695
|
+
} catch {
|
|
696
|
+
value = void 0;
|
|
697
|
+
}
|
|
698
|
+
if (isObject$1(value) || allowArray && Array.isArray(value)) return value;
|
|
699
|
+
throw new Error(`Apify ${operation}: "${label}" must be a JSON ${allowArray ? "object or array" : "object"}`);
|
|
700
|
+
}
|
|
701
|
+
/** Field names with commas between, without empty names. */
|
|
702
|
+
const names = (text) => text.split(",").map((item) => item.trim()).filter(Boolean).join(",");
|
|
703
|
+
/** The parameters of a call that starts a run. */
|
|
704
|
+
function runQuery(c) {
|
|
705
|
+
return {
|
|
706
|
+
timeout: c.timeout,
|
|
707
|
+
memory: Number(c.memory),
|
|
708
|
+
maxTotalChargeUsd: c.maxTotalChargeUsd && c.maxTotalChargeUsd > 0 ? c.maxTotalChargeUsd : void 0,
|
|
709
|
+
waitForFinish: 0
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
/** Checks the URL of Web Fetch: http or https, and a host name with a dot. */
|
|
713
|
+
function webUrl(value, operation) {
|
|
714
|
+
const text = need(value, "url", operation).trim();
|
|
715
|
+
try {
|
|
716
|
+
const parsed = new URL(text);
|
|
717
|
+
if ((parsed.protocol === "http:" || parsed.protocol === "https:") && /^(?=.{1,253}$)((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$/.test(parsed.hostname)) return text;
|
|
718
|
+
} catch {}
|
|
719
|
+
throw new Error(`Apify ${operation}: "${text}" is not a valid URL. Use a full URL with a domain, such as https://example.com`);
|
|
720
|
+
}
|
|
721
|
+
/** The Apify call for one operation, without the network. */
|
|
722
|
+
function buildRequest(c) {
|
|
723
|
+
const op = `${c.resource}.${c.operation}`;
|
|
724
|
+
switch (op) {
|
|
725
|
+
case "actor.run":
|
|
726
|
+
case "actor.runAndGetDataset": {
|
|
727
|
+
const actorId = rawId(c.actorId, "actorId", op, "actor");
|
|
728
|
+
return {
|
|
729
|
+
kind: "run",
|
|
730
|
+
target: "actor",
|
|
731
|
+
id: actorId,
|
|
732
|
+
buildTag: c.build?.trim() || void 0,
|
|
733
|
+
call: {
|
|
734
|
+
method: "POST",
|
|
735
|
+
path: `/v2/acts/${segment(actorId, "actorId")}/runs`,
|
|
736
|
+
query: runQuery(c),
|
|
737
|
+
body: parseJson(c.customBody, "customBody", op)
|
|
738
|
+
},
|
|
739
|
+
wait: c.operation === "runAndGetDataset" || c.waitForFinish,
|
|
740
|
+
dataset: c.operation === "runAndGetDataset"
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
case "actorTask.run":
|
|
744
|
+
case "actorTask.runAndGetDataset": {
|
|
745
|
+
const taskId = rawId(c.actorTaskId, "actorTaskId", op, "actorTask");
|
|
746
|
+
return {
|
|
747
|
+
kind: "run",
|
|
748
|
+
target: "actorTask",
|
|
749
|
+
id: taskId,
|
|
750
|
+
call: {
|
|
751
|
+
method: "POST",
|
|
752
|
+
path: `/v2/actor-tasks/${segment(taskId, "actorTaskId")}/runs`,
|
|
753
|
+
query: {
|
|
754
|
+
...runQuery(c),
|
|
755
|
+
build: c.build?.trim() || void 0
|
|
756
|
+
},
|
|
757
|
+
body: c.useCustomBody ? parseJson(c.customBody, "customBody", op) : {}
|
|
758
|
+
},
|
|
759
|
+
wait: c.operation === "runAndGetDataset" || c.waitForFinish,
|
|
760
|
+
dataset: c.operation === "runAndGetDataset"
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
case "actor.sendServerActorRequest": {
|
|
764
|
+
const method = c.endpointMethod;
|
|
765
|
+
const path = c.endpointPath.trim();
|
|
766
|
+
return {
|
|
767
|
+
kind: "server",
|
|
768
|
+
actorId: rawId(c.actorId, "actorId", op, "actor"),
|
|
769
|
+
method,
|
|
770
|
+
path: `/${path.replace(/^\/+/, "")}`,
|
|
771
|
+
query: parseJson(c.endpointQuery, "Query Parameters", op),
|
|
772
|
+
body: method === "GET" ? void 0 : parseJson(c.endpointBody, "Body", op, true)
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
case "actor.webFetch": {
|
|
776
|
+
const headers = parseJson(c.headers, "Headers", op);
|
|
777
|
+
return {
|
|
778
|
+
kind: "call",
|
|
779
|
+
output: "body",
|
|
780
|
+
call: {
|
|
781
|
+
method: "POST",
|
|
782
|
+
path: "/",
|
|
783
|
+
origin: WEB_FETCH_URL,
|
|
784
|
+
timeoutMs: WEB_FETCH_TIMEOUT_MS,
|
|
785
|
+
body: {
|
|
786
|
+
url: webUrl(c.url, op),
|
|
787
|
+
formats: c.formats,
|
|
788
|
+
...Object.keys(headers).length > 0 ? { headers } : {}
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
case "actor.getLastRun": return {
|
|
794
|
+
kind: "call",
|
|
795
|
+
output: "object",
|
|
796
|
+
call: {
|
|
797
|
+
method: "GET",
|
|
798
|
+
path: `/v2/acts/${id(c.userActorId, "userActorId", op, "actor")}/runs/last`,
|
|
799
|
+
query: { status: c.status ?? "SUCCEEDED" }
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
case "actorRun.get": return {
|
|
803
|
+
kind: "call",
|
|
804
|
+
output: "object",
|
|
805
|
+
call: {
|
|
806
|
+
method: "GET",
|
|
807
|
+
path: `/v2/actor-runs/${id(c.runId, "runId", op, "run")}`
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
case "actorRun.getMany": return {
|
|
811
|
+
kind: "call",
|
|
812
|
+
output: "items",
|
|
813
|
+
call: {
|
|
814
|
+
method: "GET",
|
|
815
|
+
path: "/v2/actor-runs",
|
|
816
|
+
query: {
|
|
817
|
+
limit: c.limit,
|
|
818
|
+
offset: c.offset,
|
|
819
|
+
desc: c.desc,
|
|
820
|
+
status: c.status ?? "SUCCEEDED"
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
};
|
|
824
|
+
case "actorRun.getManyForActor": return {
|
|
825
|
+
kind: "call",
|
|
826
|
+
output: "items",
|
|
827
|
+
call: {
|
|
828
|
+
method: "GET",
|
|
829
|
+
path: `/v2/acts/${id(c.userActorId, "userActorId", op, "actor")}/runs`,
|
|
830
|
+
query: {
|
|
831
|
+
limit: c.limit,
|
|
832
|
+
offset: c.offset,
|
|
833
|
+
desc: c.desc,
|
|
834
|
+
status: c.status
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
};
|
|
838
|
+
case "actorRun.abort": return {
|
|
839
|
+
kind: "call",
|
|
840
|
+
output: "object",
|
|
841
|
+
call: {
|
|
842
|
+
method: "POST",
|
|
843
|
+
path: `/v2/actor-runs/${id(c.abortRunId, "abortRunId", op, "run")}/abort`,
|
|
844
|
+
query: c.gracefully ? { gracefully: true } : void 0
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
case "dataset.getItems": return {
|
|
848
|
+
kind: "call",
|
|
849
|
+
output: "list",
|
|
850
|
+
call: {
|
|
851
|
+
method: "GET",
|
|
852
|
+
path: `/v2/datasets/${id(c.datasetId, "datasetId", op)}/items`,
|
|
853
|
+
query: {
|
|
854
|
+
offset: c.offset,
|
|
855
|
+
limit: c.limit,
|
|
856
|
+
fields: c.options.fields ? names(c.options.fields) : void 0,
|
|
857
|
+
omit: c.options.omit ? names(c.options.omit) : void 0
|
|
858
|
+
},
|
|
859
|
+
timeoutMs: DATASET_TIMEOUT_MS
|
|
860
|
+
}
|
|
861
|
+
};
|
|
862
|
+
case "keyValueStore.getRecord": {
|
|
863
|
+
const storeId = need(c.storeId, "storeId", op).trim();
|
|
864
|
+
const recordKey = need(c.recordKey, "recordKey", op).trim();
|
|
865
|
+
return {
|
|
866
|
+
kind: "record",
|
|
867
|
+
storeId,
|
|
868
|
+
recordKey,
|
|
869
|
+
call: {
|
|
870
|
+
method: "GET",
|
|
871
|
+
path: `/v2/key-value-stores/${segment(storeId, "storeId")}/records/${segment(recordKey, "recordKey")}`
|
|
872
|
+
}
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
default: throw new Error(`Apify does not know the operation "${op}"`);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
// src/node.ts
|
|
879
|
+
const CHARGED = "The request may still have been charged.";
|
|
880
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
881
|
+
/** The build number of the build that a run uses: the build of the tag, or the default build. */
|
|
882
|
+
async function buildNumberOf(access, actorId, buildTag, options) {
|
|
883
|
+
const path = `/v2/acts/${segment(actorId, "actorId")}`;
|
|
884
|
+
const actor = dataOf(await callApify(access, {
|
|
885
|
+
method: "GET",
|
|
886
|
+
path
|
|
887
|
+
}, options));
|
|
888
|
+
if (Object.keys(actor).length === 0) throw new ApifyError(`Actor ${actorId} was not found`);
|
|
889
|
+
if (buildTag) {
|
|
890
|
+
const tagged = isObject(actor.taggedBuilds) ? actor.taggedBuilds[buildTag] : void 0;
|
|
891
|
+
const buildId = isObject(tagged) ? tagged.buildId : void 0;
|
|
892
|
+
if (typeof buildId !== "string" || buildId === "") throw new ApifyError(`Build tag '${buildTag}' does not exist for Actor ${String(actor.title ?? actor.name ?? actorId)}`);
|
|
893
|
+
const build = dataOf(await callApify(access, {
|
|
894
|
+
method: "GET",
|
|
895
|
+
path: `/v2/actor-builds/${segment(buildId, "buildId")}`
|
|
896
|
+
}, options));
|
|
897
|
+
return typeof build.buildNumber === "string" ? build.buildNumber : void 0;
|
|
898
|
+
}
|
|
899
|
+
try {
|
|
900
|
+
const build = dataOf(await callApify(access, {
|
|
901
|
+
method: "GET",
|
|
902
|
+
path: `${path}/builds/default`
|
|
903
|
+
}, options));
|
|
904
|
+
return typeof build.buildNumber === "string" ? build.buildNumber : void 0;
|
|
905
|
+
} catch (error) {
|
|
906
|
+
if (error instanceof ApifyError && error.type === "unknown-build-tag") throw new ApifyError(`Actor ${actorId} has no build for its default build tag. Build the Actor in ${APIFY_CONSOLE_URL}/actors/${actorId}/builds, or set Build Tag to an existing build`, error.status, error.type, error.data);
|
|
907
|
+
throw error;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
/** Starts a run, waits when asked, and gets the dataset items when asked. */
|
|
911
|
+
async function startRun(access, plan, options) {
|
|
912
|
+
const call = {
|
|
913
|
+
...plan.call,
|
|
914
|
+
query: { ...plan.call.query },
|
|
915
|
+
retryRateLimitOnly: true
|
|
916
|
+
};
|
|
917
|
+
if (plan.target === "actor") {
|
|
918
|
+
const build = await buildNumberOf(access, plan.id, plan.buildTag, options);
|
|
919
|
+
if (build) call.query.build = build;
|
|
920
|
+
}
|
|
921
|
+
const started = dataOf(await callApify(access, call, options));
|
|
922
|
+
const runId = started.id;
|
|
923
|
+
if (typeof runId !== "string" || runId === "") throw new ApifyError(`Apify did not give the run ID after it started the ${plan.target === "actor" ? "Actor" : "task"}`);
|
|
924
|
+
if (!plan.wait) return started;
|
|
925
|
+
const run = await pollRun(access, runId, options);
|
|
926
|
+
if (!plan.dataset) return run;
|
|
927
|
+
if (typeof run.defaultDatasetId !== "string" || run.defaultDatasetId === "") throw new ApifyError(`Run ${runId} did not create a dataset`);
|
|
928
|
+
if (run.status !== "SUCCEEDED") throw new ApifyError(`Run ${runId} did not finish with status SUCCEEDED. Run status: ${String(run.status)}`);
|
|
929
|
+
return await callApify(access, {
|
|
930
|
+
method: "GET",
|
|
931
|
+
path: `/v2/datasets/${segment(run.defaultDatasetId, "datasetId")}/items`,
|
|
932
|
+
query: { format: "json" },
|
|
933
|
+
timeoutMs: DATASET_TIMEOUT_MS
|
|
934
|
+
}, options);
|
|
935
|
+
}
|
|
936
|
+
/** The origin of the server of an Actor, or null when the Actor has no server interface. */
|
|
937
|
+
async function serverOrigin(access, actorId, options) {
|
|
938
|
+
const actor = dataOf(await callApify(access, {
|
|
939
|
+
method: "GET",
|
|
940
|
+
path: `/v2/acts/${segment(actorId, "actorId")}`
|
|
941
|
+
}, options));
|
|
942
|
+
if ((isObject(actor.actorStandby) ? actor.actorStandby : {}).isEnabled !== true || typeof actor.standbyUrl !== "string") return null;
|
|
943
|
+
try {
|
|
944
|
+
const url = new URL(actor.standbyUrl);
|
|
945
|
+
return url.protocol === "https:" && url.hostname.endsWith(".apify.actor") ? url.origin : null;
|
|
946
|
+
} catch {
|
|
947
|
+
return null;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
/** A query with a list repeats the name (`a=1&a=2`). An object becomes JSON. */
|
|
951
|
+
function appendQuery(url, query) {
|
|
952
|
+
const toText = (value) => typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
|
|
953
|
+
for (const [name, value] of Object.entries(query)) for (const item of Array.isArray(value) ? value : [value]) url.searchParams.append(name, toText(item));
|
|
954
|
+
}
|
|
955
|
+
const TEXT_TYPES = /^(text\/|application\/(.+\+)?(json|xml|javascript|ecmascript|x-ndjson|ndjson|x-www-form-urlencoded|yaml|x-yaml|graphql|csv)$)/;
|
|
956
|
+
/** Sends one request to a Server Actor. It never tries again, because it can cost money. */
|
|
957
|
+
async function sendToServerActor(access, plan, options) {
|
|
958
|
+
const origin = await serverOrigin(access, plan.actorId, options);
|
|
959
|
+
if (!origin) throw new ApifyError("This Actor has no server interface. Use the Run operation to start a run instead");
|
|
960
|
+
const url = new URL(`${origin}${plan.path}`);
|
|
961
|
+
appendQuery(url, plan.query);
|
|
962
|
+
if (url.origin !== origin) throw new ApifyError(`Invalid path "${plan.path}"`);
|
|
963
|
+
let answer;
|
|
964
|
+
try {
|
|
965
|
+
answer = await sendApify(access, {
|
|
966
|
+
method: plan.method,
|
|
967
|
+
path: `${url.pathname}${url.search}`,
|
|
968
|
+
origin,
|
|
969
|
+
body: plan.body,
|
|
970
|
+
timeoutMs: SERVER_ACTOR_TIMEOUT_MS,
|
|
971
|
+
noRetry: true
|
|
972
|
+
}, options);
|
|
973
|
+
} catch (error) {
|
|
974
|
+
if (!options.signal.aborted && error instanceof Error && /Timeout|Abort/.test(error.name)) throw new ApifyError(`The Actor did not answer in time (Apify waits up to 300 s). ${CHARGED}`);
|
|
975
|
+
throw error;
|
|
976
|
+
}
|
|
977
|
+
const body = decodeBody(answer);
|
|
978
|
+
if (answer.status >= 400) {
|
|
979
|
+
const { message, type } = errorFromBody(body);
|
|
980
|
+
throw new ApifyError(answer.status === 504 ? `The Actor did not answer in time (Apify waits up to 300 s). ${CHARGED}` : `${message ?? `The Actor answered with status ${answer.status}`}. Status ${answer.status}${type ? `, type ${type}` : ""}. ${CHARGED}`, answer.status, type, body);
|
|
981
|
+
}
|
|
982
|
+
const contentType = answer.contentType.toLowerCase();
|
|
983
|
+
if (contentType && !TEXT_TYPES.test(contentType)) throw new ApifyError(`The Actor returned a binary response, which is not supported yet. ${CHARGED} Content type: ${contentType}`);
|
|
984
|
+
return {
|
|
985
|
+
status: answer.status,
|
|
986
|
+
contentType: contentType || null,
|
|
987
|
+
body
|
|
988
|
+
};
|
|
989
|
+
}
|
|
990
|
+
/** Gets a record. Text and JSON go in `data`. Other types go in `binary.data`. */
|
|
991
|
+
async function getRecord(access, plan, options) {
|
|
992
|
+
const answer = await sendApify(access, plan.call, options);
|
|
993
|
+
if (answer.status >= 400) throw apifyErrorOf("GET key-value-stores", answer.status, decodeBody(answer));
|
|
994
|
+
const base = {
|
|
995
|
+
storeId: plan.storeId,
|
|
996
|
+
recordKey: plan.recordKey,
|
|
997
|
+
contentType: answer.contentType
|
|
998
|
+
};
|
|
999
|
+
const type = answer.contentType;
|
|
1000
|
+
const text = () => new TextDecoder().decode(answer.bytes);
|
|
1001
|
+
if (type && !type.startsWith("application/json") && !type.startsWith("text/")) return {
|
|
1002
|
+
...base,
|
|
1003
|
+
binary: { data: (0, _zerodot_node_sdk.toBinary)(answer.bytes, plan.recordKey, type) }
|
|
1004
|
+
};
|
|
1005
|
+
if (type.startsWith("application/json")) try {
|
|
1006
|
+
return {
|
|
1007
|
+
...base,
|
|
1008
|
+
data: JSON.parse(text())
|
|
1009
|
+
};
|
|
1010
|
+
} catch {
|
|
1011
|
+
return {
|
|
1012
|
+
...base,
|
|
1013
|
+
data: text()
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
if (type.startsWith("text/")) return {
|
|
1017
|
+
...base,
|
|
1018
|
+
data: text()
|
|
1019
|
+
};
|
|
1020
|
+
return {
|
|
1021
|
+
...base,
|
|
1022
|
+
data: Buffer.from(answer.bytes).toString("base64")
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
/** Does the plan and gives the data of the node output. */
|
|
1026
|
+
async function executePlan(access, plan, options) {
|
|
1027
|
+
switch (plan.kind) {
|
|
1028
|
+
case "run": return await startRun(access, plan, options);
|
|
1029
|
+
case "server": return await sendToServerActor(access, plan, options);
|
|
1030
|
+
case "record": return await getRecord(access, plan, options);
|
|
1031
|
+
case "call": {
|
|
1032
|
+
const answer = await callApify(access, plan.call, options);
|
|
1033
|
+
switch (plan.output) {
|
|
1034
|
+
case "object": return dataOf(answer);
|
|
1035
|
+
case "items": {
|
|
1036
|
+
const items = dataOf(answer).items;
|
|
1037
|
+
return Array.isArray(items) ? items : [];
|
|
1038
|
+
}
|
|
1039
|
+
case "list": return Array.isArray(answer) ? answer : [];
|
|
1040
|
+
default: return answer;
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
var node_default = (0, _zerodot_node_sdk.defineNode)({
|
|
1046
|
+
type: "apify.api",
|
|
1047
|
+
label: "Apify",
|
|
1048
|
+
description: "Run Actors and tasks, and get runs, dataset items, and records with Apify",
|
|
1049
|
+
category: "integration",
|
|
1050
|
+
app: "Apify",
|
|
1051
|
+
actions: [
|
|
1052
|
+
{
|
|
1053
|
+
label: "Run an Actor",
|
|
1054
|
+
config: {
|
|
1055
|
+
resource: "actor",
|
|
1056
|
+
operation: "run"
|
|
1057
|
+
}
|
|
1058
|
+
},
|
|
1059
|
+
{
|
|
1060
|
+
label: "Run an Actor and get dataset",
|
|
1061
|
+
config: {
|
|
1062
|
+
resource: "actor",
|
|
1063
|
+
operation: "runAndGetDataset"
|
|
1064
|
+
}
|
|
1065
|
+
},
|
|
1066
|
+
{
|
|
1067
|
+
label: "Send a Server Actor request",
|
|
1068
|
+
config: {
|
|
1069
|
+
resource: "actor",
|
|
1070
|
+
operation: "sendServerActorRequest"
|
|
1071
|
+
}
|
|
1072
|
+
},
|
|
1073
|
+
{
|
|
1074
|
+
label: "Web Fetch",
|
|
1075
|
+
config: {
|
|
1076
|
+
resource: "actor",
|
|
1077
|
+
operation: "webFetch"
|
|
1078
|
+
}
|
|
1079
|
+
},
|
|
1080
|
+
{
|
|
1081
|
+
label: "Get last run of an Actor",
|
|
1082
|
+
config: {
|
|
1083
|
+
resource: "actor",
|
|
1084
|
+
operation: "getLastRun",
|
|
1085
|
+
status: "SUCCEEDED"
|
|
1086
|
+
}
|
|
1087
|
+
},
|
|
1088
|
+
{
|
|
1089
|
+
label: "Get an Actor run",
|
|
1090
|
+
config: {
|
|
1091
|
+
resource: "actorRun",
|
|
1092
|
+
operation: "get"
|
|
1093
|
+
}
|
|
1094
|
+
},
|
|
1095
|
+
{
|
|
1096
|
+
label: "Get many Actor runs",
|
|
1097
|
+
config: {
|
|
1098
|
+
resource: "actorRun",
|
|
1099
|
+
operation: "getMany",
|
|
1100
|
+
status: "SUCCEEDED"
|
|
1101
|
+
}
|
|
1102
|
+
},
|
|
1103
|
+
{
|
|
1104
|
+
label: "Get many runs of an Actor",
|
|
1105
|
+
config: {
|
|
1106
|
+
resource: "actorRun",
|
|
1107
|
+
operation: "getManyForActor"
|
|
1108
|
+
}
|
|
1109
|
+
},
|
|
1110
|
+
{
|
|
1111
|
+
label: "Abort an Actor run",
|
|
1112
|
+
config: {
|
|
1113
|
+
resource: "actorRun",
|
|
1114
|
+
operation: "abort"
|
|
1115
|
+
}
|
|
1116
|
+
},
|
|
1117
|
+
{
|
|
1118
|
+
label: "Run a task",
|
|
1119
|
+
config: {
|
|
1120
|
+
resource: "actorTask",
|
|
1121
|
+
operation: "run"
|
|
1122
|
+
}
|
|
1123
|
+
},
|
|
1124
|
+
{
|
|
1125
|
+
label: "Run a task and get dataset",
|
|
1126
|
+
config: {
|
|
1127
|
+
resource: "actorTask",
|
|
1128
|
+
operation: "runAndGetDataset"
|
|
1129
|
+
}
|
|
1130
|
+
},
|
|
1131
|
+
{
|
|
1132
|
+
label: "Get dataset items",
|
|
1133
|
+
config: {
|
|
1134
|
+
resource: "dataset",
|
|
1135
|
+
operation: "getItems"
|
|
1136
|
+
}
|
|
1137
|
+
},
|
|
1138
|
+
{
|
|
1139
|
+
label: "Get a key-value store record",
|
|
1140
|
+
config: {
|
|
1141
|
+
resource: "keyValueStore",
|
|
1142
|
+
operation: "getRecord"
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
],
|
|
1146
|
+
icon: "Globe02Icon",
|
|
1147
|
+
iconUrl: APIFY_ICON,
|
|
1148
|
+
config: apifyConfig,
|
|
1149
|
+
defaultConfig: {
|
|
1150
|
+
authentication: "apifyApi",
|
|
1151
|
+
resource: "actor",
|
|
1152
|
+
operation: "run",
|
|
1153
|
+
actorId: "",
|
|
1154
|
+
customBody: "{}",
|
|
1155
|
+
waitForFinish: true,
|
|
1156
|
+
memory: "1024",
|
|
1157
|
+
offset: 0,
|
|
1158
|
+
limit: 50
|
|
1159
|
+
},
|
|
1160
|
+
credentialTypes: [APIFY_API_CREDENTIAL, APIFY_OAUTH2_CREDENTIAL],
|
|
1161
|
+
credentialRules: {
|
|
1162
|
+
[APIFY_API_CREDENTIAL]: { showWhen: { authentication: ["apifyApi"] } },
|
|
1163
|
+
[APIFY_OAUTH2_CREDENTIAL]: { showWhen: { authentication: ["apifyOAuth2Api"] } }
|
|
1164
|
+
},
|
|
1165
|
+
ports: {
|
|
1166
|
+
in: ["in"],
|
|
1167
|
+
out: ["out"]
|
|
1168
|
+
},
|
|
1169
|
+
subtitle: (config) => typeof config.operation === "string" ? `${config.operation}: ${String(config.resource ?? "actor")}` : void 0,
|
|
1170
|
+
async run({ config, credential, signal }) {
|
|
1171
|
+
return {
|
|
1172
|
+
port: "out",
|
|
1173
|
+
data: await executePlan(apifyAccess(credential), buildRequest(config), { signal })
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
});
|
|
1177
|
+
// src/trigger.ts
|
|
1178
|
+
const TIMEOUT_MS = 15e3;
|
|
1179
|
+
/** The run events that Apify has. The value `any` means all of them. */
|
|
1180
|
+
const RUN_EVENTS = [
|
|
1181
|
+
"ACTOR.RUN.SUCCEEDED",
|
|
1182
|
+
"ACTOR.RUN.FAILED",
|
|
1183
|
+
"ACTOR.RUN.TIMED_OUT",
|
|
1184
|
+
"ACTOR.RUN.ABORTED"
|
|
1185
|
+
];
|
|
1186
|
+
const triggerConfig = zod.z.object({
|
|
1187
|
+
authentication: zod.z.enum(AUTHENTICATIONS).default("apifyApi").meta({
|
|
1188
|
+
title: "Authentication",
|
|
1189
|
+
description: "Choose which authentication method to use",
|
|
1190
|
+
labels: AUTHENTICATION_LABELS,
|
|
1191
|
+
hints: {
|
|
1192
|
+
apifyApi: "Use an API token from Apify Console",
|
|
1193
|
+
apifyOAuth2Api: "Sign in with an Apify account"
|
|
1194
|
+
}
|
|
1195
|
+
}),
|
|
1196
|
+
resource: zod.z.enum(["actor", "task"]).default("actor").meta({
|
|
1197
|
+
title: "Resource to Watch",
|
|
1198
|
+
description: "Start the workflow when a run of an Actor or of a task ends",
|
|
1199
|
+
labels: {
|
|
1200
|
+
actor: "Actor",
|
|
1201
|
+
task: "Task"
|
|
1202
|
+
},
|
|
1203
|
+
hints: {
|
|
1204
|
+
actor: "Watch the runs of one Actor",
|
|
1205
|
+
task: "Watch the runs of one saved task"
|
|
1206
|
+
}
|
|
1207
|
+
}),
|
|
1208
|
+
actorId: zod.z.string().optional().meta({
|
|
1209
|
+
showWhen: { resource: ["actor"] },
|
|
1210
|
+
title: "Actor",
|
|
1211
|
+
description: "The ID of the Actor, as \"username~actor-name\" or a plain Actor ID. A URL from Apify Console works too",
|
|
1212
|
+
placeholder: "janedoe~my-actor"
|
|
1213
|
+
}),
|
|
1214
|
+
actorTaskId: zod.z.string().optional().meta({
|
|
1215
|
+
showWhen: { resource: ["task"] },
|
|
1216
|
+
title: "Saved Tasks Name or ID",
|
|
1217
|
+
description: "The ID of the task to watch, as \"username~task-name\" or a plain task ID. A URL from Apify Console works too",
|
|
1218
|
+
placeholder: "janedoe~my-task"
|
|
1219
|
+
}),
|
|
1220
|
+
eventType: zod.z.array(zod.z.enum([
|
|
1221
|
+
"ACTOR.RUN.ABORTED",
|
|
1222
|
+
"any",
|
|
1223
|
+
"ACTOR.RUN.FAILED",
|
|
1224
|
+
"ACTOR.RUN.SUCCEEDED",
|
|
1225
|
+
"ACTOR.RUN.TIMED_OUT"
|
|
1226
|
+
])).min(1).default(["ACTOR.RUN.SUCCEEDED"]).meta({
|
|
1227
|
+
title: "Event Type",
|
|
1228
|
+
description: "The status of the run that starts the workflow",
|
|
1229
|
+
labels: {
|
|
1230
|
+
"ACTOR.RUN.ABORTED": "Aborted",
|
|
1231
|
+
any: "Any",
|
|
1232
|
+
"ACTOR.RUN.FAILED": "Failed",
|
|
1233
|
+
"ACTOR.RUN.SUCCEEDED": "Succeeded",
|
|
1234
|
+
"ACTOR.RUN.TIMED_OUT": "Timed Out"
|
|
1235
|
+
},
|
|
1236
|
+
hints: {
|
|
1237
|
+
"ACTOR.RUN.ABORTED": "The run was aborted",
|
|
1238
|
+
any: "The run ended in any way",
|
|
1239
|
+
"ACTOR.RUN.FAILED": "The run failed",
|
|
1240
|
+
"ACTOR.RUN.SUCCEEDED": "The run ended with success",
|
|
1241
|
+
"ACTOR.RUN.TIMED_OUT": "The run took more time than its limit"
|
|
1242
|
+
}
|
|
1243
|
+
})
|
|
1244
|
+
});
|
|
1245
|
+
/** The events to watch. `any` gives all four run events. */
|
|
1246
|
+
function normalizeEventTypes(selected) {
|
|
1247
|
+
return selected.includes("any") ? [...RUN_EVENTS] : [...selected];
|
|
1248
|
+
}
|
|
1249
|
+
/** The ID of the Actor or the task to watch. */
|
|
1250
|
+
function watchedId(config) {
|
|
1251
|
+
return config.resource === "task" ? rawId(config.actorTaskId, "actorTaskId", "trigger", "actorTask") : rawId(config.actorId, "actorId", "trigger", "actor");
|
|
1252
|
+
}
|
|
1253
|
+
/** The condition of the webhook: the Actor or the task. */
|
|
1254
|
+
function conditionOf(config) {
|
|
1255
|
+
const id = watchedId(config);
|
|
1256
|
+
return config.resource === "task" ? { actorTaskId: id } : { actorId: id };
|
|
1257
|
+
}
|
|
1258
|
+
/**
|
|
1259
|
+
* Apify keeps one webhook for one key. The key has the address, so two workflows that watch the
|
|
1260
|
+
* same Actor each get their own webhook.
|
|
1261
|
+
*/
|
|
1262
|
+
function idempotencyKey(config, url) {
|
|
1263
|
+
const events = normalizeEventTypes(config.eventType).sort().join(",");
|
|
1264
|
+
const raw = `${config.resource}:${watchedId(config)}:${events}:${url}`;
|
|
1265
|
+
return (0, node_crypto.createHash)("sha256").update(raw).digest("hex");
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Decides about a request. Apify has no signature for a webhook. The secret address is the check.
|
|
1269
|
+
* A body with an event that the config does not list is ignored.
|
|
1270
|
+
*/
|
|
1271
|
+
function checkApifyEvent(config, request, secret) {
|
|
1272
|
+
if (request.method.toUpperCase() !== "POST") return {
|
|
1273
|
+
verdict: "ignore",
|
|
1274
|
+
response: {
|
|
1275
|
+
status: 200,
|
|
1276
|
+
body: { ok: true }
|
|
1277
|
+
}
|
|
1278
|
+
};
|
|
1279
|
+
const sent = headerOf(request.headers, SECRET_HEADER);
|
|
1280
|
+
if (!secret || !sent || !sameText(sent, secret)) return {
|
|
1281
|
+
verdict: "forbidden",
|
|
1282
|
+
status: 401
|
|
1283
|
+
};
|
|
1284
|
+
const body = typeof request.body === "object" && request.body !== null ? request.body : {};
|
|
1285
|
+
const eventType = body.eventType;
|
|
1286
|
+
if (typeof eventType !== "string") return {
|
|
1287
|
+
verdict: "ignore",
|
|
1288
|
+
response: {
|
|
1289
|
+
status: 200,
|
|
1290
|
+
body: { ok: true }
|
|
1291
|
+
}
|
|
1292
|
+
};
|
|
1293
|
+
if (!normalizeEventTypes(config.eventType).includes(eventType)) return {
|
|
1294
|
+
verdict: "ignore",
|
|
1295
|
+
response: {
|
|
1296
|
+
status: 200,
|
|
1297
|
+
body: { ok: true }
|
|
1298
|
+
}
|
|
1299
|
+
};
|
|
1300
|
+
return {
|
|
1301
|
+
verdict: "accept",
|
|
1302
|
+
input: body
|
|
1303
|
+
};
|
|
1304
|
+
}
|
|
1305
|
+
/** The header that has the secret of the webhook. */
|
|
1306
|
+
const SECRET_HEADER = "x-zerodot-webhook-secret";
|
|
1307
|
+
function headerOf(headers, name) {
|
|
1308
|
+
for (const [key, value] of Object.entries(headers ?? {})) if (key.toLowerCase() === name) return value;
|
|
1309
|
+
}
|
|
1310
|
+
/** Compares two texts in constant time. */
|
|
1311
|
+
function sameText(a, b) {
|
|
1312
|
+
const left = (0, node_crypto.createHash)("sha256").update(a).digest();
|
|
1313
|
+
const right = (0, node_crypto.createHash)("sha256").update(b).digest();
|
|
1314
|
+
return (0, node_crypto.timingSafeEqual)(left, right);
|
|
1315
|
+
}
|
|
1316
|
+
/** Deletes a webhook. A webhook that is gone already is fine. */
|
|
1317
|
+
async function deleteHook(access, webhookId, options) {
|
|
1318
|
+
try {
|
|
1319
|
+
await callApify(access, {
|
|
1320
|
+
method: "DELETE",
|
|
1321
|
+
path: `/v2/webhooks/${segment(webhookId, "webhookId")}`
|
|
1322
|
+
}, options);
|
|
1323
|
+
} catch (error) {
|
|
1324
|
+
if (!(error instanceof ApifyError && error.status === 404)) throw error;
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
/** Removes each webhook of the account that has this address. It reads all pages first. */
|
|
1328
|
+
async function removeHooks(access, url, options) {
|
|
1329
|
+
const PAGE = 1e3;
|
|
1330
|
+
const found = [];
|
|
1331
|
+
for (let offset = 0;; offset += PAGE) {
|
|
1332
|
+
const items = dataOf(await callApify(access, {
|
|
1333
|
+
method: "GET",
|
|
1334
|
+
path: "/v2/webhooks",
|
|
1335
|
+
query: {
|
|
1336
|
+
limit: PAGE,
|
|
1337
|
+
offset
|
|
1338
|
+
}
|
|
1339
|
+
}, options)).items;
|
|
1340
|
+
const page = Array.isArray(items) ? items : [];
|
|
1341
|
+
for (const hook of page) if (hook.requestUrl === url && hook.id) found.push(hook.id);
|
|
1342
|
+
if (page.length < PAGE) break;
|
|
1343
|
+
}
|
|
1344
|
+
for (const id of found) await deleteHook(access, id, options);
|
|
1345
|
+
}
|
|
1346
|
+
// src/index.ts
|
|
1347
|
+
const nodes = [(0, _zerodot_node_sdk.defineNode)({
|
|
1348
|
+
type: "trigger.apify",
|
|
1349
|
+
label: "Apify Trigger",
|
|
1350
|
+
description: "Start the workflow when a run of an Apify Actor or task ends",
|
|
1351
|
+
category: "trigger",
|
|
1352
|
+
app: "Apify",
|
|
1353
|
+
icon: "Globe02Icon",
|
|
1354
|
+
iconUrl: APIFY_ICON,
|
|
1355
|
+
config: triggerConfig,
|
|
1356
|
+
defaultConfig: {
|
|
1357
|
+
authentication: "apifyApi",
|
|
1358
|
+
resource: "actor",
|
|
1359
|
+
actorId: "",
|
|
1360
|
+
eventType: ["ACTOR.RUN.SUCCEEDED"]
|
|
1361
|
+
},
|
|
1362
|
+
credentialTypes: [APIFY_API_CREDENTIAL, APIFY_OAUTH2_CREDENTIAL],
|
|
1363
|
+
credentialRules: {
|
|
1364
|
+
[APIFY_API_CREDENTIAL]: { showWhen: { authentication: ["apifyApi"] } },
|
|
1365
|
+
[APIFY_OAUTH2_CREDENTIAL]: { showWhen: { authentication: ["apifyOAuth2Api"] } }
|
|
1366
|
+
},
|
|
1367
|
+
ports: {
|
|
1368
|
+
in: [],
|
|
1369
|
+
out: ["out"]
|
|
1370
|
+
},
|
|
1371
|
+
subtitle: (config) => {
|
|
1372
|
+
const id = config.resource === "task" ? config.actorTaskId : config.actorId;
|
|
1373
|
+
const events = Array.isArray(config.eventType) ? config.eventType.join(", ") : "";
|
|
1374
|
+
return typeof id === "string" && id !== "" ? `${id}: ${events}` : events || void 0;
|
|
1375
|
+
},
|
|
1376
|
+
run: ({ input }) => ({
|
|
1377
|
+
port: "out",
|
|
1378
|
+
data: input
|
|
1379
|
+
}),
|
|
1380
|
+
webhook: {
|
|
1381
|
+
async receive({ config: raw, request, state }) {
|
|
1382
|
+
const saved = state;
|
|
1383
|
+
return checkApifyEvent(triggerConfig.parse(raw), request, saved?.secret);
|
|
1384
|
+
},
|
|
1385
|
+
/** Makes the webhook at Apify. A webhook with this address is removed first. */
|
|
1386
|
+
async activate({ config: raw, credential, url, signal }) {
|
|
1387
|
+
const config = triggerConfig.parse(raw);
|
|
1388
|
+
const access = apifyAccess(credential);
|
|
1389
|
+
const options = { signal };
|
|
1390
|
+
const condition = conditionOf(config);
|
|
1391
|
+
await removeHooks(access, url, options);
|
|
1392
|
+
const secret = (0, node_crypto.randomBytes)(32).toString("hex");
|
|
1393
|
+
const answer = dataOf(await callApify(access, {
|
|
1394
|
+
method: "POST",
|
|
1395
|
+
path: "/v2/webhooks",
|
|
1396
|
+
body: {
|
|
1397
|
+
eventTypes: normalizeEventTypes(config.eventType),
|
|
1398
|
+
requestUrl: url,
|
|
1399
|
+
condition,
|
|
1400
|
+
idempotencyKey: idempotencyKey(config, url),
|
|
1401
|
+
headersTemplate: JSON.stringify({ [SECRET_HEADER]: secret })
|
|
1402
|
+
},
|
|
1403
|
+
timeoutMs: TIMEOUT_MS
|
|
1404
|
+
}, options));
|
|
1405
|
+
if (typeof answer.id !== "string") throw new Error("Apify did not give the ID of the webhook");
|
|
1406
|
+
return {
|
|
1407
|
+
webhookId: answer.id,
|
|
1408
|
+
secret
|
|
1409
|
+
};
|
|
1410
|
+
},
|
|
1411
|
+
/** Removes the webhook. A webhook that is gone already is fine. */
|
|
1412
|
+
async deactivate({ credential, url, state, signal }) {
|
|
1413
|
+
const access = apifyAccess(credential);
|
|
1414
|
+
const options = { signal };
|
|
1415
|
+
const saved = state;
|
|
1416
|
+
if (saved?.webhookId) await deleteHook(access, saved.webhookId, options);
|
|
1417
|
+
else await removeHooks(access, url, options);
|
|
1418
|
+
return null;
|
|
1419
|
+
}
|
|
1420
|
+
},
|
|
1421
|
+
webhookTest: { hint: "A test run makes a webhook at Apify for the test address. Run the Actor or the task to send an event" }
|
|
1422
|
+
}), node_default];
|
|
1423
|
+
const credentialTypes = [apifyApiCredential, apifyOAuth2Credential];
|
|
1424
|
+
exports.credentialTypes = credentialTypes;
|
|
1425
|
+
exports.nodes = nodes;
|