"Unexpected token stripe" when trying to deploy Firebase Functions - swift

I'm trying to incorporate Stripe into an iOS app using Firebase Functions. I'm following the Stripe documentation for "Accepting a payment" in Swift with Node backend. I first did npm install --save stripe. That finished with no errors. Then I did npm install. My index.js looks like this so far:
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
const functions = require('firebase-functions');
const stripe = require('stripe')('sk_test_...');
const paymentIntent = await stripe.paymentIntents.create({
amount: 1099,
currency: 'usd',
});
const clientSecret = paymentIntent.client_secret
When running firebase deploy I get: 11:29 error Parsing error: Unexpected token stripe. Line 11 char 29 in my file is the stripe.paymentIntents...
This is my first time using Firebase Functions or Stripe, so I'm at a loss here. I appreciate any help.
EDIT:
Here's the contents of my package.json file.
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"dependencies": {
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.1",
"stripe": "^8.55.0"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}

This error is because on the cloud environment the stripe library is not installed before you require it.
npm install does install the dependencies but in your local environment, to install them on the Cloud Functions envirornment you need to edit the package.json file from the Cloud Function.
This to add the dependencies that it will be required by the function.
This is done by adding the dependency section to the package.json file
It will lok something like:
{
"name": "sample-name",
"version": "0.0.1",
"dependencies": {
"escape-html": "^1.0.3",
"stripe": "^8.24.0"
}
}
EDIT
With this code it works on Cloud functions:
const stripe = require('stripe')('<My Secret Key>');
exports.helloWorld = (req, res) => {
let paymentIntent = null;
paymentIntent = stripe.paymentIntents.create({
amount: 2000,
currency: 'usd',
description: 'My first payment',
});
let message = req.query.message || req.body.message || 'Hello World!';
res.status(200).send(message);
};
Apparently the issue was the await because HTTP Cloud Functions work on a Synchronous way

I see this question is old but I ran into this exact issue and couldn't find an answer.
I had my backend functions folder nested within my overall app and I had let firebase generate some files for me, including a lint configuration. So, I ended up with two lint config files in my project total. The firebase generated one tried to enforce double quotes and the one I created tried to enforce single quotes. I ended up just deleting the generated lint config and it works fine now.

Related

ERR_REQUIRE_ESM require of of ES Module not supported how can I fix this? on file-type package

I've a outdated app that uses very older few packages those doesn't support ES Module as an example file-type package. So if you setup babel and node HTTP server with and then install file-type package then start building and running will throw error message like below:
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\test\testbabel\node_modules\file-
type\index.js from E:\test\testbabel\dist\index.js not supported.
Instead change the require of E:\test\testbabel\node_modules\file-type\index.js in
E:\test\testbabel\dist\index.js to a dynamic import() which is available in all CommonJS
modules.
at Object.<anonymous> (E:\test\testbabel\dist\index.js:10:17) {
code: 'ERR_REQUIRE_ESM'
}
I tried this on a fresh project though my old project has an outdated config or so, It still throwing this error
Here are my index.js codes
import http from 'http';
import { fileTypeFromFile } from 'file-type';
const server = http.createServer((req, res) => {
res.end('Hello from the server');
}).listen(4001);
console.log('Server is up and running');
export default server;
file package.json.
{
"name": "testbabel",
"version": "1.0.0",
"description": "test babel with http or express",
"main": "index.js",
"scripts": {
"build": "babel index.js -d dist",
"start": "npm run build && node dist/index.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.17.10",
"#babel/core": "^7.18.2",
"#babel/plugin-transform-modules-commonjs": "^7.18.2",
"#babel/preset-env": "^7.18.2"
},
"dependencies": {
"file-type": "^17.1.1"
}
}
I just tried to import the package and got the errors above.
attempt:
I thought a converter might help so used #babel/plugin-transform-modules-commonjs but still didn't help, and seems no effect on including that package
I'm not sure but added some tweaks on package.json like "type": "module" "type": "commonjs" didn't help at all.
what is the easiest solution for this issue and how do we fix it?
Note: I saw people were going back to the supported package instead of new one which doesn't make sense to me as a solution.
Option1(babel with mocha): Rename "index.js" to "index.mjs" and modify file-type's pacakage.json ("index.js" to "index.mjs"), then leave Babel to transpile for you.
// babel-register.js
const babel_register = require("#babel/register").default;
babel_register({
ignore: [
// Only work on Project-wide configuration
// overrides ignore can transpile packages(modules) from node_modules (https://babeljs.io/docs/en/babel-register/#ignores-node_modules-by-default)
],
});
Use babel.config instead of .babelrc
//.mocharc.js
require("./babel-register");
module.exports = {
// https://github.com/mochajs/mocha/blob/v8.4.0/example/config/.mocharc.js
ui: "bdd",
timeout: 5000,
recursive: true,
};
Option2(babel only): Using dynamic import expression
async function doSomething() {
const {fileTypeFromStream} = await import("file-type");
}
and
["#babel/preset-env", {
exclude: ["proposal-dynamic-import"]
}]
Avoiding Babel tanspile dynamic import expression

Cannot test a native Android app using codeceptJS

I have created a codeceptJS project by following the mobile testing setup steps located here: https://codecept.io/mobile/#setting-up
So far, I'm unable to test any apps via simulator; I instead get the following error:
1) login
I should be able to login with the correct username and password:
>> The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource <<
at Object.getErrorFromResponseBody (node_modules/webdriver/build/utils.js:189:12)
at NodeJSRequest._request (node_modules/webdriver/build/request/index.js:157:31)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
I have verified my appium config using appium-doctor, and there are no issues found.
My codecept.conf.js is as follows:
const path = require('path');
const { setHeadlessWhen } = require('#codeceptjs/configure');
// turn on headless mode when running with HEADLESS=true environment variable
// export HEADLESS=true && npx codeceptjs run
setHeadlessWhen(process.env.HEADLESS);
exports.config = {
tests: './*_test.js',
output: './output',
helpers: {
Appium: {
platform: 'Android',
device: 'emulator',
desiredCapabilities: {
avd: 'Pixel_5_API_28',
app: path.resolve('./sample_apps/Android.apk'),
appActivity: 'com.swaglabsmobileapp.MainActivity'
}
},
},
include: {
I: './steps_file.js'
},
bootstrap: null,
mocha: {},
name: 'appium-codecept-android-POC',
plugins: {
pauseOnFail: {},
retryFailedStep: {
enabled: true
},
tryTo: {
enabled: true
},
screenshotOnFail: {
enabled: true
}
}
}
And here's my package.json as created by codeceptjs init:
{
"name": "appium-codecept-android-POC",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"codeceptjs": "^3.0.7",
"webdriverio": "^7.9.0"
}
}
Finally, my test file is as follows:
Feature('login');
Scenario('I should be able to login with the correct username and password', ({ I }) => {
setTimeout(() => {
I.see('Username');
}, 3000);
I.click('//android.widget.EditText[#content-desc="test-Username"]');
I.fillField('//android.widget.EditText[#content-desc="test-Username"]', 'standard_user');
I.click('//android.widget.EditText[#content-desc="test-Password"]');
I.fillField('//android.widget.EditText[#content-desc="test-Password"]', 'secret_sauce');
I.click('//android.view.ViewGroup[#content-desc="test-LOGIN"]');
I.waitForElement('//android.view.ViewGroup[#content-desc="test-Cart drop zone"]/android.view.ViewGroup/android.widget.TextView', 3)
I.dontSeeElement('//android.view.ViewGroup[#content-desc="test-Error message"]/android.widget.TextView');
});
Scenario('I should not be able to login with an incorrect username or password', ({ I }) => {
setTimeout(() => {
I.see('Username');
}, 3000);
I.click('//android.widget.EditText[#content-desc="test-Username"]');
I.fillField('//android.widget.EditText[#content-desc="test-Username"]', 'bob');
I.click('//android.widget.EditText[#content-desc="test-Password"]');
I.fillField('//android.widget.EditText[#content-desc="test-Password"]', 'secret_sauce');
I.click('//android.view.ViewGroup[#content-desc="test-LOGIN"]');
I.waitForElement('//android.view.ViewGroup[#content-desc="test-Cart drop zone"]/android.view.ViewGroup/android.widget.TextView', 3)
I.dontSeeElement('//android.view.ViewGroup[#content-desc="test-Error message"]/android.widget.TextView');
});
Scenario('I should be able to see details', ({ I }) => {
// login
setTimeout(() => {
I.see('Username');
}, 3000);
I.click('//android.widget.EditText[#content-desc="test-Username"]');
I.fillField('//android.widget.EditText[#content-desc="test-Username"]', 'standard_user');
I.click('//android.widget.EditText[#content-desc="test-Password"]');
I.fillField('//android.widget.EditText[#content-desc="test-Password"]', 'secret_sauce');
I.click('//android.view.ViewGroup[#content-desc="test-LOGIN"]');
I.waitForElement('//android.view.ViewGroup[#content-desc="test-Cart drop zone"]/android.view.ViewGroup/android.widget.TextView', 3)
// should be able to click a label to see details
I.click('(//android.widget.TextView[#content-desc="test-Item title"])[2]');
I.seeElement('//android.view.ViewGroup[#content-desc="test-Description"]/android.widget.TextView[2]');
I.click('//android.view.ViewGroup[#content-desc="test-BACK TO PRODUCTS"]');
});
I'm at a loss here, as I haven't done anything except follow the setup instructions. Executing against ios works; it is only the android execution that fails. Appium is installed and running, env vars are set, etc. Any help would be appreciated, as this could be a deal breaker for me in terms of whether or not I can use codeceptjs. I love the project and really want to use it, but I must be able to test both ios and android native apps.
One final note: If anyone wants to try this config, the app I am using for the above test can be found here: https://github.com/saucelabs/sample-app-mobile/releases/download/2.7.1/Android.SauceLabs.Mobile.Sample.app.2.7.1.apk

Trying to write a vuepress plugin

(The doc on writing a plugin is pretty sparse...)
THE GOAL
Create a plugin to add headers to a page.
THE ATTEMPT
Created a plugin following guidelines and an example plugin (that presumably works...) to do something similar.
THE ISSUE
Plugin won't load.
config.js
plugins: [
[
'vuepress-plugin-headertags',
{ headerTags: ["<script src='https://cdn.jsdelivr.net/npm/netlify-identity-widget#1.5.2/build/netlify-identity-widget.min.js'></script>"]}
]
],
(the <script> tag is what I'm trying to insert, in this instance.
PLUGIN index.js
const { path } = require('path')
// was: const { path } = require('#vuepress/shared-utils')
// dunno. No documentation on this...
// got the current version from the 'default-theme' code
module.exports = (options) => ({
define () {
return {
headerTags: options.headerTags || []
}
},
enhanceAppFiles () {
return [path.resolve(__dirname, 'enhanceAppFile.js')]
},
globalUIComponents: ['HeaderTags']
})
PLUGIN INSTALLATION
I published it to npm as vuepress-plugin-headertags, and then installed it with:
yarn add -D vuepress-plugin-headertags
Here's the relevant package.json content:
{
"name": "vuepress-netlifycms",
"version": "0.0.0",
"scripts": {
"dev": "vuepress dev",
"build": "vuepress build",
"debug": "node --nolazy --inspect=9229 /home/rickb/.yarn/bin/vuepress build"
},
"devDependencies": {
"vuepress": "^0.14.8",
"vuepress-plugin-headertags": "^1.0.3"
},
"dependencies": {}
}
VUEPRESS INSTALLATION
I cloned the vuepress repo from git and did a yarn link, which makes it globally available. With that, I can trace it in the debugger via the 'debug' script.
TRACING
I've followed the VP source code in the debugger and get to resolvePathPackage() in moduleResolver.js. The incoming path is not correct:
/home/(...)/VuePress-NetlifyCMS/vuepress-plugin-headertags
It should be:
/home/(...)/VuePress-NetlifyCMS/node_modules/vuepress-plugin-headertags
At any rate, it doesn't resolve, even after the 'normalization' process.
MORE EYES
I need more eyes on this to help me figure it out. The project is already up on github as 'rickbsgu/VuePress-NetlifyCMS.git'. If you do an install, the plugin will be in the project directory under 'node_modules/vuepress-plugin-headertags'
Any thoughts appreciated
And it works, now. Two problems:
Version I was running/debugging was not the same as the version in package.json. There is the vuepress executable and the vuepress libraries the plugin requires. The library was always the older version at runtime.
I needed to change the path import in index.html from const { path } = require('path') to const { path } = require('#vuepress/shared-utils'). That's my doc issue - I don't see that documented anywhere.
Thanks #Sun Haoran for getting me to look in the right place.

Save data to firestore from google cloud function

I am new to IOT and firestore.
I am trying to save data to firestore using cloud function (MQTT).
Following is the code:
exports.helloPubSub = (event, callback) => {
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firestore);
const db = admin.firestore()
//admin.initializeApp();
console.log("Start");
var docRef = db.collection('users').doc('alovelace');
var setAda = docRef.set({
first: 'Ada',
last: 'Lovelace',
born: 1815
});
};
I am getting following errors in view logs :
"Function execution took 22 ms, finished with status: 'error'"
Any suggestion
Also after some changes I am getting error - Error: Firebase config variables are not available. Please use the latest version of the Firebase CLI to deploy this function
My package.json is
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"#google-cloud/vision": "^0.12.0",
"async": "^2.5.0",
"consolidate": "^0.14.5",
"express": "^4.15.4",
"firebase-admin": "^5.4.0",
"firebase-functions": "^0.7.0",
"firebase-tools": "3.15.4",
"handlebars": "^4.0.10",
"jquery": "^3.2.1",
"js-levenshtein": "^1.1.3",
"json-query": "^2.2.2"
},
"private": true
}
As you are getting following error message
Error: Firebase config variables are not available. Please use the
latest version of the Firebase CLI to deploy this function
You need to update firebase CLI to deploy cloud function
npm i --save firebase-functions#latest
There was a breaking change introduced in firebase-tools#3.17.x which requires your project to upgrade firebase-functions to the latest version.
However, firebase-functions#latest also requires firebase-admin#latest (at the time of writing this answer firebase-admin#5.11.0. Once all packages are upgraded, this problem should be solved.
Another alternative is to downgrade your global firebase-tools to 3.16.0, which lets you use older firebase-functions and firebase-admin packages.

electron-builder cannot find git repository although specifying

package.json
{
//some other config
"repository": "git#gitintsrv.domain.com/UserName/RepoName",
"scripts": {
"build": "build --win",
"ship": "build --win -p always"
}
}
electron-builder.yml
appId: com.xorchat.app.windows
publish:
provider: github
token: some_token
electron.js
const { app, BrowserWindow, ipcMain } = require('electron');
const { autoUpdater } = require("electron-updater");
let win; // this will store the window object
// creates the default window
function createDefaultWindow() {
win = new BrowserWindow({ width: 900, height: 680 });
win.loadURL(`file://${__dirname}/src/index.html`);
win.on('closed', () => app.quit());
return win;
}
// when the app is loaded create a BrowserWindow and check for updates
app.on('ready', function() {
createDefaultWindow()
autoUpdater.checkForUpdates();
});
// when the update has been downloaded and is ready to be installed, notify the BrowserWindow
autoUpdater.on('update-downloaded', (info) => {
win.webContents.send('updateReady')
});
// when receiving a quitAndInstall signal, quit and install the new version ;)
ipcMain.on("quitAndInstall", (event, arg) => {
autoUpdater.quitAndInstall();
})
When i am running npm run build i am receiving this error.
Error: Cannot detect repository by .git/config. Please specify "repository" in the package.json (https://docs.npmjs.com/files/package.json#repository).
Please see https://electron.build/configuration/publish
Where is the error?
I know it's probably too late, but in case you end up here as I did, here's how I solved it:
Add this to your package.json
"build": {
"publish": [{
"provider": "github",
"host": "github.<<DOMAIN>>.com",
"owner": "<<USER>>",
"repo": "<<NAME OF YOUR REPO (ONLY THE NAME)>>",
"token": "<<ACCESS TOKEN>>"
}]
}
I think the issue is that electron cannot parse corporate github urls, or something.
*********** EDIT:
Make a electron-builder.yml in the root folder, with the following content
appId: com.corporate.AppName
publish:
provider: github
token: <<ACCESS TOKEN>>
host: github.corporate.com
owner: <<User/ Org>>
repo: <<repo name>>
Don't forget to include this file on your .gitignore
This use to be a specific issue with Electron Builder 19x, and it has since been fixed:
https://github.com/electron-userland/electron-builder/issues/2785