alchemy 0.70.2 → 0.71.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +1 -1
  2. package/bin/alchemy.js +131 -58
  3. package/bin/commands/init.ts +0 -10
  4. package/bin/services/execute-alchemy.ts +12 -3
  5. package/bin/trpc.ts +12 -12
  6. package/lib/alchemy.d.ts.map +1 -1
  7. package/lib/alchemy.js +21 -6
  8. package/lib/alchemy.js.map +1 -1
  9. package/lib/apply.d.ts.map +1 -1
  10. package/lib/apply.js +3 -1
  11. package/lib/apply.js.map +1 -1
  12. package/lib/cloudflare/bindings.d.ts +12 -2
  13. package/lib/cloudflare/bindings.d.ts.map +1 -1
  14. package/lib/cloudflare/bindings.js.map +1 -1
  15. package/lib/cloudflare/bound.d.ts +3 -2
  16. package/lib/cloudflare/bound.d.ts.map +1 -1
  17. package/lib/cloudflare/bucket.d.ts +6 -0
  18. package/lib/cloudflare/bucket.d.ts.map +1 -1
  19. package/lib/cloudflare/bucket.js +5 -3
  20. package/lib/cloudflare/bucket.js.map +1 -1
  21. package/lib/cloudflare/bun-spa/bun-spa.d.ts +6 -1
  22. package/lib/cloudflare/bun-spa/bun-spa.d.ts.map +1 -1
  23. package/lib/cloudflare/bun-spa/bun-spa.js +29 -9
  24. package/lib/cloudflare/bun-spa/bun-spa.js.map +1 -1
  25. package/lib/cloudflare/compatibility-date.gen.d.ts +1 -1
  26. package/lib/cloudflare/compatibility-date.gen.js +1 -1
  27. package/lib/cloudflare/d1-database.d.ts +1 -1
  28. package/lib/cloudflare/d1-database.d.ts.map +1 -1
  29. package/lib/cloudflare/d1-database.js +1 -1
  30. package/lib/cloudflare/d1-database.js.map +1 -1
  31. package/lib/cloudflare/health-check.d.ts +261 -0
  32. package/lib/cloudflare/health-check.d.ts.map +1 -0
  33. package/lib/cloudflare/health-check.js +277 -0
  34. package/lib/cloudflare/health-check.js.map +1 -0
  35. package/lib/cloudflare/index.d.ts +3 -0
  36. package/lib/cloudflare/index.d.ts.map +1 -1
  37. package/lib/cloudflare/index.js +3 -0
  38. package/lib/cloudflare/index.js.map +1 -1
  39. package/lib/cloudflare/logpush-job.d.ts +349 -0
  40. package/lib/cloudflare/logpush-job.d.ts.map +1 -0
  41. package/lib/cloudflare/logpush-job.js +277 -0
  42. package/lib/cloudflare/logpush-job.js.map +1 -0
  43. package/lib/cloudflare/miniflare/build-worker-options.d.ts +1 -0
  44. package/lib/cloudflare/miniflare/build-worker-options.d.ts.map +1 -1
  45. package/lib/cloudflare/miniflare/build-worker-options.js +16 -6
  46. package/lib/cloudflare/miniflare/build-worker-options.js.map +1 -1
  47. package/lib/cloudflare/miniflare/remote-binding-proxy.d.ts.map +1 -1
  48. package/lib/cloudflare/miniflare/remote-binding-proxy.js +2 -0
  49. package/lib/cloudflare/miniflare/remote-binding-proxy.js.map +1 -1
  50. package/lib/cloudflare/queue-consumer.js +2 -2
  51. package/lib/cloudflare/queue-consumer.js.map +1 -1
  52. package/lib/cloudflare/worker-loader.d.ts +9 -0
  53. package/lib/cloudflare/worker-loader.d.ts.map +1 -0
  54. package/lib/cloudflare/worker-loader.js +6 -0
  55. package/lib/cloudflare/worker-loader.js.map +1 -0
  56. package/lib/cloudflare/worker-metadata.d.ts.map +1 -1
  57. package/lib/cloudflare/worker-metadata.js +6 -0
  58. package/lib/cloudflare/worker-metadata.js.map +1 -1
  59. package/lib/cloudflare/worker-subdomain.js +1 -1
  60. package/lib/cloudflare/worker.d.ts.map +1 -1
  61. package/lib/cloudflare/worker.js +7 -0
  62. package/lib/cloudflare/worker.js.map +1 -1
  63. package/lib/cloudflare/wrangler.json.d.ts +11 -8
  64. package/lib/cloudflare/wrangler.json.d.ts.map +1 -1
  65. package/lib/cloudflare/wrangler.json.js +18 -11
  66. package/lib/cloudflare/wrangler.json.js.map +1 -1
  67. package/lib/cloudflare/zone.js +1 -1
  68. package/lib/destroy.d.ts.map +1 -1
  69. package/lib/destroy.js +27 -0
  70. package/lib/destroy.js.map +1 -1
  71. package/lib/docker/image.js +1 -1
  72. package/lib/docker/image.js.map +1 -1
  73. package/lib/github/comment.d.ts.map +1 -1
  74. package/lib/github/comment.js +14 -7
  75. package/lib/github/comment.js.map +1 -1
  76. package/lib/resource.js +1 -1
  77. package/lib/resource.js.map +1 -1
  78. package/lib/scope.d.ts +6 -1
  79. package/lib/scope.d.ts.map +1 -1
  80. package/lib/scope.js +22 -22
  81. package/lib/scope.js.map +1 -1
  82. package/lib/state/instrumented-state-store.js +1 -1
  83. package/lib/state/instrumented-state-store.js.map +1 -1
  84. package/lib/util/cli-args.d.ts +3 -0
  85. package/lib/util/cli-args.d.ts.map +1 -0
  86. package/lib/util/cli-args.js +6 -0
  87. package/lib/util/cli-args.js.map +1 -0
  88. package/lib/util/retry.d.ts +1 -1
  89. package/lib/util/retry.d.ts.map +1 -1
  90. package/lib/util/retry.js +2 -2
  91. package/lib/util/retry.js.map +1 -1
  92. package/lib/util/telemetry.d.ts +1 -0
  93. package/lib/util/telemetry.d.ts.map +1 -1
  94. package/lib/util/telemetry.js +47 -2
  95. package/lib/util/telemetry.js.map +1 -1
  96. package/lib/util/validate-resource-id.d.ts +2 -0
  97. package/lib/util/validate-resource-id.d.ts.map +1 -0
  98. package/lib/util/validate-resource-id.js +11 -0
  99. package/lib/util/validate-resource-id.js.map +1 -0
  100. package/package.json +11 -9
  101. package/src/alchemy.ts +25 -11
  102. package/src/apply.ts +3 -1
  103. package/src/cloudflare/bindings.ts +13 -0
  104. package/src/cloudflare/bound.ts +36 -32
  105. package/src/cloudflare/bucket.ts +13 -4
  106. package/src/cloudflare/bun-spa/bun-spa.ts +42 -10
  107. package/src/cloudflare/compatibility-date.gen.ts +1 -1
  108. package/src/cloudflare/d1-database.ts +2 -2
  109. package/src/cloudflare/health-check.ts +617 -0
  110. package/src/cloudflare/index.ts +3 -0
  111. package/src/cloudflare/logpush-job.ts +768 -0
  112. package/src/cloudflare/miniflare/build-worker-options.ts +18 -6
  113. package/src/cloudflare/miniflare/remote-binding-proxy.ts +2 -0
  114. package/src/cloudflare/queue-consumer.ts +2 -2
  115. package/src/cloudflare/worker-loader.ts +12 -0
  116. package/src/cloudflare/worker-metadata.ts +5 -0
  117. package/src/cloudflare/worker-subdomain.ts +1 -1
  118. package/src/cloudflare/worker.ts +8 -0
  119. package/src/cloudflare/wrangler.json.ts +36 -23
  120. package/src/cloudflare/zone.ts +1 -1
  121. package/src/destroy.ts +32 -0
  122. package/src/docker/image.ts +1 -1
  123. package/src/github/comment.ts +17 -8
  124. package/src/resource.ts +1 -1
  125. package/src/scope.ts +32 -25
  126. package/src/state/instrumented-state-store.ts +1 -1
  127. package/src/util/cli-args.ts +11 -0
  128. package/src/util/retry.ts +2 -1
  129. package/src/util/telemetry.ts +68 -2
  130. package/src/util/validate-resource-id.ts +10 -0
  131. package/workers/tunnel-proxy.js +1 -1
@@ -0,0 +1,768 @@
1
+ import type { Context } from "../context.ts";
2
+ import { Resource, ResourceKind } from "../resource.ts";
3
+ import { secret, type Secret } from "../secret.ts";
4
+ import { withExponentialBackoff } from "../util/retry.ts";
5
+ import { AccountApiToken } from "./account-api-token.ts";
6
+ import { handleApiError, type CloudflareApiError } from "./api-error.ts";
7
+ import { extractCloudflareResult } from "./api-response.ts";
8
+ import { createCloudflareApi, type CloudflareApiOptions } from "./api.ts";
9
+ import { isBucket, type R2Bucket } from "./bucket.ts";
10
+
11
+ /**
12
+ * Properties for creating or updating a LogPush Job
13
+ */
14
+ export interface LogPushJobProps extends CloudflareApiOptions {
15
+ /**
16
+ * Zone ID or Zone object for zone-level LogPush jobs
17
+ * Mutually exclusive with accountId
18
+ */
19
+ zone?: string | { id: string; name?: string };
20
+
21
+ /**
22
+ * Name of the dataset. A list of supported datasets can be found on the
23
+ * Developer Docs
24
+ * @default "http_requests"
25
+ * @see https://developers.cloudflare.com/logs/reference/log-fields/
26
+ */
27
+ dataset: LogPushJobDataset;
28
+
29
+ /**
30
+ * Uniquely identifies a resource (such as an s3 bucket) where data will be
31
+ * pushed. Additional configuration parameters supported by the destination
32
+ * may be included (format: uri, maxLength: 4096)
33
+ *
34
+ * Can be:
35
+ * - A full destination string (e.g., "s3://bucket/path" or "r2://bucket/path?account-id=...")
36
+ * - An R2Bucket resource (will use bucket.name and R2 credentials from environment)
37
+ * - A Secret containing a destination string
38
+ */
39
+ destination: string | R2Bucket | Secret<string>;
40
+
41
+ /**
42
+ * Filter to apply to logs (JSON string)
43
+ * @example '{"where":{"and":[{"key":"ClientCountry","operator":"neq","value":"ca"}]}}'
44
+ */
45
+ filter?: string;
46
+
47
+ /**
48
+ * Optional human readable job name. Not unique. Cloudflare suggests that you
49
+ * set this to a meaningful string, like the domain name, to make it easier to
50
+ * identify your job (maxLength: 512)
51
+ */
52
+ name?: string | undefined;
53
+
54
+ /**
55
+ * Flag that indicates if the job is enabled
56
+ */
57
+ enabled?: boolean;
58
+
59
+ /**
60
+ * Ownership challenge token (obtained from ownership validation)
61
+ * Required on creation if destination ownership not yet validated
62
+ */
63
+ ownershipChallenge?: string;
64
+
65
+ /**
66
+ * @deprecated This field is deprecated. Please use maxUploadBytes,
67
+ * maxUploadIntervalSeconds, or maxUploadRecords instead. The frequency at
68
+ * which Cloudflare sends batches of logs to your destination. Setting
69
+ * frequency to high sends your logs in larger quantities of smaller files.
70
+ * Setting frequency to low sends logs in smaller quantities of larger files
71
+ */
72
+ frequency?: "high" | "low" | undefined;
73
+
74
+ /**
75
+ * The kind parameter (optional) is used to differentiate between Logpush and
76
+ * Edge Log Delivery jobs (when supported by the dataset)
77
+ */
78
+ kind?: "edge";
79
+
80
+ /**
81
+ * The maximum uncompressed file size of a batch of logs. This setting value
82
+ * must be between 5 MB and 1 GB, or 0 to disable it. Note that you cannot
83
+ * set a minimum file size; this means that log files may be much smaller than
84
+ * this batch size
85
+ */
86
+ maxUploadBytes?: 0 | number | undefined;
87
+
88
+ /**
89
+ * The maximum interval in seconds for log batches. This setting must be
90
+ * between 30 and 300 seconds (5 minutes), or 0 to disable it. Note that you
91
+ * cannot specify a minimum interval for log batches; this means that log
92
+ * files may be sent in shorter intervals than this
93
+ */
94
+ maxUploadIntervalSeconds?: 0 | number | undefined;
95
+
96
+ /**
97
+ * The maximum number of log lines per batch. This setting must be between
98
+ * 1000 and 1,000,000 lines, or 0 to disable it. Note that you cannot specify
99
+ * a minimum number of log lines per batch; this means that log files may
100
+ * contain many fewer lines than this
101
+ */
102
+ maxUploadRecords?: 0 | number | undefined;
103
+
104
+ /**
105
+ * The structured replacement for logpull_options. When including this field,
106
+ * the logpull_option field will be ignored
107
+ */
108
+ outputOptions?: LogPushJobOutputOptions;
109
+
110
+ /**
111
+ * Whether to delete the LogPush job when removed
112
+ * @default true
113
+ */
114
+ delete?: boolean;
115
+ }
116
+
117
+ export interface LogPushJobOutputOptions {
118
+ /**
119
+ * String to join fields. This field will be ignored when recordTemplate is
120
+ * set
121
+ */
122
+ fieldDelimiter?: string | undefined;
123
+
124
+ /**
125
+ * List of field names to be included in the Logpush output. For the moment,
126
+ * there is no option to add all fields at once, so you must specify all the
127
+ * field names you are interested in
128
+ */
129
+ fieldNames?: string[];
130
+
131
+ /**
132
+ * Specifies the output type, such as ndjson or csv. This sets default
133
+ * values for the rest of the settings, depending on the chosen output type.
134
+ * Some formatting rules, like string quoting, are different between output
135
+ * types
136
+ */
137
+ outputType?: "ndjson" | "csv";
138
+
139
+ /**
140
+ * String to specify the format for timestamps, such as unixnano, unix, or
141
+ * rfc3339
142
+ */
143
+ timestampFormat?: "unixnano" | "unix" | "rfc3339";
144
+
145
+ /**
146
+ * Floating number to specify sampling rate. Sampling is applied on top of
147
+ * filtering, and regardless of the current sample_interval of the data
148
+ * (minimum: 0, maximum: 1)
149
+ */
150
+ sampleRate?: number | undefined;
151
+
152
+ /**
153
+ * Prepended before each batch
154
+ */
155
+ batchPrefix?: string | undefined;
156
+
157
+ /**
158
+ * Appended after each batch
159
+ */
160
+ batchSuffix?: string | undefined;
161
+
162
+ /**
163
+ * If set to true, will cause all occurrences of ${ in the generated files
164
+ * to be replaced with x{
165
+ */
166
+ cve202144228?: boolean | undefined;
167
+
168
+ /**
169
+ * Be inserted in-between the records as separator
170
+ */
171
+ recordDelimiter?: string | undefined;
172
+
173
+ /**
174
+ * Prepended before each record
175
+ */
176
+ recordPrefix?: string | undefined;
177
+
178
+ /**
179
+ * After each record
180
+ */
181
+ recordSuffix?: string | undefined;
182
+
183
+ /**
184
+ * Use as template for each record instead of the default json key value
185
+ * mapping. All fields used in the template must be present in fieldNames as
186
+ * well, otherwise they will end up as null. Format as a Go text/template
187
+ * without any standard functions, like conditionals, loops, sub-templates,
188
+ * etc
189
+ */
190
+ recordTemplate?: string | undefined;
191
+ }
192
+
193
+ /**
194
+ * Output returned after LogPush Job creation/update
195
+ */
196
+ export type LogPushJob = Omit<
197
+ LogPushJobProps,
198
+ "delete" | "ownershipChallenge" | "zone" | "destination"
199
+ > & {
200
+ /**
201
+ * Resource type identifier
202
+ */
203
+ type: "logpush_job";
204
+
205
+ /**
206
+ * Unique id of the job (minimum: 1)
207
+ * Assigned by Cloudflare upon job creation
208
+ */
209
+ id?: number;
210
+
211
+ /**
212
+ * The Cloudflare account ID
213
+ */
214
+ accountId: string;
215
+
216
+ /**
217
+ * The destination of the job
218
+ */
219
+ destination: Secret<string>;
220
+
221
+ /**
222
+ * If not null, the job is currently failing. Failures are usually repetitive
223
+ * (example: no permissions to write to destination bucket). Only the last
224
+ * failure is recorded. On successful execution of a job the errorMessage and
225
+ * lastError are set to null
226
+ */
227
+ errorMessage?: string | undefined;
228
+
229
+ /**
230
+ * Records the last time for which logs have been successfully pushed. If the
231
+ * last successful push was for logs range 2018-07-23T10:00:00Z to
232
+ * 2018-07-23T10:01:00Z then the value of this field will be
233
+ * 2018-07-23T10:01:00Z. If the job has never run or has just been enabled and
234
+ * hasn't run yet then the field will be empty (format: datetime)
235
+ */
236
+ lastComplete?: string | undefined;
237
+
238
+ /**
239
+ * Records the last time the job failed. If not null, the job is currently
240
+ * failing. If null, the job has either never failed or has run successfully
241
+ * at least once since last failure. See also the errorMessage field (format:
242
+ * datetime)
243
+ */
244
+ lastError?: string | undefined;
245
+
246
+ /**
247
+ * Time at which the job was created (Unix timestamp in ms)
248
+ */
249
+ createdAt: number;
250
+
251
+ /**
252
+ * Time at which the job was last modified (Unix timestamp in ms)
253
+ */
254
+ modifiedAt: number;
255
+ };
256
+
257
+ /**
258
+ * Check if a resource is a LogPushJob
259
+ */
260
+ export function isLogPushJob(resource: any): resource is LogPushJob {
261
+ return resource?.[ResourceKind] === "cloudflare::LogPushJob";
262
+ }
263
+
264
+ /**
265
+ * Creates and manages Cloudflare LogPush Jobs for streaming logs to external
266
+ * destinations.
267
+ *
268
+ * LogPush jobs can be scoped to either an account or a zone, and support
269
+ * various log datasets like HTTP requests, firewall events, DNS logs, and more.
270
+ *
271
+ * @example
272
+ * // Basic HTTP request logs to S3 (zone-level)
273
+ * const httpLogs = await LogPushJob("http-logs", {
274
+ * zone: "example.com",
275
+ * dataset: "http_requests",
276
+ * destination: "s3://my-bucket/logs?region=us-west-2",
277
+ * name: "HTTP Request Logs"
278
+ * });
279
+ *
280
+ * @example
281
+ * // Account-level firewall events with filtering using a string destination
282
+ * const blockedRequests = await LogPushJob("blocked-requests", {
283
+ * dataset: "firewall_events",
284
+ * destination: "r2://my-bucket/firewall-logs?account-id=xxx&access-key-id=xxx&secret-access-key=xxx",
285
+ * filter:
286
+ * '{"where":{"and":[{"key":"Action","operator":"eq","value":"block"}]}}',
287
+ * maxUploadBytes: 100 * 1024 * 1024, // 100MB batches
288
+ * maxUploadIntervalSeconds: 300 // 5 minutes
289
+ * });
290
+ *
291
+ * @example
292
+ * // Stream logs to R2 using R2Bucket resource (requires R2_ACCESS_KEY_ID and R2_SECRET_ACCESS_KEY env vars)
293
+ * const bucket = await R2Bucket("logs-bucket", {
294
+ * name: "my-logs-bucket"
295
+ * });
296
+ *
297
+ * const logsToR2 = await LogPushJob("http-to-r2", {
298
+ * dataset: "http_requests",
299
+ * destination: bucket // Automatically constructs R2 URL with env credentials
300
+ * });
301
+ *
302
+ * @example
303
+ * // Or use a direct destination string with embedded credentials
304
+ * const logsToR2 = await LogPushJob("http-to-r2", {
305
+ * dataset: "http_requests",
306
+ * destination: `r2://my-logs-bucket/logs/{DATE}?account-id=${accountId}&access-key-id=${R2_ACCESS_KEY_ID}&secret-access-key=${R2_SECRET_ACCESS_KEY}`
307
+ * });
308
+ *
309
+ * @example
310
+ * // High-volume analytics with custom output format
311
+ * const analyticsLogs = await LogPushJob("analytics-logs", {
312
+ * zone: myZone,
313
+ * dataset: "http_requests",
314
+ * destination: "s3://analytics-bucket/logs?region=eu-west-1",
315
+ * sample: 0.01, // 1% sampling for high-volume sites
316
+ * maxUploadRecords: 100000, // 100k records per batch
317
+ * outputOptions: {
318
+ * outputType: "ndjson",
319
+ * timestampFormat: "unixnano",
320
+ * fieldNames: [
321
+ * "ClientIP",
322
+ * "ClientRequestHost",
323
+ * "EdgeResponseStatus",
324
+ * "EdgeStartTimestamp"
325
+ * ],
326
+ * sampleRate: 0.1 // Additional 10% sampling within the batch
327
+ * }
328
+ * });
329
+ *
330
+ * @see https://developers.cloudflare.com/logs/get-started/enable-destinations/
331
+ * @see https://developers.cloudflare.com/api/resources/logpush/
332
+ */
333
+ export function LogPushJob(
334
+ id: string,
335
+ props: LogPushJobProps,
336
+ ): Promise<LogPushJob> {
337
+ return _LogPushJob(id, {
338
+ ...props,
339
+ destination:
340
+ typeof props.destination === "string"
341
+ ? secret(props.destination)
342
+ : isBucket(props.destination)
343
+ ? props.destination
344
+ : props.destination,
345
+ });
346
+ }
347
+
348
+ const _LogPushJob = Resource(
349
+ "cloudflare::LogPushJob",
350
+ async function (
351
+ this: Context<LogPushJob>,
352
+ _id: string,
353
+ props: Omit<LogPushJobProps, "destination"> & {
354
+ destination: Secret<string> | R2Bucket;
355
+ },
356
+ ): Promise<LogPushJob> {
357
+ const api = await createCloudflareApi(props);
358
+ const isZoneScoped = !!props.zone;
359
+
360
+ let zoneId: string | undefined;
361
+ let accountId: string | undefined;
362
+
363
+ if (isZoneScoped) {
364
+ zoneId = typeof props.zone === "string" ? props.zone : props.zone!.id;
365
+ } else {
366
+ accountId = api.accountId;
367
+ }
368
+
369
+ const basePath = isZoneScoped
370
+ ? `/zones/${zoneId}/logpush/jobs`
371
+ : `/accounts/${accountId}/logpush/jobs`;
372
+
373
+ if (this.phase === "delete") {
374
+ if (this.output?.id && props.delete !== false) {
375
+ const deleteResponse = await api.delete(
376
+ `${basePath}/${this.output.id}`,
377
+ );
378
+
379
+ if (!deleteResponse.ok && deleteResponse.status !== 404) {
380
+ await handleApiError(
381
+ deleteResponse,
382
+ "delete",
383
+ "logpush_job",
384
+ String(this.output.id),
385
+ );
386
+ }
387
+ }
388
+ return this.destroy();
389
+ }
390
+
391
+ let destination: string;
392
+ let apiToken: AccountApiToken | undefined;
393
+
394
+ if (isBucket(props.destination)) {
395
+ const bucket = props.destination;
396
+ let accessKeyId = process.env.R2_ACCESS_KEY_ID;
397
+ let secretAccessKey = process.env.R2_SECRET_ACCESS_KEY;
398
+
399
+ if (!accessKeyId || !secretAccessKey) {
400
+ try {
401
+ apiToken = await AccountApiToken("token", {
402
+ accountId: props.accountId,
403
+ apiKey: props.apiKey,
404
+ apiToken: props.apiToken,
405
+ baseUrl: props.baseUrl,
406
+ profile: props.profile,
407
+ email: props.email,
408
+ policies: [
409
+ {
410
+ effect: "allow",
411
+ permissionGroups: [
412
+ "Workers R2 Storage Write",
413
+ "Workers R2 Storage Read",
414
+ "Workers R2 Storage Bucket Item Read",
415
+ "Workers R2 Storage Bucket Item Write",
416
+ ],
417
+ resources: {
418
+ [`com.cloudflare.edge.r2.bucket.${api.accountId}_${bucket.jurisdiction ?? "default"}_${bucket.name}`]:
419
+ "*",
420
+ },
421
+ },
422
+ ],
423
+ });
424
+ accessKeyId = apiToken.accessKeyId.unencrypted;
425
+ secretAccessKey = apiToken.secretAccessKey.unencrypted;
426
+ } catch (err) {
427
+ console.error(err);
428
+ console.warn(
429
+ "[Cloudflare Logpush Job] Warning: Cloudflare currently only allows the use of a Global API Key or an API Token with permission to create other API Tokens in order to generate new API Tokens programmatically.\n" +
430
+ "Please use your Global API Key, or create an API Token with the necessary permissions. For more information, see: https://alchemy.run/guides/cloudflare/#api-token",
431
+ );
432
+ throw new Error(
433
+ "Unable to create an API Token: Cloudflare only allows Global API Key or an API Token with permission to create other API Tokens. " +
434
+ "See https://alchemy.run/guides/cloudflare/#api-token for more details.",
435
+ );
436
+ }
437
+ }
438
+
439
+ destination = `r2://${bucket.name}/logs/{DATE}?${new URLSearchParams({
440
+ "account-id": api.accountId,
441
+ "access-key-id": accessKeyId,
442
+ "secret-access-key": secretAccessKey,
443
+ }).toString()}`;
444
+ } else {
445
+ destination = props.destination.unencrypted;
446
+ }
447
+
448
+ const jobConfig: LogPushJobConfig = {
449
+ dataset: props.dataset,
450
+ destination_conf: destination,
451
+ ...(props.name && { name: props.name }),
452
+ ...(props.enabled !== undefined && { enabled: props.enabled }),
453
+ ...(props.frequency && { frequency: props.frequency }),
454
+ ...(props.kind !== undefined && { kind: props.kind }),
455
+ ...(props.maxUploadBytes !== undefined && {
456
+ max_upload_bytes: props.maxUploadBytes,
457
+ }),
458
+ ...(props.maxUploadIntervalSeconds !== undefined && {
459
+ max_upload_interval_seconds: props.maxUploadIntervalSeconds,
460
+ }),
461
+ ...(props.maxUploadRecords !== undefined && {
462
+ max_upload_records: props.maxUploadRecords,
463
+ }),
464
+ ...(props.ownershipChallenge && {
465
+ ownership_challenge: props.ownershipChallenge,
466
+ }),
467
+ };
468
+
469
+ if (props.outputOptions) {
470
+ jobConfig.output_options = {
471
+ ...(props.outputOptions.outputType && {
472
+ output_type: props.outputOptions.outputType,
473
+ }),
474
+ ...(props.outputOptions.timestampFormat && {
475
+ timestamp_format: props.outputOptions.timestampFormat,
476
+ }),
477
+ ...(props.outputOptions.fieldNames && {
478
+ field_names: props.outputOptions.fieldNames,
479
+ }),
480
+ ...(props.outputOptions.fieldDelimiter && {
481
+ field_delimiter: props.outputOptions.fieldDelimiter,
482
+ }),
483
+ ...(props.outputOptions.sampleRate !== undefined && {
484
+ sample_rate: props.outputOptions.sampleRate,
485
+ }),
486
+ ...(props.outputOptions.batchPrefix && {
487
+ batch_prefix: props.outputOptions.batchPrefix,
488
+ }),
489
+ ...(props.outputOptions.batchSuffix && {
490
+ batch_suffix: props.outputOptions.batchSuffix,
491
+ }),
492
+ ...(props.outputOptions.cve202144228 !== undefined && {
493
+ "CVE-2021-44228": props.outputOptions.cve202144228,
494
+ }),
495
+ ...(props.outputOptions.recordDelimiter && {
496
+ record_delimiter: props.outputOptions.recordDelimiter,
497
+ }),
498
+ ...(props.outputOptions.recordPrefix && {
499
+ record_prefix: props.outputOptions.recordPrefix,
500
+ }),
501
+ ...(props.outputOptions.recordSuffix && {
502
+ record_suffix: props.outputOptions.recordSuffix,
503
+ }),
504
+ ...(props.outputOptions.recordTemplate && {
505
+ record_template: props.outputOptions.recordTemplate,
506
+ }),
507
+ };
508
+ }
509
+
510
+ const jobData = await withExponentialBackoff(
511
+ async () => {
512
+ if (this.phase === "update" && this.output?.id) {
513
+ return await extractCloudflareResult<LogPushJobConfig>(
514
+ `update logpush job ${this.output.id}`,
515
+ api.put(`${basePath}/${this.output.id}`, jobConfig),
516
+ );
517
+ } else {
518
+ return await extractCloudflareResult<LogPushJobConfig>(
519
+ `create logpush job for dataset ${props.dataset}`,
520
+ api.post(basePath, jobConfig),
521
+ );
522
+ }
523
+ },
524
+ // if we just recently created an api token for R2, we can retry on 1002 which are caused by token propagation
525
+ (error: CloudflareApiError) => {
526
+ console.warn(
527
+ "Received error when creating LogPush job, there may be a propagation delay",
528
+ error.message,
529
+ );
530
+ return error.errorData?.[0]?.code === 1002;
531
+ },
532
+ 30,
533
+ 100,
534
+ );
535
+
536
+ return {
537
+ type: "logpush_job",
538
+ id: jobData.id,
539
+ accountId: api.accountId,
540
+ dataset: jobData.dataset ?? props.dataset,
541
+ destination: secret(jobData.destination_conf ?? destination),
542
+ name: jobData.name ?? undefined,
543
+ enabled: jobData.enabled ?? props.enabled ?? true,
544
+ frequency: jobData.frequency ?? undefined,
545
+ filter: props.filter,
546
+ maxUploadBytes: jobData.max_upload_bytes ?? undefined,
547
+ maxUploadIntervalSeconds:
548
+ jobData.max_upload_interval_seconds ?? undefined,
549
+ maxUploadRecords: jobData.max_upload_records ?? undefined,
550
+ outputOptions: jobData.output_options
551
+ ? {
552
+ outputType: jobData.output_options.output_type,
553
+ timestampFormat: jobData.output_options.timestamp_format,
554
+ fieldNames: jobData.output_options.field_names,
555
+ fieldDelimiter: jobData.output_options.field_delimiter ?? undefined,
556
+ sampleRate: jobData.output_options.sample_rate ?? undefined,
557
+ batchPrefix: jobData.output_options.batch_prefix ?? undefined,
558
+ batchSuffix: jobData.output_options.batch_suffix ?? undefined,
559
+ cve202144228: jobData.output_options["CVE-2021-44228"] ?? undefined,
560
+ recordDelimiter:
561
+ jobData.output_options.record_delimiter ?? undefined,
562
+ recordPrefix: jobData.output_options.record_prefix ?? undefined,
563
+ recordSuffix: jobData.output_options.record_suffix ?? undefined,
564
+ recordTemplate: jobData.output_options.record_template ?? undefined,
565
+ }
566
+ : undefined,
567
+ kind: jobData.kind || undefined,
568
+ errorMessage: jobData.error_message ?? undefined,
569
+ lastComplete: jobData.last_complete ?? undefined,
570
+ lastError: jobData.last_error ?? undefined,
571
+ createdAt: this.output?.createdAt ?? Date.now(),
572
+ modifiedAt: Date.now(),
573
+ };
574
+ },
575
+ );
576
+ /**
577
+ * The structured replacement for logpull_options. When including this field, the logpull_option field will be ignored.
578
+ */
579
+ export interface OutputOptions {
580
+ /**
581
+ * String to be prepended before each batch.
582
+ */
583
+ batch_prefix?: string | null;
584
+
585
+ /**
586
+ * String to be appended after each batch.
587
+ */
588
+ batch_suffix?: string | null;
589
+
590
+ /**
591
+ * If set to true, will cause all occurrences of ${ in the generated files to be replaced with x{.
592
+ */
593
+ "CVE-2021-44228"?: boolean | null;
594
+
595
+ /**
596
+ * String to join fields. This field will be ignored when record_template is set.
597
+ */
598
+ field_delimiter?: string | null;
599
+
600
+ /**
601
+ * List of field names to be included in the Logpush output.
602
+ * For the moment, there is no option to add all fields at once, so you must specify all the field names you are interested in.
603
+ */
604
+ field_names?: string[];
605
+
606
+ /**
607
+ * Specifies the output type, such as ndjson or csv.
608
+ * This sets default values for the rest of the settings, depending on the chosen output type.
609
+ * Some formatting rules, like string quoting, are different between output types.
610
+ */
611
+ output_type?: "ndjson" | "csv";
612
+
613
+ /**
614
+ * String to be inserted in-between the records as separator.
615
+ */
616
+ record_delimiter?: string | null;
617
+
618
+ /**
619
+ * String to be prepended before each record.
620
+ */
621
+ record_prefix?: string | null;
622
+
623
+ /**
624
+ * String to be appended after each record.
625
+ */
626
+ record_suffix?: string | null;
627
+
628
+ /**
629
+ * String to use as template for each record instead of the default json key value mapping.
630
+ * All fields used in the template must be present in field_names as well, otherwise they will end up as null.
631
+ * Format as a Go text/template without any standard functions, like conditionals, loops, sub-templates, etc.
632
+ */
633
+ record_template?: string | null;
634
+
635
+ /**
636
+ * Floating number to specify sampling rate. Sampling is applied on top of filtering, and regardless of the current sample_interval of the data.
637
+ * (format: float, maximum: 1, minimum: 0)
638
+ */
639
+ sample_rate?: number | null;
640
+
641
+ /**
642
+ * String to specify the format for timestamps, such as unixnano, unix, or rfc3339.
643
+ */
644
+ timestamp_format?: "unixnano" | "unix" | "rfc3339";
645
+ }
646
+
647
+ export type LogPushJobDataset =
648
+ | "access_requests"
649
+ | "audit_logs_v2"
650
+ | "audit_logs"
651
+ | "biso_user_actions"
652
+ | "casb_findings"
653
+ | "device_posture_results"
654
+ | "dlp_forensic_copies"
655
+ | "dns_firewall_logs"
656
+ | "dns_logs"
657
+ | "email_security_alerts"
658
+ | "firewall_events"
659
+ | "gateway_dns"
660
+ | "gateway_http"
661
+ | "gateway_network"
662
+ | "http_requests"
663
+ | "magic_ids_detections"
664
+ | "nel_reports"
665
+ | "network_analytics_logs"
666
+ | "page_shield_events"
667
+ | "sinkhole_http_logs"
668
+ | "spectrum_events"
669
+ | "ssh_logs"
670
+ | "workers_trace_events"
671
+ | "zaraz_events"
672
+ | "zero_trust_network_sessions"
673
+ | (string & {});
674
+
675
+ /**
676
+ * Raw Cloudflare API response for LogPush Job
677
+ * @internal
678
+ */
679
+ interface LogPushJobConfig {
680
+ /**
681
+ * Unique id of the job.
682
+ * (minimum: 1)
683
+ */
684
+ id?: number;
685
+
686
+ /**
687
+ * Name of the dataset. A list of supported datasets can be found on the Developer Docs.
688
+ * (default: "http_requests")
689
+ */
690
+ dataset?: LogPushJobDataset | null;
691
+
692
+ /**
693
+ * Uniquely identifies a resource (such as an s3 bucket) where data will be pushed.
694
+ * (format: uri, maxLength: 4096)
695
+ */
696
+ destination_conf?: string;
697
+
698
+ /**
699
+ * Flag that indicates if the job is enabled.
700
+ */
701
+ enabled?: boolean;
702
+
703
+ /**
704
+ * If not null, the job is currently failing. Only the last failure is recorded.
705
+ */
706
+ error_message?: string | null;
707
+
708
+ /**
709
+ * Deprecated. Please use max_upload_* parameters instead.
710
+ * The frequency at which Cloudflare sends batches of logs to your destination.
711
+ * (default: "high")
712
+ */
713
+ frequency?: "high" | "low" | null;
714
+
715
+ /**
716
+ * The kind parameter (optional) is used to differentiate between Logpush and Edge Log Delivery jobs.
717
+ */
718
+ kind?: "" | "edge";
719
+
720
+ /**
721
+ * Records the last time for which logs have been successfully pushed.
722
+ * (format: date-time)
723
+ */
724
+ last_complete?: string | null;
725
+
726
+ /**
727
+ * Records the last time the job failed.
728
+ * (format: date-time)
729
+ */
730
+ last_error?: string | null;
731
+
732
+ /**
733
+ * Deprecated. Use output_options instead.
734
+ * Configuration string.
735
+ * (format: uri-reference, maxLength: 4096)
736
+ */
737
+ logpull_options?: string | null;
738
+
739
+ /**
740
+ * The maximum uncompressed file size of a batch of logs.
741
+ * Must be between 5 MB and 1 GB, or 0 to disable it.
742
+ */
743
+ max_upload_bytes?: 0 | number | null;
744
+
745
+ /**
746
+ * The maximum interval in seconds for log batches.
747
+ * Must be between 30 and 300 seconds, or 0 to disable it.
748
+ */
749
+ max_upload_interval_seconds?: 0 | number | null;
750
+
751
+ /**
752
+ * The maximum number of log lines per batch.
753
+ * Must be between 1000 and 1,000,000 lines, or 0 to disable it.
754
+ */
755
+ max_upload_records?: 0 | number | null;
756
+
757
+ /**
758
+ * Optional human readable job name. Not unique.
759
+ * (maxLength: 512)
760
+ */
761
+ name?: string | null;
762
+
763
+ /**
764
+ * The structured replacement for logpull_options.
765
+ * When including this field, the logpull_option field will be ignored.
766
+ */
767
+ output_options?: OutputOptions | null;
768
+ }