firebase-functions 3.21.1 → 3.23.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.
Files changed (49) hide show
  1. package/lib/bin/firebase-functions.js +2 -1
  2. package/lib/cloud-functions.d.ts +1 -48
  3. package/lib/cloud-functions.js +2 -59
  4. package/lib/common/change.d.ts +46 -0
  5. package/lib/common/change.js +82 -0
  6. package/lib/common/providers/database.d.ts +145 -0
  7. package/lib/common/providers/database.js +271 -0
  8. package/lib/common/providers/identity.js +12 -7
  9. package/lib/common/providers/tasks.d.ts +8 -7
  10. package/lib/common/providers/tasks.js +13 -12
  11. package/lib/common/timezone.d.ts +2 -0
  12. package/lib/common/timezone.js +543 -0
  13. package/lib/function-builder.d.ts +2 -2
  14. package/lib/function-builder.js +2 -2
  15. package/lib/function-configuration.d.ts +6 -5
  16. package/lib/providers/database.d.ts +4 -146
  17. package/lib/providers/database.js +7 -251
  18. package/lib/providers/firestore.d.ts +2 -1
  19. package/lib/providers/firestore.js +2 -1
  20. package/lib/runtime/loader.js +6 -1
  21. package/lib/runtime/manifest.d.ts +19 -16
  22. package/lib/runtime/manifest.js +24 -0
  23. package/lib/utilities/path-pattern.d.ts +1 -0
  24. package/lib/utilities/path-pattern.js +142 -0
  25. package/lib/v2/core.d.ts +2 -0
  26. package/lib/v2/core.js +7 -0
  27. package/lib/v2/index.d.ts +4 -1
  28. package/lib/v2/index.js +7 -1
  29. package/lib/v2/options.d.ts +16 -6
  30. package/lib/v2/options.js +2 -2
  31. package/lib/v2/params/index.d.ts +14 -12
  32. package/lib/v2/params/index.js +25 -15
  33. package/lib/v2/params/types.d.ts +97 -24
  34. package/lib/v2/params/types.js +127 -67
  35. package/lib/v2/providers/alerts/alerts.d.ts +7 -6
  36. package/lib/v2/providers/alerts/appDistribution.d.ts +50 -5
  37. package/lib/v2/providers/alerts/appDistribution.js +23 -1
  38. package/lib/v2/providers/alerts/crashlytics.d.ts +6 -5
  39. package/lib/v2/providers/database.d.ts +183 -0
  40. package/lib/v2/providers/database.js +204 -0
  41. package/lib/v2/providers/eventarc.d.ts +6 -5
  42. package/lib/v2/providers/https.d.ts +6 -5
  43. package/lib/v2/providers/identity.d.ts +8 -7
  44. package/lib/v2/providers/pubsub.d.ts +6 -5
  45. package/lib/v2/providers/scheduler.d.ts +63 -0
  46. package/lib/v2/providers/scheduler.js +98 -0
  47. package/lib/v2/providers/storage.d.ts +6 -5
  48. package/lib/v2/providers/tasks.d.ts +7 -6
  49. package/package.json +18 -8
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ // The MIT License (MIT)
3
+ //
4
+ // Copyright (c) 2022 Firebase
5
+ //
6
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ // of this software and associated documentation files (the "Software"), to deal
8
+ // in the Software without restriction, including without limitation the rights
9
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ // copies of the Software, and to permit persons to whom the Software is
11
+ // furnished to do so, subject to the following conditions:
12
+ //
13
+ // The above copyright notice and this permission notice shall be included in all
14
+ // copies or substantial portions of the Software.
15
+ //
16
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ // SOFTWARE.
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.onOperation = exports.onChangedOperation = exports.makeEndpoint = exports.makeParams = exports.getOpts = exports.onValueDeleted = exports.onValueUpdated = exports.onValueCreated = exports.onValueWritten = exports.deletedEventType = exports.updatedEventType = exports.createdEventType = exports.writtenEventType = exports.DataSnapshot = void 0;
25
+ const apps_1 = require("../../apps");
26
+ const database_1 = require("../../common/providers/database");
27
+ Object.defineProperty(exports, "DataSnapshot", { enumerable: true, get: function () { return database_1.DataSnapshot; } });
28
+ const path_1 = require("../../utilities/path");
29
+ const path_pattern_1 = require("../../utilities/path-pattern");
30
+ const utils_1 = require("../../utils");
31
+ const options = require("../options");
32
+ /** @internal */
33
+ exports.writtenEventType = 'google.firebase.database.ref.v1.written';
34
+ /** @internal */
35
+ exports.createdEventType = 'google.firebase.database.ref.v1.created';
36
+ /** @internal */
37
+ exports.updatedEventType = 'google.firebase.database.ref.v1.updated';
38
+ /** @internal */
39
+ exports.deletedEventType = 'google.firebase.database.ref.v1.deleted';
40
+ /**
41
+ * Event handler which triggers when data is created, updated, or deleted in Realtime Database.
42
+ *
43
+ * @param referenceOrOpts - Options or a string reference.
44
+ * @param handler - Event handler which is run every time a Realtime Database create, update, or delete occurs.
45
+ */
46
+ function onValueWritten(referenceOrOpts, handler) {
47
+ return onChangedOperation(exports.writtenEventType, referenceOrOpts, handler);
48
+ }
49
+ exports.onValueWritten = onValueWritten;
50
+ /**
51
+ * Event handler which triggers when data is created in Realtime Database.
52
+ *
53
+ * @param referenceOrOpts - Options or a string reference.
54
+ * @param handler - Event handler which is run every time a Realtime Database create occurs.
55
+ */
56
+ function onValueCreated(referenceOrOpts, handler) {
57
+ return onOperation(exports.createdEventType, referenceOrOpts, handler);
58
+ }
59
+ exports.onValueCreated = onValueCreated;
60
+ /**
61
+ * Event handler which triggers when data is updated in Realtime Database.
62
+ *
63
+ * @param referenceOrOpts - Options or a string reference.
64
+ * @param handler - Event handler which is run every time a Realtime Database update occurs.
65
+ */
66
+ function onValueUpdated(referenceOrOpts, handler) {
67
+ return onChangedOperation(exports.updatedEventType, referenceOrOpts, handler);
68
+ }
69
+ exports.onValueUpdated = onValueUpdated;
70
+ /**
71
+ * Event handler which triggers when data is deleted in Realtime Database.
72
+ *
73
+ * @param referenceOrOpts - Options or a string reference.
74
+ * @param handler - Event handler which is run every time a Realtime Database deletion occurs.
75
+ */
76
+ function onValueDeleted(referenceOrOpts, handler) {
77
+ // TODO - need to use event.data.delta
78
+ return onOperation(exports.deletedEventType, referenceOrOpts, handler);
79
+ }
80
+ exports.onValueDeleted = onValueDeleted;
81
+ /** @internal */
82
+ function getOpts(referenceOrOpts) {
83
+ let path, instance, opts;
84
+ if (typeof referenceOrOpts === 'string') {
85
+ path = (0, path_1.normalizePath)(referenceOrOpts);
86
+ instance = '*';
87
+ opts = {};
88
+ }
89
+ else {
90
+ path = (0, path_1.normalizePath)(referenceOrOpts.ref);
91
+ instance = referenceOrOpts.instance || '*';
92
+ opts = { ...referenceOrOpts };
93
+ delete opts.ref;
94
+ delete opts.instance;
95
+ }
96
+ return {
97
+ path,
98
+ instance,
99
+ opts,
100
+ };
101
+ }
102
+ exports.getOpts = getOpts;
103
+ /** @internal */
104
+ function makeParams(event, path, instance) {
105
+ return {
106
+ ...path.extractMatches(event.ref),
107
+ ...instance.extractMatches(event.instance),
108
+ };
109
+ }
110
+ exports.makeParams = makeParams;
111
+ /** @hidden */
112
+ function makeDatabaseEvent(event, data, instance, params) {
113
+ const snapshot = new database_1.DataSnapshot(data, event.ref, (0, apps_1.apps)().admin, instance);
114
+ const databaseEvent = {
115
+ ...event,
116
+ firebaseDatabaseHost: event.firebasedatabasehost,
117
+ data: snapshot,
118
+ params,
119
+ };
120
+ delete databaseEvent.firebasedatabasehost;
121
+ return databaseEvent;
122
+ }
123
+ /** @hidden */
124
+ function makeChangedDatabaseEvent(event, instance, params) {
125
+ const before = new database_1.DataSnapshot(event.data.data, event.ref, (0, apps_1.apps)().admin, instance);
126
+ const after = new database_1.DataSnapshot((0, utils_1.applyChange)(event.data.data, event.data.delta), event.ref, (0, apps_1.apps)().admin, instance);
127
+ const databaseEvent = {
128
+ ...event,
129
+ firebaseDatabaseHost: event.firebasedatabasehost,
130
+ data: {
131
+ before,
132
+ after,
133
+ },
134
+ params,
135
+ };
136
+ delete databaseEvent.firebasedatabasehost;
137
+ return databaseEvent;
138
+ }
139
+ /** @internal */
140
+ function makeEndpoint(eventType, opts, path, instance) {
141
+ const baseOpts = options.optionsToEndpoint(options.getGlobalOptions());
142
+ const specificOpts = options.optionsToEndpoint(opts);
143
+ const eventFilters = {};
144
+ const eventFilterPathPatterns = {
145
+ // Note: Eventarc always treats ref as a path pattern
146
+ ref: path.getValue(),
147
+ };
148
+ instance.hasWildcards()
149
+ ? (eventFilterPathPatterns.instance = instance.getValue())
150
+ : (eventFilters.instance = instance.getValue());
151
+ return {
152
+ platform: 'gcfv2',
153
+ ...baseOpts,
154
+ ...specificOpts,
155
+ labels: {
156
+ ...baseOpts === null || baseOpts === void 0 ? void 0 : baseOpts.labels,
157
+ ...specificOpts === null || specificOpts === void 0 ? void 0 : specificOpts.labels,
158
+ },
159
+ eventTrigger: {
160
+ eventType,
161
+ eventFilters,
162
+ eventFilterPathPatterns,
163
+ retry: false,
164
+ },
165
+ };
166
+ }
167
+ exports.makeEndpoint = makeEndpoint;
168
+ /** @internal */
169
+ function onChangedOperation(eventType, referenceOrOpts, handler) {
170
+ const { path, instance, opts } = getOpts(referenceOrOpts);
171
+ const pathPattern = new path_pattern_1.PathPattern(path);
172
+ const instancePattern = new path_pattern_1.PathPattern(instance);
173
+ // wrap the handler
174
+ const func = (raw) => {
175
+ const event = raw;
176
+ const instanceUrl = `https://${event.instance}.${event.firebasedatabasehost}`;
177
+ const params = makeParams(event, pathPattern, instancePattern);
178
+ const databaseEvent = makeChangedDatabaseEvent(event, instanceUrl, params);
179
+ return handler(databaseEvent);
180
+ };
181
+ func.run = handler;
182
+ func.__endpoint = makeEndpoint(eventType, opts, pathPattern, instancePattern);
183
+ return func;
184
+ }
185
+ exports.onChangedOperation = onChangedOperation;
186
+ /** @internal */
187
+ function onOperation(eventType, referenceOrOpts, handler) {
188
+ const { path, instance, opts } = getOpts(referenceOrOpts);
189
+ const pathPattern = new path_pattern_1.PathPattern(path);
190
+ const instancePattern = new path_pattern_1.PathPattern(instance);
191
+ // wrap the handler
192
+ const func = (raw) => {
193
+ const event = raw;
194
+ const instanceUrl = `https://${event.instance}.${event.firebasedatabasehost}`;
195
+ const params = makeParams(event, pathPattern, instancePattern);
196
+ const data = eventType === exports.deletedEventType ? event.data.data : event.data.delta;
197
+ const databaseEvent = makeDatabaseEvent(event, data, instanceUrl, params);
198
+ return handler(databaseEvent);
199
+ };
200
+ func.run = handler;
201
+ func.__endpoint = makeEndpoint(eventType, opts, pathPattern, instancePattern);
202
+ return func;
203
+ }
204
+ exports.onOperation = onOperation;
@@ -1,5 +1,6 @@
1
1
  import { CloudEvent, CloudFunction } from '../core';
2
2
  import * as options from '../options';
3
+ import { Expression } from '../params';
3
4
  /** Options that can be set on an Eventarc trigger. */
4
5
  export interface EventarcTriggerOptions extends options.EventHandlerOptions {
5
6
  /**
@@ -33,7 +34,7 @@ export interface EventarcTriggerOptions extends options.EventHandlerOptions {
33
34
  * Amount of memory to allocate to a function.
34
35
  * A value of null restores the defaults of 256MB.
35
36
  */
36
- memory?: options.MemoryOption | null;
37
+ memory?: options.MemoryOption | Expression<number> | null;
37
38
  /**
38
39
  * Timeout for the function in sections, possible values are 0 to 540.
39
40
  * HTTPS functions can specify a higher timeout.
@@ -44,19 +45,19 @@ export interface EventarcTriggerOptions extends options.EventHandlerOptions {
44
45
  * maximum timeout of 36,00s (1 hour). Task queue functions have a maximum
45
46
  * timeout of 1,800s (30 minutes)
46
47
  */
47
- timeoutSeconds?: number | null;
48
+ timeoutSeconds?: number | Expression<number> | null;
48
49
  /**
49
50
  * Min number of actual instances to be running at a given time.
50
51
  * Instances will be billed for memory allocation and 10% of CPU allocation
51
52
  * while idle.
52
53
  * A value of null restores the default min instances.
53
54
  */
54
- minInstances?: number | null;
55
+ minInstances?: number | Expression<number> | null;
55
56
  /**
56
57
  * Max number of instances to be running in parallel.
57
58
  * A value of null restores the default max instances.
58
59
  */
59
- maxInstances?: number | null;
60
+ maxInstances?: number | Expression<number> | null;
60
61
  /**
61
62
  * Number of requests a function can serve at once.
62
63
  * Can only be applied to functions running on Cloud Functions v2.
@@ -64,7 +65,7 @@ export interface EventarcTriggerOptions extends options.EventHandlerOptions {
64
65
  * Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
65
66
  * The maximum value for concurrency is 1,000.
66
67
  */
67
- concurrency?: number | null;
68
+ concurrency?: number | Expression<number> | null;
68
69
  /**
69
70
  * Fractional number of CPUs to allocate to a function.
70
71
  * Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
@@ -3,6 +3,7 @@ import { CallableRequest, FunctionsErrorCode, HttpsError, Request } from '../../
3
3
  import { ManifestEndpoint } from '../../runtime/manifest';
4
4
  import * as options from '../options';
5
5
  import { GlobalOptions, SupportedRegion } from '../options';
6
+ import { Expression } from '../params';
6
7
  export { Request, CallableRequest, FunctionsErrorCode, HttpsError };
7
8
  /**
8
9
  * Options that can be set on an individual HTTPS function.
@@ -20,7 +21,7 @@ export interface HttpsOptions extends Omit<GlobalOptions, 'region'> {
20
21
  * Amount of memory to allocate to a function.
21
22
  * A value of null restores the defaults of 256MB.
22
23
  */
23
- memory?: options.MemoryOption | null;
24
+ memory?: options.MemoryOption | Expression<number> | null;
24
25
  /**
25
26
  * Timeout for the function in sections, possible values are 0 to 540.
26
27
  * HTTPS functions can specify a higher timeout.
@@ -31,19 +32,19 @@ export interface HttpsOptions extends Omit<GlobalOptions, 'region'> {
31
32
  * maximum timeout of 36,00s (1 hour). Task queue functions have a maximum
32
33
  * timeout of 1,800s (30 minutes)
33
34
  */
34
- timeoutSeconds?: number | null;
35
+ timeoutSeconds?: number | Expression<number> | null;
35
36
  /**
36
37
  * Min number of actual instances to be running at a given time.
37
38
  * Instances will be billed for memory allocation and 10% of CPU allocation
38
39
  * while idle.
39
40
  * A value of null restores the default min instances.
40
41
  */
41
- minInstances?: number | null;
42
+ minInstances?: number | Expression<number> | null;
42
43
  /**
43
44
  * Max number of instances to be running in parallel.
44
45
  * A value of null restores the default max instances.
45
46
  */
46
- maxInstances?: number | null;
47
+ maxInstances?: number | Expression<number> | null;
47
48
  /**
48
49
  * Number of requests a function can serve at once.
49
50
  * Can only be applied to functions running on Cloud Functions v2.
@@ -51,7 +52,7 @@ export interface HttpsOptions extends Omit<GlobalOptions, 'region'> {
51
52
  * Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
52
53
  * The maximum value for concurrency is 1,000.
53
54
  */
54
- concurrency?: number | null;
55
+ concurrency?: number | Expression<number> | null;
55
56
  /**
56
57
  * Fractional number of CPUs to allocate to a function.
57
58
  * Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
@@ -3,9 +3,10 @@
3
3
  * @packageDocumentation
4
4
  */
5
5
  import { BlockingFunction } from '../../cloud-functions';
6
- import { AuthBlockingEvent, AuthBlockingEventType, BeforeCreateResponse, BeforeSignInResponse, HttpsError } from '../../common/providers/identity';
6
+ import { AuthBlockingEvent, AuthBlockingEventType, AuthUserRecord, BeforeCreateResponse, BeforeSignInResponse, HttpsError } from '../../common/providers/identity';
7
7
  import * as options from '../options';
8
- export { HttpsError };
8
+ import { Expression } from '../params';
9
+ export { AuthUserRecord, AuthBlockingEvent, HttpsError };
9
10
  /** @hidden Internally used when parsing the options. */
10
11
  interface InternalOptions {
11
12
  opts: options.GlobalOptions;
@@ -31,7 +32,7 @@ export interface BlockingOptions {
31
32
  * Amount of memory to allocate to a function.
32
33
  * A value of null restores the defaults of 256MB.
33
34
  */
34
- memory?: options.MemoryOption | null;
35
+ memory?: options.MemoryOption | Expression<number> | null;
35
36
  /**
36
37
  * Timeout for the function in sections, possible values are 0 to 540.
37
38
  * HTTPS functions can specify a higher timeout.
@@ -42,19 +43,19 @@ export interface BlockingOptions {
42
43
  * maximum timeout of 36,00s (1 hour). Task queue functions have a maximum
43
44
  * timeout of 1,800s (30 minutes)
44
45
  */
45
- timeoutSeconds?: number | null;
46
+ timeoutSeconds?: number | Expression<number> | null;
46
47
  /**
47
48
  * Min number of actual instances to be running at a given time.
48
49
  * Instances will be billed for memory allocation and 10% of CPU allocation
49
50
  * while idle.
50
51
  * A value of null restores the default min instances.
51
52
  */
52
- minInstances?: number | null;
53
+ minInstances?: number | Expression<number> | null;
53
54
  /**
54
55
  * Max number of instances to be running in parallel.
55
56
  * A value of null restores the default max instances.
56
57
  */
57
- maxInstances?: number | null;
58
+ maxInstances?: number | Expression<number> | null;
58
59
  /**
59
60
  * Number of requests a function can serve at once.
60
61
  * Can only be applied to functions running on Cloud Functions v2.
@@ -62,7 +63,7 @@ export interface BlockingOptions {
62
63
  * Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
63
64
  * The maximum value for concurrency is 1,000.
64
65
  */
65
- concurrency?: number | null;
66
+ concurrency?: number | Expression<number> | null;
66
67
  /**
67
68
  * Fractional number of CPUs to allocate to a function.
68
69
  * Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
@@ -1,5 +1,6 @@
1
1
  import { CloudEvent, CloudFunction } from '../core';
2
2
  import * as options from '../options';
3
+ import { Expression } from '../params';
3
4
  /**
4
5
  * Google Cloud Pub/Sub is a globally distributed message bus that automatically scales as you need it.
5
6
  * You can create a function ({@link onMessagePublished}) that handles pub/sub events by using functions.pubsub.
@@ -89,7 +90,7 @@ export interface PubSubOptions extends options.EventHandlerOptions {
89
90
  * Amount of memory to allocate to a function.
90
91
  * A value of null restores the defaults of 256MB.
91
92
  */
92
- memory?: options.MemoryOption | null;
93
+ memory?: options.MemoryOption | Expression<number> | null;
93
94
  /**
94
95
  * Timeout for the function in sections, possible values are 0 to 540.
95
96
  * HTTPS functions can specify a higher timeout.
@@ -100,19 +101,19 @@ export interface PubSubOptions extends options.EventHandlerOptions {
100
101
  * maximum timeout of 36,00s (1 hour). Task queue functions have a maximum
101
102
  * timeout of 1,800s (30 minutes)
102
103
  */
103
- timeoutSeconds?: number | null;
104
+ timeoutSeconds?: number | Expression<number> | null;
104
105
  /**
105
106
  * Min number of actual instances to be running at a given time.
106
107
  * Instances will be billed for memory allocation and 10% of CPU allocation
107
108
  * while idle.
108
109
  * A value of null restores the default min instances.
109
110
  */
110
- minInstances?: number | null;
111
+ minInstances?: number | Expression<number> | null;
111
112
  /**
112
113
  * Max number of instances to be running in parallel.
113
114
  * A value of null restores the default max instances.
114
115
  */
115
- maxInstances?: number | null;
116
+ maxInstances?: number | Expression<number> | null;
116
117
  /**
117
118
  * Number of requests a function can serve at once.
118
119
  * Can only be applied to functions running on Cloud Functions v2.
@@ -120,7 +121,7 @@ export interface PubSubOptions extends options.EventHandlerOptions {
120
121
  * Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
121
122
  * The maximum value for concurrency is 1,000.
122
123
  */
123
- concurrency?: number | null;
124
+ concurrency?: number | Expression<number> | null;
124
125
  /**
125
126
  * Fractional number of CPUs to allocate to a function.
126
127
  * Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
@@ -0,0 +1,63 @@
1
+ import { timezone } from '../../common/timezone';
2
+ import { ManifestRequiredAPI } from '../../runtime/manifest';
3
+ import * as options from '../options';
4
+ import { HttpsFunction } from './https';
5
+ /**
6
+ * Interface representing a ScheduleEvent that is passed to the function handler.
7
+ */
8
+ export interface ScheduledEvent {
9
+ /**
10
+ * The Cloud Scheduler job name.
11
+ * Populated via the X-CloudScheduler-JobName header.
12
+ *
13
+ * If invoked manually, this field is undefined.
14
+ */
15
+ jobName?: string;
16
+ /**
17
+ * For Cloud Scheduler jobs specified in the unix-cron format,
18
+ * this is the job schedule time in RFC3339 UTC "Zulu" format.
19
+ * Populated via the X-CloudScheduler-ScheduleTime header.
20
+ *
21
+ * If the schedule is manually triggered, this field will be
22
+ * the function execution time.
23
+ */
24
+ scheduleTime: string;
25
+ }
26
+ /** The Cloud Function type for Schedule triggers. */
27
+ export interface ScheduleFunction extends HttpsFunction {
28
+ __requiredAPIs?: ManifestRequiredAPI[];
29
+ run(data: ScheduledEvent): void | Promise<void>;
30
+ }
31
+ /** Options that can be set on a Schedule trigger. */
32
+ export interface ScheduleOptions extends options.GlobalOptions {
33
+ /** The schedule, in Unix Crontab or AppEngine syntax. */
34
+ schedule: string;
35
+ /** The timezone that the schedule executes in. */
36
+ timeZone?: timezone;
37
+ /** The number of retry attempts for a failed run. */
38
+ retryCount?: number;
39
+ /** The time limit for retrying. */
40
+ maxRetrySeconds?: number;
41
+ /** The minimum time to wait before retying. */
42
+ minBackoffSeconds?: number;
43
+ /** The maximum time to wait before retrying. */
44
+ maxBackoffSeconds?: number;
45
+ /** The time between will double max doublings times. */
46
+ maxDoublings?: number;
47
+ }
48
+ /**
49
+ * Handler for scheduled functions. Triggered whenever the associated
50
+ * scheduler job sends a http request.
51
+ * @param schedule - The schedule, in Unix Crontab or AppEngine syntax.
52
+ * @param handler - A function to execute when triggered.
53
+ * @returns A function that you can export and deploy.
54
+ */
55
+ export declare function onSchedule(schedule: string, handler: (req: ScheduledEvent) => void | Promise<void>): ScheduleFunction;
56
+ /**
57
+ * Handler for scheduled functions. Triggered whenever the associated
58
+ * scheduler job sends a http request.
59
+ * @param options - Options to set on scheduled functions.
60
+ * @param handler - A function to execute when triggered.
61
+ * @returns A function that you can export and deploy.
62
+ */
63
+ export declare function onSchedule(options: ScheduleOptions, handler: (req: ScheduledEvent) => void | Promise<void>): ScheduleFunction;
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ // The MIT License (MIT)
3
+ //
4
+ // Copyright (c) 2022 Firebase
5
+ //
6
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ // of this software and associated documentation files (the "Software"), to deal
8
+ // in the Software without restriction, including without limitation the rights
9
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ // copies of the Software, and to permit persons to whom the Software is
11
+ // furnished to do so, subject to the following conditions:
12
+ //
13
+ // The above copyright notice and this permission notice shall be included in all
14
+ // copies or substantial portions of the Software.
15
+ //
16
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ // SOFTWARE.
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.onSchedule = exports.getOpts = void 0;
25
+ const encoding_1 = require("../../common/encoding");
26
+ const logger = require("../../logger");
27
+ const options = require("../options");
28
+ /** @internal */
29
+ function getOpts(args) {
30
+ if (typeof args === 'string') {
31
+ return {
32
+ schedule: args,
33
+ opts: {},
34
+ };
35
+ }
36
+ return {
37
+ schedule: args.schedule,
38
+ timeZone: args.timeZone,
39
+ retryCount: args.retryCount,
40
+ maxRetrySeconds: args.maxRetrySeconds,
41
+ minBackoffSeconds: args.minBackoffSeconds,
42
+ maxBackoffSeconds: args.maxBackoffSeconds,
43
+ maxDoublings: args.maxDoublings,
44
+ opts: args,
45
+ };
46
+ }
47
+ exports.getOpts = getOpts;
48
+ /**
49
+ * Handler for scheduled functions. Triggered whenever the associated
50
+ * scheduler job sends a http request.
51
+ * @param args - Either a schedule or an object containing function options.
52
+ * @param handler - A function to execute when triggered.
53
+ * @returns A function that you can export and deploy.
54
+ */
55
+ function onSchedule(args, handler) {
56
+ const separatedOpts = getOpts(args);
57
+ const func = async (req, res) => {
58
+ const event = {
59
+ jobName: req.header('X-CloudScheduler-JobName') || undefined,
60
+ scheduleTime: req.header('X-CloudScheduler-ScheduleTime') || new Date().toISOString(),
61
+ };
62
+ try {
63
+ await handler(event);
64
+ res.status(200).send();
65
+ }
66
+ catch (err) {
67
+ logger.error(err.message);
68
+ res.status(500).send();
69
+ }
70
+ };
71
+ func.run = handler;
72
+ const baseOptsEndpoint = options.optionsToEndpoint(options.getGlobalOptions());
73
+ const specificOptsEndpoint = options.optionsToEndpoint(separatedOpts.opts);
74
+ const ep = {
75
+ platform: 'gcfv2',
76
+ ...baseOptsEndpoint,
77
+ ...specificOptsEndpoint,
78
+ labels: {
79
+ ...baseOptsEndpoint === null || baseOptsEndpoint === void 0 ? void 0 : baseOptsEndpoint.labels,
80
+ ...specificOptsEndpoint === null || specificOptsEndpoint === void 0 ? void 0 : specificOptsEndpoint.labels,
81
+ },
82
+ scheduleTrigger: {
83
+ schedule: separatedOpts.schedule,
84
+ retryConfig: {},
85
+ },
86
+ };
87
+ (0, encoding_1.copyIfPresent)(ep.scheduleTrigger, separatedOpts, 'timeZone');
88
+ (0, encoding_1.copyIfPresent)(ep.scheduleTrigger.retryConfig, separatedOpts, 'retryCount', 'maxRetrySeconds', 'minBackoffSeconds', 'maxBackoffSeconds', 'maxDoublings');
89
+ func.__endpoint = ep;
90
+ func.__requiredAPIs = [
91
+ {
92
+ api: 'cloudscheduler.googleapis.com',
93
+ reason: 'Needed for scheduled functions.',
94
+ },
95
+ ];
96
+ return func;
97
+ }
98
+ exports.onSchedule = onSchedule;
@@ -1,5 +1,6 @@
1
1
  import { CloudEvent, CloudFunction } from '../core';
2
2
  import * as options from '../options';
3
+ import { Expression } from '../params';
3
4
  /**
4
5
  * An object within Google Cloud Storage.
5
6
  * Ref: https://github.com/googleapis/google-cloudevents-nodejs/blob/main/cloud/storage/v1/StorageObjectData.ts
@@ -165,7 +166,7 @@ export interface StorageOptions extends options.EventHandlerOptions {
165
166
  * Amount of memory to allocate to a function.
166
167
  * A value of null restores the defaults of 256MB.
167
168
  */
168
- memory?: options.MemoryOption | null;
169
+ memory?: options.MemoryOption | Expression<number> | null;
169
170
  /**
170
171
  * Timeout for the function in sections, possible values are 0 to 540.
171
172
  * HTTPS functions can specify a higher timeout.
@@ -176,19 +177,19 @@ export interface StorageOptions extends options.EventHandlerOptions {
176
177
  * maximum timeout of 36,00s (1 hour). Task queue functions have a maximum
177
178
  * timeout of 1,800s (30 minutes)
178
179
  */
179
- timeoutSeconds?: number | null;
180
+ timeoutSeconds?: number | Expression<number> | null;
180
181
  /**
181
182
  * Min number of actual instances to be running at a given time.
182
183
  * Instances will be billed for memory allocation and 10% of CPU allocation
183
184
  * while idle.
184
185
  * A value of null restores the default min instances.
185
186
  */
186
- minInstances?: number | null;
187
+ minInstances?: number | Expression<number> | null;
187
188
  /**
188
189
  * Max number of instances to be running in parallel.
189
190
  * A value of null restores the default max instances.
190
191
  */
191
- maxInstances?: number | null;
192
+ maxInstances?: number | Expression<number> | null;
192
193
  /**
193
194
  * Number of requests a function can serve at once.
194
195
  * Can only be applied to functions running on Cloud Functions v2.
@@ -196,7 +197,7 @@ export interface StorageOptions extends options.EventHandlerOptions {
196
197
  * Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
197
198
  * The maximum value for concurrency is 1,000.
198
199
  */
199
- concurrency?: number | null;
200
+ concurrency?: number | Expression<number> | null;
200
201
  /**
201
202
  * Fractional number of CPUs to allocate to a function.
202
203
  * Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
@@ -1,7 +1,8 @@
1
1
  import { AuthData, RateLimits, Request, RetryConfig } from '../../common/providers/tasks';
2
2
  import * as options from '../options';
3
3
  import { HttpsFunction } from './https';
4
- export { AuthData, RateLimits, Request, RetryConfig };
4
+ import { Expression } from '../params';
5
+ export { AuthData, Request };
5
6
  export interface TaskQueueOptions extends options.EventHandlerOptions {
6
7
  /** How a task should be retried in the event of a non-2xx return. */
7
8
  retryConfig?: RetryConfig;
@@ -22,7 +23,7 @@ export interface TaskQueueOptions extends options.EventHandlerOptions {
22
23
  * Amount of memory to allocate to a function.
23
24
  * A value of null restores the defaults of 256MB.
24
25
  */
25
- memory?: options.MemoryOption | null;
26
+ memory?: options.MemoryOption | Expression<number> | null;
26
27
  /**
27
28
  * Timeout for the function in sections, possible values are 0 to 540.
28
29
  * HTTPS functions can specify a higher timeout.
@@ -33,19 +34,19 @@ export interface TaskQueueOptions extends options.EventHandlerOptions {
33
34
  * maximum timeout of 36,00s (1 hour). Task queue functions have a maximum
34
35
  * timeout of 1,800s (30 minutes)
35
36
  */
36
- timeoutSeconds?: number | null;
37
+ timeoutSeconds?: number | Expression<number> | null;
37
38
  /**
38
39
  * Min number of actual instances to be running at a given time.
39
40
  * Instances will be billed for memory allocation and 10% of CPU allocation
40
41
  * while idle.
41
42
  * A value of null restores the default min instances.
42
43
  */
43
- minInstances?: number | null;
44
+ minInstances?: number | Expression<number> | null;
44
45
  /**
45
46
  * Max number of instances to be running in parallel.
46
47
  * A value of null restores the default max instances.
47
48
  */
48
- maxInstances?: number | null;
49
+ maxInstances?: number | Expression<number> | null;
49
50
  /**
50
51
  * Number of requests a function can serve at once.
51
52
  * Can only be applied to functions running on Cloud Functions v2.
@@ -53,7 +54,7 @@ export interface TaskQueueOptions extends options.EventHandlerOptions {
53
54
  * Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
54
55
  * The maximum value for concurrency is 1,000.
55
56
  */
56
- concurrency?: number | null;
57
+ concurrency?: number | Expression<number> | null;
57
58
  /**
58
59
  * Fractional number of CPUs to allocate to a function.
59
60
  * Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.