Best JavaScript code snippet using best
function-builder.js
Source:function-builder.js
1"use strict";2// The MIT License (MIT)3//4// Copyright (c) 2017 Firebase5//6// Permission is hereby granted, free of charge, to any person obtaining a copy7// of this software and associated documentation files (the "Software"), to deal8// in the Software without restriction, including without limitation the rights9// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell10// copies of the Software, and to permit persons to whom the Software is11// furnished to do so, subject to the following conditions:12//13// The above copyright notice and this permission notice shall be included in all14// copies or substantial portions of the Software.15//16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER20// 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 THE22// SOFTWARE.23Object.defineProperty(exports, "__esModule", { value: true });24exports.FunctionBuilder = exports.runWith = exports.region = void 0;25const _ = require("lodash");26const function_configuration_1 = require("./function-configuration");27const analytics = require("./providers/analytics");28const auth = require("./providers/auth");29const database = require("./providers/database");30const firestore = require("./providers/firestore");31const https = require("./providers/https");32const pubsub = require("./providers/pubsub");33const remoteConfig = require("./providers/remoteConfig");34const storage = require("./providers/storage");35const tasks = require("./providers/tasks");36const testLab = require("./providers/testLab");37/**38 * Assert that the runtime options passed in are valid.39 * @param runtimeOptions object containing memory and timeout information.40 * @throws { Error } Memory and TimeoutSeconds values must be valid.41 */42function assertRuntimeOptionsValid(runtimeOptions) {43 if (runtimeOptions.memory &&44 !_.includes(function_configuration_1.VALID_MEMORY_OPTIONS, runtimeOptions.memory)) {45 throw new Error(`The only valid memory allocation values are: ${function_configuration_1.VALID_MEMORY_OPTIONS.join(', ')}`);46 }47 if (runtimeOptions.timeoutSeconds > function_configuration_1.MAX_TIMEOUT_SECONDS ||48 runtimeOptions.timeoutSeconds < 0) {49 throw new Error(`TimeoutSeconds must be between 0 and ${function_configuration_1.MAX_TIMEOUT_SECONDS}`);50 }51 if (runtimeOptions.ingressSettings &&52 !_.includes(function_configuration_1.INGRESS_SETTINGS_OPTIONS, runtimeOptions.ingressSettings)) {53 throw new Error(`The only valid ingressSettings values are: ${function_configuration_1.INGRESS_SETTINGS_OPTIONS.join(',')}`);54 }55 if (runtimeOptions.vpcConnectorEgressSettings &&56 !_.includes(function_configuration_1.VPC_EGRESS_SETTINGS_OPTIONS, runtimeOptions.vpcConnectorEgressSettings)) {57 throw new Error(`The only valid vpcConnectorEgressSettings values are: ${function_configuration_1.VPC_EGRESS_SETTINGS_OPTIONS.join(',')}`);58 }59 if (runtimeOptions.failurePolicy !== undefined) {60 if (_.isBoolean(runtimeOptions.failurePolicy) === false &&61 _.isObjectLike(runtimeOptions.failurePolicy) === false) {62 throw new Error(`failurePolicy must be a boolean or an object.`);63 }64 if (typeof runtimeOptions.failurePolicy === 'object') {65 if (_.isObjectLike(runtimeOptions.failurePolicy.retry) === false ||66 _.isEmpty(runtimeOptions.failurePolicy.retry) === false) {67 throw new Error('failurePolicy.retry must be an empty object.');68 }69 }70 }71 if (runtimeOptions.serviceAccount &&72 runtimeOptions.serviceAccount !== 'default' &&73 !_.includes(runtimeOptions.serviceAccount, '@')) {74 throw new Error(`serviceAccount must be set to 'default', a service account email, or '{serviceAccountName}@'`);75 }76 if (runtimeOptions.labels) {77 // Labels must follow the rules listed in78 // https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements79 if (Object.keys(runtimeOptions.labels).length > function_configuration_1.MAX_NUMBER_USER_LABELS) {80 throw new Error(`A function must not have more than ${function_configuration_1.MAX_NUMBER_USER_LABELS} user-defined labels.`);81 }82 // We reserve the 'deployment' and 'firebase' namespaces for future feature development.83 const reservedKeys = Object.keys(runtimeOptions.labels).filter((key) => key.startsWith('deployment') || key.startsWith('firebase'));84 if (reservedKeys.length) {85 throw new Error(`Invalid labels: ${reservedKeys.join(', ')}. Labels may not start with reserved names 'deployment' or 'firebase'`);86 }87 const invalidLengthKeys = Object.keys(runtimeOptions.labels).filter((key) => key.length < 1 || key.length > 63);88 if (invalidLengthKeys.length > 0) {89 throw new Error(`Invalid labels: ${invalidLengthKeys.join(', ')}. Label keys must be between 1 and 63 characters in length.`);90 }91 const invalidLengthValues = Object.values(runtimeOptions.labels).filter((value) => value.length > 63);92 if (invalidLengthValues.length > 0) {93 throw new Error(`Invalid labels: ${invalidLengthValues.join(', ')}. Label values must be less than 64 charcters.`);94 }95 // Keys can contain lowercase letters, foreign characters, numbers, _ or -. They must start with a letter.96 const validKeyPattern = /^[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}$/u;97 const invalidKeys = Object.keys(runtimeOptions.labels).filter((key) => !validKeyPattern.test(key));98 if (invalidKeys.length > 0) {99 throw new Error(`Invalid labels: ${invalidKeys.join(', ')}. Label keys can only contain lowercase letters, international characters, numbers, _ or -, and must start with a letter.`);100 }101 // Values can contain lowercase letters, foreign characters, numbers, _ or -.102 const validValuePattern = /^[\p{Ll}\p{Lo}\p{N}_-]{0,63}$/u;103 const invalidValues = Object.values(runtimeOptions.labels).filter((value) => !validValuePattern.test(value));104 if (invalidValues.length > 0) {105 throw new Error(`Invalid labels: ${invalidValues.join(', ')}. Label values can only contain lowercase letters, international characters, numbers, _ or -.`);106 }107 }108 if (typeof runtimeOptions.invoker === 'string' &&109 runtimeOptions.invoker.length === 0) {110 throw new Error('Invalid service account for function invoker, must be a non-empty string');111 }112 if (runtimeOptions.invoker !== undefined &&113 Array.isArray(runtimeOptions.invoker)) {114 if (runtimeOptions.invoker.length === 0) {115 throw new Error('Invalid invoker array, must contain at least 1 service account entry');116 }117 for (const serviceAccount of runtimeOptions.invoker) {118 if (serviceAccount.length === 0) {119 throw new Error('Invalid invoker array, a service account must be a non-empty string');120 }121 if (serviceAccount === 'public') {122 throw new Error("Invalid invoker array, a service account cannot be set to the 'public' identifier");123 }124 if (serviceAccount === 'private') {125 throw new Error("Invalid invoker array, a service account cannot be set to the 'private' identifier");126 }127 }128 }129 if (runtimeOptions.secrets !== undefined) {130 const invalidSecrets = runtimeOptions.secrets.filter((s) => !/^[A-Za-z\d\-_]+$/.test(s));131 if (invalidSecrets.length > 0) {132 throw new Error(`Invalid secrets: ${invalidSecrets.join(',')}. ` +133 'Secret must be configured using the resource id (e.g. API_KEY)');134 }135 }136 return true;137}138/**139 * Assert regions specified are valid.140 * @param regions list of regions.141 * @throws { Error } Regions must be in list of supported regions.142 */143function assertRegionsAreValid(regions) {144 if (!regions.length) {145 throw new Error('You must specify at least one region');146 }147 return true;148}149/**150 * Configure the regions that the function is deployed to.151 * @param regions One of more region strings.152 * @example153 * functions.region('us-east1')154 * @example155 * functions.region('us-east1', 'us-central1')156 */157function region(...regions) {158 if (assertRegionsAreValid(regions)) {159 return new FunctionBuilder({ regions });160 }161}162exports.region = region;163/**164 * Configure runtime options for the function.165 * @param runtimeOptions Object with optional fields:166 * 1. `memory`: amount of memory to allocate to the function, possible values167 * are: '128MB', '256MB', '512MB', '1GB', '2GB', and '4GB'.168 * 2. `timeoutSeconds`: timeout for the function in seconds, possible values are169 * 0 to 540.170 * 3. `failurePolicy`: failure policy of the function, with boolean `true` being171 * equivalent to providing an empty retry object.172 * 4. `vpcConnector`: id of a VPC connector in same project and region.173 * 5. `vpcConnectorEgressSettings`: when a vpcConnector is set, control which174 * egress traffic is sent through the vpcConnector.175 * 6. `serviceAccount`: Specific service account for the function.176 * 7. `ingressSettings`: ingress settings for the function, which control where a HTTPS177 * function can be called from.178 *179 * Value must not be null.180 */181function runWith(runtimeOptions) {182 if (assertRuntimeOptionsValid(runtimeOptions)) {183 return new FunctionBuilder(runtimeOptions);184 }185}186exports.runWith = runWith;187class FunctionBuilder {188 constructor(options) {189 this.options = options;190 }191 /**192 * Configure the regions that the function is deployed to.193 * @param regions One or more region strings.194 * @example195 * functions.region('us-east1')196 * @example197 * functions.region('us-east1', 'us-central1')198 */199 region(...regions) {200 if (assertRegionsAreValid(regions)) {201 this.options.regions = regions;202 return this;203 }204 }205 /**206 * Configure runtime options for the function.207 * @param runtimeOptions Object with optional fields:208 * 1. `memory`: amount of memory to allocate to the function, possible values209 * are: '128MB', '256MB', '512MB', '1GB', '2GB', and '4GB'.210 * 2. `timeoutSeconds`: timeout for the function in seconds, possible values are211 * 0 to 540.212 * 3. `failurePolicy`: failure policy of the function, with boolean `true` being213 * equivalent to providing an empty retry object.214 * 4. `vpcConnector`: id of a VPC connector in the same project and region215 * 5. `vpcConnectorEgressSettings`: when a `vpcConnector` is set, control which216 * egress traffic is sent through the `vpcConnector`.217 *218 * Value must not be null.219 */220 runWith(runtimeOptions) {221 if (assertRuntimeOptionsValid(runtimeOptions)) {222 this.options = _.assign(this.options, runtimeOptions);223 return this;224 }225 }226 get https() {227 if (this.options.failurePolicy !== undefined) {228 console.warn('RuntimeOptions.failurePolicy is not supported in https functions.');229 }230 return {231 /**232 * Handle HTTP requests.233 * @param handler A function that takes a request and response object,234 * same signature as an Express app.235 */236 onRequest: (handler) => https._onRequestWithOptions(handler, this.options),237 /**238 * Declares a callable method for clients to call using a Firebase SDK.239 * @param handler A method that takes a data and context and returns a value.240 */241 onCall: (handler) => https._onCallWithOptions(handler, this.options),242 };243 }244 get tasks() {245 return {246 /**247 * Declares a task queue function for clients to call using a Firebase Admin SDK.248 * @param options Configurations for the task queue function.249 */250 /** @hidden */251 taskQueue: (options) => {252 return new tasks.TaskQueueBuilder(options, this.options);253 },254 };255 }256 get database() {257 return {258 /**259 * Selects a database instance that will trigger the function. If omitted,260 * will pick the default database for your project.261 * @param instance The Realtime Database instance to use.262 */263 instance: (instance) => database._instanceWithOptions(instance, this.options),264 /**265 * Select Firebase Realtime Database Reference to listen to.266 *267 * This method behaves very similarly to the method of the same name in268 * the client and Admin Firebase SDKs. Any change to the Database that269 * affects the data at or below the provided `path` will fire an event in270 * Cloud Functions.271 *272 * There are three important differences between listening to a Realtime273 * Database event in Cloud Functions and using the Realtime Database in274 * the client and Admin SDKs:275 * 1. Cloud Functions allows wildcards in the `path` name. Any `path`276 * component in curly brackets (`{}`) is a wildcard that matches all277 * strings. The value that matched a certain invocation of a Cloud278 * Function is returned as part of the `context.params` object. For279 * example, `ref("messages/{messageId}")` matches changes at280 * `/messages/message1` or `/messages/message2`, resulting in281 * `context.params.messageId` being set to `"message1"` or282 * `"message2"`, respectively.283 * 2. Cloud Functions do not fire an event for data that already existed284 * before the Cloud Function was deployed.285 * 3. Cloud Function events have access to more information, including286 * information about the user who triggered the Cloud Function.287 * @param ref Path of the database to listen to.288 */289 ref: (path) => database._refWithOptions(path, this.options),290 };291 }292 get firestore() {293 return {294 /**295 * Select the Firestore document to listen to for events.296 * @param path Full database path to listen to. This includes the name of297 * the collection that the document is a part of. For example, if the298 * collection is named "users" and the document is named "Ada", then the299 * path is "/users/Ada".300 */301 document: (path) => firestore._documentWithOptions(path, this.options),302 /** @hidden */303 namespace: (namespace) => firestore._namespaceWithOptions(namespace, this.options),304 /** @hidden */305 database: (database) => firestore._databaseWithOptions(database, this.options),306 };307 }308 get analytics() {309 return {310 /**311 * Select analytics events to listen to for events.312 * @param analyticsEventType Name of the analytics event type.313 */314 event: (analyticsEventType) => analytics._eventWithOptions(analyticsEventType, this.options),315 };316 }317 get remoteConfig() {318 return {319 /**320 * Handle all updates (including rollbacks) that affect a Remote Config321 * project.322 * @param handler A function that takes the updated Remote Config template323 * version metadata as an argument.324 */325 onUpdate: (handler) => remoteConfig._onUpdateWithOptions(handler, this.options),326 };327 }328 get storage() {329 return {330 /**331 * The optional bucket function allows you to choose which buckets' events332 * to handle. This step can be bypassed by calling object() directly,333 * which will use the default Cloud Storage for Firebase bucket.334 * @param bucket Name of the Google Cloud Storage bucket to listen to.335 */336 bucket: (bucket) => storage._bucketWithOptions(this.options, bucket),337 /**338 * Handle events related to Cloud Storage objects.339 */340 object: () => storage._objectWithOptions(this.options),341 };342 }343 get pubsub() {344 return {345 /**346 * Select Cloud Pub/Sub topic to listen to.347 * @param topic Name of Pub/Sub topic, must belong to the same project as348 * the function.349 */350 topic: (topic) => pubsub._topicWithOptions(topic, this.options),351 schedule: (schedule) => pubsub._scheduleWithOptions(schedule, this.options),352 };353 }354 get auth() {355 return {356 /**357 * Handle events related to Firebase authentication users.358 */359 user: () => auth._userWithOptions(this.options),360 };361 }362 get testLab() {363 return {364 /**365 * Handle events related to Test Lab test matrices.366 */367 testMatrix: () => testLab._testMatrixWithOpts(this.options),368 };369 }370}...
ActionFactory.ts
Source:ActionFactory.ts
1import {CommentAction, CommentActionJson} from "./CommentAction";2import LockAction, {LockActionJson} from "./LockAction";3import {RemoveAction, RemoveActionJson} from "./RemoveAction";4import {ReportAction, ReportActionJson} from "./ReportAction";5import {FlairAction, FlairActionJson} from "./SubmissionAction/FlairAction";6import Action, {ActionJson, ActionRuntimeOptions, StructuredActionJson} from "./index";7import {Logger} from "winston";8import {UserNoteAction, UserNoteActionJson} from "./UserNoteAction";9import ApproveAction, {ApproveActionConfig} from "./ApproveAction";10import BanAction, {BanActionJson} from "./BanAction";11import {MessageAction, MessageActionJson} from "./MessageAction";12import {SubredditResources} from "../Subreddit/SubredditResources";13import {UserFlairAction, UserFlairActionJson} from './UserFlairAction';14import {ExtendedSnoowrap} from '../Utils/SnoowrapClients';15import EventEmitter from "events";16import {DispatchAction, DispatchActionJson} from "./DispatchAction";17import {CancelDispatchAction, CancelDispatchActionJson} from "./CancelDispatchAction";18import ContributorAction, {ContributorActionJson} from "./ContributorAction";19import {StructuredFilter} from "../Common/Infrastructure/Filters/FilterShapes";20import {ModNoteAction, ModNoteActionJson} from "./ModNoteAction";21import {SubmissionAction, SubmissionActionJson} from "./SubmissionAction";22export function actionFactory23(config: StructuredActionJson, runtimeOptions: ActionRuntimeOptions): Action {24 switch (config.kind) {25 case 'comment':26 return new CommentAction({...config as StructuredFilter<CommentActionJson>, ...runtimeOptions});27 case 'submission':28 return new SubmissionAction({...config as StructuredFilter<SubmissionActionJson>, ...runtimeOptions});29 case 'lock':30 return new LockAction({...config as StructuredFilter<LockActionJson>, ...runtimeOptions});31 case 'remove':32 return new RemoveAction({...config as StructuredFilter<RemoveActionJson>, ...runtimeOptions});33 case 'report':34 return new ReportAction({...config as StructuredFilter<ReportActionJson>, ...runtimeOptions});35 case 'flair':36 return new FlairAction({...config as StructuredFilter<FlairActionJson>, ...runtimeOptions});37 case 'userflair':38 return new UserFlairAction({...config as StructuredFilter<UserFlairActionJson>, ...runtimeOptions});39 case 'approve':40 return new ApproveAction({...config as StructuredFilter<ApproveActionConfig>, ...runtimeOptions});41 case 'usernote':42 return new UserNoteAction({...config as StructuredFilter<UserNoteActionJson>, ...runtimeOptions});43 case 'ban':44 return new BanAction({...config as StructuredFilter<BanActionJson>, ...runtimeOptions});45 case 'message':46 return new MessageAction({...config as StructuredFilter<MessageActionJson>, ...runtimeOptions});47 case 'dispatch':48 return new DispatchAction({...config as StructuredFilter<DispatchActionJson>, ...runtimeOptions});49 case 'cancelDispatch':50 return new CancelDispatchAction({...config as StructuredFilter<CancelDispatchActionJson>, ...runtimeOptions})51 case 'contributor':52 return new ContributorAction({...config as StructuredFilter<ContributorActionJson>, ...runtimeOptions})53 case 'modnote':54 return new ModNoteAction({...config as StructuredFilter<ModNoteActionJson>, ...runtimeOptions})55 default:56 throw new Error('rule "kind" was not recognized.');57 }...
settings.controller.ts
Source:settings.controller.ts
1import { MatrixOptions, RuntimeOptions } from "rpi-led-matrix";2import { matrixOptions, runtimeOptions } from "../common/matrix.config";3import { MatrixController } from "./matrix.controller";4export class SettingsController {5 private matrix: MatrixController;6 private matrixOptions: MatrixOptions;7 private runtimeOptions: RuntimeOptions;8 constructor() {9 this.matrix = MatrixController.getInstance();10 this.matrixOptions = matrixOptions;11 this.runtimeOptions = runtimeOptions;12 }13 getMatrixOptions() {14 return this.matrixOptions;15 }16 setMatrixSettings(opts: MatrixOptions) {17 this.matrixOptions = opts;18 this.matrix.updateMatrixSettings(this.matrixOptions, this.runtimeOptions);19 }20 21 getRuntimeOptions() {22 return this.runtimeOptions;23 }24 setRuntimeOptions(opts: RuntimeOptions) {25 this.runtimeOptions = opts;26 this.matrix.updateMatrixSettings(this.matrixOptions, this.runtimeOptions);27 }28 getApplicationSettings() {29 }30 setApplicationSettings() {31 }...
Using AI Code Generation
1var BestBuy = require('./bestbuy.js');2var bb = new BestBuy();3var searchTerm = process.argv[2];4bb.runtimeOptions(searchTerm, function(err, data) {5 if(err) {6 console.log(err);7 }8 else {9 console.log(data);10 }11});
Using AI Code Generation
1var BestPractice = require('./BestPractice');2var bestPractice = new BestPractice();3bestPractice.runtimeOptions({4});5bestPractice.test4();6function BestPractice(){7 this.options = {8 };9}10BestPractice.prototype.runtimeOptions = function(options){11 for(var key in options){12 this.options[key] = options[key];13 }14};15BestPractice.prototype.test4 = function(){16 console.log("Runtime: " + this.options.runtime + ", Test: " + this.options.test);17};18Your name to display (optional):19Your name to display (
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!