Merge branch 'v2' into rc
* v2: (237 commits) review & update all fields Create README.md update row heights add darker dark theme migrate from @material-ui/pickers to @mui/lab functional connect table TextEditor: rewrite styles to sx prop multiselect: fix spacing & use custom radio & checkbox icons update FirebaseUi icon sizes add confirmation to delete column hide “Hide for everyone” in column menu add Alpha tag to Connect Table, Connect Service Test page: fix horizontal scroll UserItem: fix crash if user is undefined round progress components Navigation: fix horizontal scroll NavDrawer: persist pin after window narrowing allow NavDrawer to be pinned on 1200+ wide screens fix TextEditor positioning ProjectContext: add empty table array if table field missing in settings doc ...
2
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for Firetable
|
||||
about: Suggest an idea for Rowy
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
51
.github/workflows/tweet_release.yml
vendored
@@ -6,28 +6,32 @@ name: tweet_releases
|
||||
on:
|
||||
# Triggers the workflow on push or pull request events but only for the master branch
|
||||
push:
|
||||
branches: [ master ]
|
||||
branches: [master]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
branches: [master]
|
||||
release:
|
||||
types:
|
||||
types:
|
||||
- published
|
||||
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
build:
|
||||
name: Tweet
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Post Twitter Status
|
||||
uses: julb/action-post-twitter-status@v1
|
||||
env:
|
||||
twitter_app_consumer_api_key: ${{ secrets.TWITTER_API_KEY }}
|
||||
twitter_app_consumer_api_secret_key: ${{ secrets.TWITTER_API_SECRET_KEY }}
|
||||
twitter_app_access_token: ${{ secrets.TWITTER_ACCESS_TOKEN }}
|
||||
twitter_app_access_token_secret: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }}
|
||||
with:
|
||||
message: "Testing github action for tweeting new releases and updates to Firetable project"
|
||||
build:
|
||||
name: Tweet
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Post Twitter Status
|
||||
uses: julb/action-post-twitter-status@v1
|
||||
env:
|
||||
twitter_app_consumer_api_key: ${{ secrets.TWITTER_API_KEY }}
|
||||
twitter_app_consumer_api_secret_key:
|
||||
${{ secrets.TWITTER_API_SECRET_KEY }}
|
||||
twitter_app_access_token: ${{ secrets.TWITTER_ACCESS_TOKEN }}
|
||||
twitter_app_access_token_secret:
|
||||
${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }}
|
||||
with:
|
||||
message:
|
||||
"Testing github action for tweeting new releases and updates to
|
||||
Rowy project"
|
||||
|
||||
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
|
||||
jobs:
|
||||
@@ -39,10 +43,13 @@ jobs:
|
||||
- name: Post Twitter Status
|
||||
uses: julb/action-post-twitter-status@v1
|
||||
env:
|
||||
twitter_app_consumer_api_key: ${{ secrets.TWITTER_API_KEY }}
|
||||
twitter_app_consumer_api_secret_key: ${{ secrets.TWITTER_API_SECRET_KEY }}
|
||||
twitter_app_access_token: ${{ secrets.TWITTER_ACCESS_TOKEN }}
|
||||
twitter_app_access_token_secret: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }}
|
||||
twitter_app_consumer_api_key: ${{ secrets.TWITTER_API_KEY }}
|
||||
twitter_app_consumer_api_secret_key:
|
||||
${{ secrets.TWITTER_API_SECRET_KEY }}
|
||||
twitter_app_access_token: ${{ secrets.TWITTER_ACCESS_TOKEN }}
|
||||
twitter_app_access_token_secret:
|
||||
${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }}
|
||||
with:
|
||||
message: "Testing github action for tweeting new releases and updates to Firetable project"
|
||||
|
||||
message:
|
||||
"Testing github action for tweeting new releases and updates to
|
||||
Rowy project"
|
||||
|
||||
34
.gitignore
vendored
@@ -2,26 +2,17 @@
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
www/node_modules
|
||||
|
||||
|
||||
Firetable/node_modules
|
||||
cloud_functions/functions/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
www/build
|
||||
/build
|
||||
cloud_functions/functions/lib
|
||||
|
||||
|
||||
# cloud function config
|
||||
cloud_functions/functions/src/functionConfig.ts
|
||||
|
||||
cloud_functions/functions/firebase-credentials.json
|
||||
# firebase
|
||||
*.firebaserc
|
||||
*-firebase.json
|
||||
.firebase/
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
@@ -34,16 +25,7 @@ yarn-debug.log*
|
||||
yarn-error.log*
|
||||
firebase-debug.log*
|
||||
|
||||
*.firebaserc
|
||||
.eslintcache
|
||||
.npm
|
||||
|
||||
|
||||
# Accidental package installs to root directories
|
||||
/yarn.lock
|
||||
/package.json
|
||||
package-lock.json
|
||||
node_modules/
|
||||
|
||||
cloud_functions/functions/src/functionConfig.json
|
||||
*.iml
|
||||
.idea
|
||||
*-firebase.json
|
||||
.vercel
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "Firetable",
|
||||
"name": "Rowy",
|
||||
"platforms": ["Node", "Admin", "Web"],
|
||||
"content": "README.md",
|
||||
"related": ["firebase/firebase-js-sdk"],
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
{
|
||||
"trailingComma": "es5",
|
||||
"proseWrap": "always"
|
||||
}
|
||||
|
||||
2
LICENSE
@@ -186,7 +186,7 @@
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2019 Antler Innovation Pte Ltd
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
177
README.md
@@ -1,163 +1,36 @@
|
||||
<h1 align="center">
|
||||
Firetable
|
||||
Rowy
|
||||
</h1>
|
||||
|
||||
<h3 align="center">
|
||||
Firetable is an open-source platform to unlock the full potential of Google Firestore
|
||||
|
||||
Rowy is an open source platform that allows you to build on Google Cloud
|
||||
Platform in minutes.
|
||||
|
||||
</h3>
|
||||
|
||||
<p align="center">
|
||||
With Firetable, non-technical team members can access Firestore data with a permission controlled intuitive UI while developers can build fast on the GCP stack (manage their data models, create and deploy cloud functions, connect to third party apps via webhooks and APIs...and more!) 🚀
|
||||
With Rowy you can
|
||||
✅ Manage Firestore data in a spreadsheet-like UI
|
||||
✅ Write Cloud Functions effortlessly in the browser
|
||||
✅ Connect to your favorite third party platforms
|
||||
and do more with a fully flexible open source platform
|
||||
|
||||
<img src="https://firebasestorage.googleapis.com/v0/b/rowyio.appspot.com/o/publicDemo%2FRowy%20Website%20Video.gif?alt=media&token=184ed868-e9dd-4082-b881-436845076d8b" />
|
||||
|
||||
### Quick Try
|
||||
|
||||
<p>Set up Rowy on your Google Cloud Platform project with this one-click deploy button.
|
||||
<a href="https://deploy.cloud.run/?git_repo=https://github.com/rowyio/rowyRun.git" target="_blank">
|
||||
<img src="https://storage.googleapis.com/cloudrun/button.png" alt="One Click Deploy"
|
||||
title="One Click Deploy" width="250" /></a>
|
||||
</p>
|
||||
|
||||
<!-- [](https://firetable.io) -->
|
||||
Full installation guide is available [here](./install).
|
||||
|
||||
<h3 align="center"> ✨ <a href="https://github.com/FiretableProject/firetable/wiki/Getting-Started">Getting Started Guide</a>✨</h3>
|
||||
### Reach us
|
||||
|
||||
<p align="center">
|
||||
<a aria-label="License" href="https://github.com/FiretableProject/firetable/blob/master/LICENSE">
|
||||
<img src="https://badgen.net/github/license/FiretableProject/firetable" />
|
||||
</a>
|
||||
<a aria-label="Commits" href="https://github.com/FiretableProject/firetable/commits/develop">
|
||||
<img src="https://badgen.net/github/last-commit/FiretableProject/firetable/develop" />
|
||||
</a>
|
||||
<a aria-label="Firetable CLI" href="https://npmjs.com/package/firetable">
|
||||
<img src="https://badgen.net/npm/v/firetable" />
|
||||
</a>
|
||||
</p>
|
||||
We would love to connect and hear what you think!
|
||||
|
||||
<h3 align="center">
|
||||
<a href="https://discord.gg/B8yAD5PDX4">Discord</a>
|
||||
<span> · </span>
|
||||
<a href="https://twitter.com/firetableio">Twitter</a>
|
||||
</h3>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://try.firetable.io" >
|
||||
<img align="center" alt="Firetable demo GIF" src="https://firetable.io/demo.gif" width="100%">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<h3 align="center">
|
||||
<a href="https://try.firetable.io">Live Demo</a>
|
||||
<span> · </span>
|
||||
<a href="https://github.com/FiretableProject/firetable/wiki/Getting-Started">Get started</a>
|
||||
<span> · </span>
|
||||
<a href="https://github.com/FiretableProject/firetable/issues/new?assignees=&labels=&template=feature_request.md&title=">Feature request</a>
|
||||
<span> · </span>
|
||||
<a href="https://github.com/FiretableProject/firetable/issues/new?assignees=&labels=&template=bug_report.md&title=">Report a bug</a>
|
||||
<span> · </span>
|
||||
<a href="https://discord.gg/B8yAD5PDX4">Discussions</a>
|
||||
</a>
|
||||
</h3>
|
||||
<br/>
|
||||
|
||||
# Stay Up-to-Date
|
||||
Watch the releases of this repository to be notified for future updates
|
||||
|
||||
<img src="https://user-images.githubusercontent.com/307298/128521637-4735b890-18bd-4ee5-940e-0013e25393a1.gif" alt="drawing" width="450"/>
|
||||
|
||||
|
||||
# Features
|
||||
|
||||
- **Intuitive spreadsheet like interface for Firestore.** With Firetable UI you
|
||||
can view and directly edit the data in Firestore but not just that, you can
|
||||
completely manage your existing data model or create from scratch.
|
||||
|
||||
- CRUD operations on your data - Add, edit, and delete rows
|
||||
- Create table collections, add column fields
|
||||
- Sort and filter data
|
||||
- Resize and rename columns
|
||||
|
||||
- **Rich set of data fields.**
|
||||
[29+ field types](https://github.com/FiretableProject/firetable/wiki/Field-Types)
|
||||
supported and growing
|
||||
|
||||
- Basic types: Short Text, Long Text, Email, Phone, URL…
|
||||
- Custom UI pickers: Date, Checkbox, Single Select, Multi Select…
|
||||
- Uploaders: Image, File
|
||||
- Rich Editors: JSON, Code, Rich Text (HTML)
|
||||
|
||||
- **Default values and Required fields.** You can assign default values to any Firestore fields on row creation (null, static or undefined). You can also define which fields are required for a row creation.
|
||||
|
||||
- **Permission controlled views.** You can customize who sees what data and what
|
||||
action they can take with powerful set of access controls based on custom user
|
||||
roles.
|
||||
[Read more](https://github.com/FiretableProject/firetable/wiki/Role-Based-Security-Rules)
|
||||
|
||||
- **Bulk data actions.** You can import and export your Firestore data from/to CSV files.
|
||||
|
||||
- **Supercharge your database with your own scripts.**
|
||||
|
||||
- Action field: trigger any Cloud Function
|
||||
- Derivative field: populate cell with value derived from the rest of the
|
||||
row’s values
|
||||
- Aggregate field: populate cell with value aggregated from the row’s
|
||||
sub-table
|
||||
|
||||
- **Integrations with external services.**
|
||||
- Connect Table uses Algolia to get a snapshot of another table’s row values
|
||||
- Connect Service uses any HTTP endpoint to get a cell value
|
||||
|
||||
## Firetable makes it easy to use key Firebase products
|
||||
|
||||
<p align="center">
|
||||
<a href="https://firebase.google.com/products/firestore">
|
||||
<img src="https://github.com/FiretableProject/firetable/wiki/images/firebase/firestore.png" alt="Cloud Firestore" width="19%" />
|
||||
</a>
|
||||
<a href="https://firebase.google.com/products/auth">
|
||||
<img src="https://github.com/FiretableProject/firetable/wiki/images/firebase/authentication.png" alt="Firebase Authentication" width="19%" />
|
||||
</a>
|
||||
<a href="https://firebase.google.com/products/functions">
|
||||
<img src="https://github.com/FiretableProject/firetable/wiki/images/firebase/functions.png" alt="Firebase Functions" width="19%" />
|
||||
</a>
|
||||
<a href="https://firebase.google.com/products/hosting">
|
||||
<img src="https://github.com/FiretableProject/firetable/wiki/images/firebase/hosting.png" alt="Firebase Hosting" width="19%" />
|
||||
</a>
|
||||
<a href="https://firebase.google.com/products/storage">
|
||||
<img src="https://github.com/FiretableProject/firetable/wiki/images/firebase/storage.png" alt="Firebase Storage" width="19%" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
# Getting started
|
||||
|
||||
To set up Firetable, you must be comfortable with working with the command line and have basic how to use npm.
|
||||
### [**Read the getting started guide →**](https://github.com/FiretableProject/firetable/wiki/Getting-Started)
|
||||
|
||||
# Documentation
|
||||
|
||||
We’re still working on improving our documentation and writing more
|
||||
beginner-friendly guides.
|
||||
|
||||
[**Documentation on GitHub Wiki →**](https://github.com/FiretableProject/firetable/wiki)
|
||||
|
||||
# Issues
|
||||
|
||||
[](https://github.com/antlervc/firetable/issues)
|
||||
|
||||
[Create issues and bug reports here.](https://github.com/antlervc/firetable/issues)
|
||||
Make sure to provide console log outputs and screenshots!
|
||||
|
||||
# Roadmap and feature requests
|
||||
|
||||
- [Roadmap](https://github.com/FiretableProject/firetable/wiki/Roadmap)
|
||||
- [View our ideas and feature requests](https://github.com/FiretableProject/firetable/projects/1)
|
||||
|
||||
---
|
||||
|
||||
<!-- # Join Our Community
|
||||
|
||||
<a href="https://discord.gg/B8yAD5PDX4">
|
||||
<img
|
||||
src="https://invidget.switchblade.xyz/B8yAD5PDX4"
|
||||
alt="Join Firetable Open Source Project"
|
||||
>
|
||||
</a>
|
||||
<br> -->
|
||||
|
||||
# Contributing 🙌
|
||||
|
||||
We welcome any contributions from the open source community.
|
||||
|
||||
- **[Good First Issues](https://github.com/FiretableProject/firetable/projects/3)** project is a good place to start for contributing to Firetable.
|
||||
- For new feature or enhancement, please create an issue first or send us a message on **[Discord](https://discord.gg/B8yAD5PDX4)** so that we can discuss and guide you as needed ahead of you starting the work.
|
||||
- [Discord](https://discord.gg/B8yAD5PDX4)
|
||||
- [Twitter](https://twitter.com/rowyio)
|
||||
- [Email](mailto:rowy.io)
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"functions": {
|
||||
"predeploy": [
|
||||
"npm --prefix \"$RESOURCE_DIR\" run lint",
|
||||
"npm --prefix \"$RESOURCE_DIR\" run build"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
lib/
|
||||
147392
cloud_functions/functions/.yarn/releases/yarn-1.22.5.cjs
vendored
@@ -1,56 +0,0 @@
|
||||
{
|
||||
"name": "functions",
|
||||
"scripts": {
|
||||
"updateStatus": "ts-node updateDeployStatus.ts",
|
||||
"generateConfig": "ts-node src/generateConfig.ts",
|
||||
"lint": "tslint --project tsconfig.json",
|
||||
"build": "tsc",
|
||||
"serve": "npm run build && firebase serve --only functions",
|
||||
"shell": "npm run build && firebase functions:shell",
|
||||
"start": "npm run shell",
|
||||
"deployFT": "echo 'n\n' | firebase deploy --interactive",
|
||||
"logs": "firebase functions:log"
|
||||
},
|
||||
"engines": {
|
||||
"node": "14"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"dependencies": {
|
||||
"@google-cloud/cloudbuild": "^2.0.6",
|
||||
"@google-cloud/firestore": "^4.9.7",
|
||||
"@google-cloud/pubsub": "^2.5.0",
|
||||
"@google-cloud/storage": "^5.1.2",
|
||||
"@sendgrid/mail": "^7.4.2",
|
||||
"@slack/web-api": "^6.0.0",
|
||||
"algoliasearch": "^4.8.6",
|
||||
"firebase-admin": "^9.4.2",
|
||||
"firebase-functions": "^3.13.1",
|
||||
"imagemin": "^7.0.1",
|
||||
"imagemin-mozjpeg": "^9.0.0",
|
||||
"imagemin-pngquant": "^9.0.2",
|
||||
"lodash": "^4.17.21",
|
||||
"sharp": "^0.25.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/algoliasearch": "^3.34.10",
|
||||
"@types/imagemin": "^7.0.0",
|
||||
"@types/imagemin-mozjpeg": "^8.0.0",
|
||||
"@types/imagemin-pngquant": "^7.0.0",
|
||||
"@types/json2csv": "^5.0.1",
|
||||
"@types/lodash": "^4.14.158",
|
||||
"@types/sharp": "^0.25.1",
|
||||
"firebase-tools": "^9.2.2",
|
||||
"husky": "^4.2.5",
|
||||
"prettier": "^2.1.1",
|
||||
"pretty-quick": "^3.0.0",
|
||||
"ts-node": "^8.6.2",
|
||||
"tslint": "^6.1.0",
|
||||
"typescript": "^3.2.2"
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {
|
||||
"pre-commit": "pretty-quick --staged"
|
||||
}
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
import * as _ from "lodash";
|
||||
import { db, auth } from "../config";
|
||||
import * as admin from "firebase-admin";
|
||||
import utilFns from "../utils";
|
||||
type ActionData = {
|
||||
ref: {
|
||||
id: string;
|
||||
path: string;
|
||||
parentId: string;
|
||||
tablePath: string;
|
||||
};
|
||||
schemaDocPath?: string;
|
||||
column: any;
|
||||
action: "run" | "redo" | "undo";
|
||||
actionParams: any;
|
||||
};
|
||||
// import {
|
||||
// makeId,
|
||||
// hasGoogleMailServer,
|
||||
// hasMissingFields,
|
||||
// } from "../utils";
|
||||
|
||||
import { hasAnyRole } from "../utils/auth";
|
||||
|
||||
const missingFieldsReducer = (data: any) => (acc: string[], curr: string) => {
|
||||
if (data[curr] === undefined) {
|
||||
return [...acc, curr];
|
||||
} else return acc;
|
||||
};
|
||||
|
||||
const generateSchemaDocPath = (tablePath) => {
|
||||
const pathComponents = tablePath.split("/");
|
||||
return `_FIRETABLE_/settings/${
|
||||
pathComponents[1] === "table" ? "schema" : "groupSchema"
|
||||
}/${pathComponents[2]}`;
|
||||
};
|
||||
const serverTimestamp = admin.firestore.FieldValue.serverTimestamp;
|
||||
|
||||
export const actionScript = functions.https.onCall(
|
||||
async (data: ActionData, context: functions.https.CallableContext) => {
|
||||
try {
|
||||
if (!context) {
|
||||
throw Error(`You are unauthenticated`);
|
||||
}
|
||||
|
||||
const { ref, actionParams, column, action, schemaDocPath } = data;
|
||||
const _schemaDocPath =
|
||||
schemaDocPath ?? generateSchemaDocPath(ref.tablePath);
|
||||
const [schemaDoc, rowQuery] = await Promise.all([
|
||||
db.doc(_schemaDocPath).get(),
|
||||
db.doc(ref.path).get(),
|
||||
]);
|
||||
const row = rowQuery.data();
|
||||
const schemaDocData = schemaDoc.data();
|
||||
if (!schemaDocData) {
|
||||
return {
|
||||
success: false,
|
||||
message: "no schema found",
|
||||
};
|
||||
}
|
||||
const config = schemaDocData.columns[column.key].config;
|
||||
const { script, requiredRoles, requiredFields, undo, redo } = config;
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
throw Error(`You need to specify at least one role to run this script`);
|
||||
}
|
||||
if (!hasAnyRole(requiredRoles, context)) {
|
||||
throw Error(`You don't have the required roles permissions`);
|
||||
}
|
||||
|
||||
const missingRequiredFields = requiredFields
|
||||
? requiredFields.reduce(missingFieldsReducer(row), [])
|
||||
: [];
|
||||
if (missingRequiredFields.length > 0) {
|
||||
throw new Error(
|
||||
`Missing required fields:${missingRequiredFields.join(", ")}`
|
||||
);
|
||||
}
|
||||
//
|
||||
// get auth
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
undo,
|
||||
redo,
|
||||
row,
|
||||
ref,
|
||||
actionParams,
|
||||
column,
|
||||
schemaDocData,
|
||||
script,
|
||||
requiredRoles,
|
||||
requiredFields,
|
||||
})
|
||||
);
|
||||
|
||||
const result: {
|
||||
message: string;
|
||||
status: string;
|
||||
success: boolean;
|
||||
} = await eval(
|
||||
`async({row,db, ref,auth,utilFns,actionParams,context})=>{${
|
||||
action === "undo" ? config["undo.script"] : script
|
||||
}}`
|
||||
)({ row, db, auth, utilFns, ref, actionParams, context });
|
||||
if (result.success)
|
||||
return {
|
||||
success: result.success,
|
||||
message: result.message,
|
||||
cellValue: {
|
||||
redo: config["redo.enabled"],
|
||||
status: result.status,
|
||||
completedAt: serverTimestamp(),
|
||||
meta: { ranBy: context.auth!.token.email },
|
||||
undo: action !== "undo" && config["undo.enabled"],
|
||||
},
|
||||
undo: config["undo.enabled"],
|
||||
redo: config["redo.enabled"],
|
||||
};
|
||||
else
|
||||
return {
|
||||
success: false,
|
||||
message: result.message,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -1,81 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
import * as admin from "firebase-admin";
|
||||
|
||||
import { db } from "../config";
|
||||
import config, { collectionPath, functionName } from "../functionConfig";
|
||||
// generated using generateConfig.ts
|
||||
|
||||
const incrementor = (v: number) => admin.firestore.FieldValue.increment(v);
|
||||
const functionConfig: any = config;
|
||||
|
||||
const subDocTrigger = async (
|
||||
change: functions.Change<functions.firestore.DocumentSnapshot>,
|
||||
context: functions.EventContext
|
||||
) => {
|
||||
const beforeData = change.before?.data();
|
||||
const afterData = change.after?.data();
|
||||
const triggerType =
|
||||
Boolean(beforeData) && Boolean(afterData)
|
||||
? "update"
|
||||
: Boolean(afterData)
|
||||
? "create"
|
||||
: "delete";
|
||||
const parentDocRef = change.after
|
||||
? change.after.ref.parent.parent
|
||||
: change.before.ref.parent.parent;
|
||||
const parentDoc = await parentDocRef?.get();
|
||||
const parentDocData = parentDoc?.data();
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
parentDocRef,
|
||||
parentDocData,
|
||||
beforeData,
|
||||
afterData,
|
||||
triggerType,
|
||||
})
|
||||
);
|
||||
//return false;
|
||||
const aggregateData = await functionConfig.reduce(
|
||||
async (accAggregate: any, currAggregate) => {
|
||||
// check relavent sub-table
|
||||
if (currAggregate.subtables.includes(context.params.subCollectionId)) {
|
||||
const newValue = await currAggregate.eval(db)({
|
||||
beforeData,
|
||||
afterData,
|
||||
incrementor,
|
||||
triggerType,
|
||||
});
|
||||
if (newValue !== undefined) {
|
||||
return {
|
||||
...(await accAggregate),
|
||||
...Object.keys(newValue).reduce((acc, curr) => {
|
||||
return {
|
||||
...acc,
|
||||
[`${currAggregate.fieldName}.${curr}`]: newValue[curr],
|
||||
};
|
||||
}, {}),
|
||||
};
|
||||
} else return await accAggregate;
|
||||
} else return await accAggregate;
|
||||
},
|
||||
{}
|
||||
);
|
||||
const update = Object.keys(aggregateData).reduce((acc: any, curr: string) => {
|
||||
if (aggregateData[curr] !== undefined) {
|
||||
return { ...acc, [curr]: aggregateData[curr] };
|
||||
} else {
|
||||
return acc;
|
||||
}
|
||||
}, {});
|
||||
console.log({ update, aggregateData });
|
||||
if (parentDocRef && Object.keys(update).length !== 0) {
|
||||
return parentDocRef.update(update);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
export const FT_aggregates = {
|
||||
[functionName]: functions.firestore
|
||||
.document(`${collectionPath}/{parentId}/{subCollectionId}/{docId}`)
|
||||
.onWrite(subDocTrigger),
|
||||
};
|
||||
@@ -1,218 +0,0 @@
|
||||
import algoliasearch from "algoliasearch";
|
||||
import * as functions from "firebase-functions";
|
||||
import * as _ from "lodash";
|
||||
import { env } from "../config";
|
||||
import fnConfig from "../functionConfig"; // generated using generateConfig.ts
|
||||
const functionConfig: any = fnConfig;
|
||||
|
||||
const APP_ID = env.algolia ? env.algolia.app : "NEEDS_CONFIG";
|
||||
const ADMIN_KEY = env.algolia ? env.algolia.key : "NEEDS_CONFIG";
|
||||
|
||||
const client = algoliasearch(APP_ID, ADMIN_KEY);
|
||||
|
||||
const missingFieldsReducer = (data: any) => (acc: string[], curr: string) => {
|
||||
if (data[curr] === undefined) {
|
||||
return [...acc, curr];
|
||||
} else return acc;
|
||||
};
|
||||
|
||||
const filterSnapshot = (
|
||||
field: { docPath: string; snapshot: any },
|
||||
preservedKeys: string[]
|
||||
) => {
|
||||
return {
|
||||
docPath: field.docPath,
|
||||
...preservedKeys.reduce((acc: any, currentKey: string) => {
|
||||
const value = _.get(field.snapshot, currentKey);
|
||||
if (value) {
|
||||
return { ...acc, snapshot: { [currentKey]: value, ...acc.snapshot } };
|
||||
} else return acc;
|
||||
}, {}),
|
||||
};
|
||||
};
|
||||
|
||||
// returns object of fieldsToSync
|
||||
const algoliaReducer = (docData: FirebaseFirestore.DocumentData) => (
|
||||
acc: any,
|
||||
curr: string | { fieldName: string; snapshotFields: string[] }
|
||||
) => {
|
||||
if (typeof curr === "string") {
|
||||
if (docData[curr] && typeof docData[curr].toDate === "function") {
|
||||
return {
|
||||
...acc,
|
||||
[curr]: docData[curr].toDate().getTime() / 1000,
|
||||
};
|
||||
} else if (docData[curr] !== undefined || docData[curr] !== null) {
|
||||
return { ...acc, [curr]: docData[curr] };
|
||||
} else {
|
||||
return acc;
|
||||
}
|
||||
} else {
|
||||
if (docData[curr.fieldName] && curr.snapshotFields) {
|
||||
return {
|
||||
...acc,
|
||||
[curr.fieldName]: docData[curr.fieldName].map((snapshot) =>
|
||||
filterSnapshot(snapshot, curr.snapshotFields)
|
||||
),
|
||||
};
|
||||
} else {
|
||||
return acc;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const addToAlgolia = (
|
||||
config: any,
|
||||
fieldsToSync: string[],
|
||||
requiredFields: string[],
|
||||
indexName?: string
|
||||
) => (
|
||||
snapshot: FirebaseFirestore.DocumentSnapshot,
|
||||
context: functions.EventContext
|
||||
) => {
|
||||
if (config.subTable && config.subTable !== context.params.subCollectionId)
|
||||
return false;
|
||||
const _index = indexName
|
||||
? indexName
|
||||
: `${config.name}${config.subTable ? `_${config.subTable}` : ""}`;
|
||||
const objectID = snapshot.id;
|
||||
const docData = snapshot.data();
|
||||
if (!docData) return false; // returns if theres no data in the doc
|
||||
const missingRequiredFields = requiredFields.reduce(
|
||||
missingFieldsReducer(docData),
|
||||
[]
|
||||
);
|
||||
if (missingRequiredFields.length > 0) {
|
||||
throw new Error(
|
||||
`Missing required fields:${missingRequiredFields.join(", ")}`
|
||||
);
|
||||
}
|
||||
const algoliaData = fieldsToSync.reduce(algoliaReducer(docData), {});
|
||||
if (Object.keys(algoliaData).length === 0) return false; // returns if theres nothing to sync
|
||||
const index = client.initIndex(_index); // initialize algolia index
|
||||
return index.saveObject({ ...algoliaData, objectID }); // add new algolia entry
|
||||
};
|
||||
|
||||
const updateAlgolia = (
|
||||
config: any,
|
||||
fieldsToSync: string[],
|
||||
requiredFields: string[],
|
||||
indexName?: string
|
||||
) => async (
|
||||
snapshot: functions.Change<FirebaseFirestore.DocumentSnapshot>,
|
||||
context: functions.EventContext
|
||||
) => {
|
||||
const objectID = snapshot.after.id;
|
||||
try {
|
||||
if (config.subTable && config.subTable !== context.params.subCollectionId)
|
||||
return false;
|
||||
const _index = indexName
|
||||
? indexName
|
||||
: `${config.name}${config.subTable ? `_${config.subTable}` : ""}`;
|
||||
|
||||
const docData = snapshot.after.data();
|
||||
if (!docData) return false; // returns if theres no data in the doc
|
||||
|
||||
const missingRequiredFields = requiredFields.reduce(
|
||||
missingFieldsReducer(docData),
|
||||
[]
|
||||
);
|
||||
if (missingRequiredFields.length > 0) {
|
||||
throw new Error(
|
||||
`Missing required fields:${missingRequiredFields.join(", ")}`
|
||||
);
|
||||
}
|
||||
const algoliaData = fieldsToSync.reduce(algoliaReducer(docData), {});
|
||||
if (Object.keys(algoliaData).length === 0) return false; // returns if theres nothing to sync
|
||||
const index = client.initIndex(_index); // initialize algolia index
|
||||
const algoliaTask = await index.saveObject({ ...algoliaData, objectID }); // add update algolia entry
|
||||
|
||||
return algoliaTask;
|
||||
} catch (error) {
|
||||
console.error(JSON.stringify({ error, objectID }));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const deleteFromAlgolia = (config: any, indexName?: string) => (
|
||||
snapshot: FirebaseFirestore.DocumentSnapshot,
|
||||
context: functions.EventContext
|
||||
) => {
|
||||
if (config.subTable && config.subTable !== context.params.subCollectionId)
|
||||
return false;
|
||||
const _index = indexName
|
||||
? indexName
|
||||
: `${config.name}${config.subTable ? `_${config.subTable}` : ""}`;
|
||||
const objectID = snapshot.id;
|
||||
const index = client.initIndex(_index); // initialize algolia index
|
||||
return index.deleteObject(objectID); // delete algolia entry
|
||||
};
|
||||
|
||||
const documentPathGenerator = (config) =>
|
||||
`${
|
||||
config.subTable
|
||||
? `${config.name}/{parentId}/{subCollectionId}/{docId}`
|
||||
: `${config.name}/{docId}`
|
||||
}`;
|
||||
/**
|
||||
* returns 3 different trigger functions (onCreate,onUpdate,onDelete) in an object
|
||||
* @param config configuration object
|
||||
*/
|
||||
const algoliaFnsGenerator = (config) => ({
|
||||
onCreate: functions.firestore
|
||||
.document(documentPathGenerator(config))
|
||||
.onCreate(
|
||||
config.indices
|
||||
? (snapshot, context) =>
|
||||
Promise.all(
|
||||
config.indices.map((index) =>
|
||||
addToAlgolia(
|
||||
config,
|
||||
index.fieldsToSync,
|
||||
config.requiredFields ?? [],
|
||||
index.name
|
||||
)(snapshot, context)
|
||||
)
|
||||
)
|
||||
: addToAlgolia(config, config.fieldsToSync, config.requiredFields ?? [])
|
||||
),
|
||||
onUpdate: functions.firestore
|
||||
.document(documentPathGenerator(config))
|
||||
.onUpdate(
|
||||
config.indices
|
||||
? (snapshot, context) =>
|
||||
Promise.all(
|
||||
config.indices.map((index) =>
|
||||
updateAlgolia(
|
||||
config,
|
||||
index.fieldsToSync,
|
||||
config.requiredFields ?? [],
|
||||
index.name
|
||||
)(snapshot, context)
|
||||
)
|
||||
)
|
||||
: updateAlgolia(
|
||||
config,
|
||||
config.fieldsToSync,
|
||||
config.requiredFields ?? []
|
||||
)
|
||||
),
|
||||
onDelete: functions.firestore
|
||||
.document(documentPathGenerator(config))
|
||||
.onDelete(
|
||||
config.indices
|
||||
? (snapshot, context) =>
|
||||
Promise.all(
|
||||
config.indices.map((index) =>
|
||||
deleteFromAlgolia(config, index.name)(snapshot, context)
|
||||
)
|
||||
)
|
||||
: deleteFromAlgolia(config)
|
||||
),
|
||||
});
|
||||
|
||||
export const FT_algolia = {
|
||||
[`${functionConfig.name}${
|
||||
functionConfig.subTable ? `${functionConfig.subTable}` : ""
|
||||
}`]: { ...algoliaFnsGenerator(functionConfig) },
|
||||
};
|
||||
@@ -1,51 +0,0 @@
|
||||
import algoliasearch from "algoliasearch";
|
||||
import * as functions from "firebase-functions";
|
||||
import { env } from "./config";
|
||||
|
||||
const algoliaClient = algoliasearch(env.algolia.app, env.algolia.key);
|
||||
|
||||
export const getAlgoliaSearchKey = functions.https.onCall(async (
|
||||
data: { index: string },
|
||||
context: functions.https.CallableContext
|
||||
) => {
|
||||
const requestedIndex = data.index
|
||||
try {
|
||||
if (!context.auth || !context.auth.token) throw new Error("Unauthenticated")
|
||||
|
||||
const allIndicesRoles = ['ADMIN',"TEAM"] // you can add more roles here that need access to all algolia indices
|
||||
|
||||
const rolesIndicesAccess = {
|
||||
"ROLE":["index_1","index_2"]
|
||||
}
|
||||
const userRoles = context.auth.token.roles
|
||||
if (userRoles.some(role=> allIndicesRoles.includes(role)||rolesIndicesAccess[role].includes(requestedIndex))){
|
||||
const validUntil = Math.floor(Date.now() / 1000) + 3600;
|
||||
const key = algoliaClient.generateSecuredApiKey(
|
||||
env.algolia.search,
|
||||
{
|
||||
filters:"",
|
||||
validUntil,
|
||||
restrictIndices: [requestedIndex],
|
||||
userToken: context.auth.uid,
|
||||
}
|
||||
);
|
||||
return {
|
||||
data: key,
|
||||
success: true,
|
||||
};
|
||||
}else{
|
||||
return {
|
||||
message: 'Missing Required roles for this index',
|
||||
success: false,
|
||||
};
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
import * as firestore from "@google-cloud/firestore";
|
||||
import { hasAnyRole } from "./utils/auth";
|
||||
|
||||
const client = new firestore.v1.FirestoreAdminClient();
|
||||
|
||||
// Replace BUCKET_NAME
|
||||
const bucket = "gs://BUCKET_NAME";
|
||||
/*
|
||||
const restoreFirestoreBackup = (collectionIds: string[] = []) => {
|
||||
const projectId = process.env.GCP_PROJECT || process.env.GCLOUD_PROJECT;
|
||||
const databaseName = client.databasePath(projectId, "(default)");
|
||||
const date = new Date();
|
||||
|
||||
const backupFolder = `${date.getFullYear()}-${
|
||||
date.getMonth() + 1
|
||||
}-${date.getDate()}`;
|
||||
const inputUriPrefix = bucket + "/" + backupFolder;
|
||||
console.log(inputUriPrefix);
|
||||
return client
|
||||
.importDocuments({
|
||||
name: databaseName,
|
||||
inputUriPrefix,
|
||||
// Leave collectionIds empty to export all collections
|
||||
// or set to a list of collection IDs to export,
|
||||
// collectionIds: ['users', 'posts']
|
||||
collectionIds,
|
||||
})
|
||||
.then((responses) => {
|
||||
const response = responses[0];
|
||||
console.log(`Operation Name: ${response["name"]}`);
|
||||
return response;
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
throw new Error("import operation failed");
|
||||
});
|
||||
};
|
||||
|
||||
export const scheduledFirestoreImport = functions.pubsub
|
||||
.schedule("every 24 hours")
|
||||
.onRun((context) => {
|
||||
console.log(context);
|
||||
return restoreFirestoreBackup();
|
||||
});
|
||||
*/
|
||||
|
||||
const firestoreBackup = (collectionIds: string[] = []) => {
|
||||
const projectId = process.env.GCP_PROJECT || process.env.GCLOUD_PROJECT;
|
||||
const databaseName = client.databasePath(projectId ?? "", "(default)");
|
||||
const date = new Date();
|
||||
|
||||
const backupFolder = `${date.getUTCFullYear()}-${
|
||||
date.getUTCMonth() + 1
|
||||
}-${date.getUTCDate()}-${date.getUTCHours()}`;
|
||||
|
||||
return client
|
||||
.exportDocuments({
|
||||
name: databaseName,
|
||||
outputUriPrefix: bucket + "/" + backupFolder,
|
||||
// Leave collectionIds empty to export all collections
|
||||
// or set to a list of collection IDs to export,
|
||||
// collectionIds: ['users', 'posts']
|
||||
collectionIds,
|
||||
})
|
||||
.then((responses) => {
|
||||
const response = responses[0];
|
||||
console.log(`Operation Name: ${response["name"]}`);
|
||||
return response;
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
throw new Error("Export operation failed");
|
||||
});
|
||||
};
|
||||
export const scheduledFirestoreBackup = functions.pubsub
|
||||
.schedule("every 12 hours")
|
||||
.onRun((context) => {
|
||||
console.log(context);
|
||||
return firestoreBackup();
|
||||
});
|
||||
|
||||
export const callableFirestoreBackup = functions.https.onCall(
|
||||
async (data, context) => {
|
||||
console.log(data);
|
||||
const authorized = hasAnyRole(["ADMIN"], context);
|
||||
if (!context.auth || !authorized) {
|
||||
console.warn(`unauthorized user${context}`);
|
||||
return {
|
||||
success: false,
|
||||
message: "you don't have permissions to send this email",
|
||||
};
|
||||
} else {
|
||||
await firestoreBackup();
|
||||
return {
|
||||
success: true,
|
||||
message: "backup ran",
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -1,96 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
import { hasAnyRole } from "../utils/auth";
|
||||
import { serverTimestamp } from "../utils";
|
||||
import { db } from "../config";
|
||||
const { CloudBuildClient } = require("@google-cloud/cloudbuild");
|
||||
const cb = new CloudBuildClient();
|
||||
|
||||
export const triggerCloudBuild = functions.https.onCall(
|
||||
async (
|
||||
data: {
|
||||
ref: {
|
||||
id: string;
|
||||
path: string;
|
||||
parentId: string;
|
||||
};
|
||||
action: "run" | "redo" | "undo";
|
||||
},
|
||||
context: functions.https.CallableContext
|
||||
) => {
|
||||
const {
|
||||
ref, // action
|
||||
} = data;
|
||||
|
||||
const authorized = hasAnyRole(["ADMIN"], context);
|
||||
if (!context.auth || !authorized) {
|
||||
console.warn(`unauthorized user${context}`);
|
||||
return {
|
||||
success: false,
|
||||
message: "you don't have permission to trigger a build",
|
||||
};
|
||||
}
|
||||
const doc = await db.doc(ref.path).get();
|
||||
const row = doc.data();
|
||||
if (!row) throw Error("No row data");
|
||||
const { triggerId, branch, projectId, groupName, functionConfig } = row;
|
||||
// Starts a build against the branch provided.
|
||||
const [resp] = await cb.runBuildTrigger({
|
||||
projectId, //project hosting cloud build
|
||||
triggerId,
|
||||
source: {
|
||||
branchName: branch,
|
||||
substitutions: {
|
||||
_PROJECT_ID: projectId,
|
||||
_FUNCTIONS_GROUP: groupName,
|
||||
_FUNCTION_CONFIG: functionConfig,
|
||||
_REQUEST_DOC_PATH: ref.path,
|
||||
},
|
||||
},
|
||||
});
|
||||
const buildId = resp.metadata.build.id;
|
||||
const logUrl = resp.metadata.build.logUrl;
|
||||
console.log({ buildId, logUrl });
|
||||
await db
|
||||
.doc(ref.path)
|
||||
.update({ buildId, logUrl, buildDuration: { start: serverTimestamp() } });
|
||||
if (buildId && logUrl) {
|
||||
return {
|
||||
message: "cloud functions are snow flakes",
|
||||
cellValue: {
|
||||
redo: true,
|
||||
status: `Triggered`,
|
||||
completedAt: serverTimestamp(),
|
||||
meta: { ranBy: context.auth.token.email },
|
||||
undo: false,
|
||||
},
|
||||
success: true,
|
||||
};
|
||||
}
|
||||
return false;
|
||||
}
|
||||
);
|
||||
|
||||
export const cloudBuildUpdates = functions.pubsub
|
||||
.topic("cloud-builds")
|
||||
.onPublish(async (message, context) => {
|
||||
console.log(JSON.stringify(message));
|
||||
const { buildId, status } = message.attributes;
|
||||
console.log(JSON.stringify({ buildId, status }));
|
||||
//message
|
||||
//status: "SUCCESS"
|
||||
//buildId: "1a6d7819-aa35-486c-a29c-fb67eb39430f"
|
||||
|
||||
const query = await db
|
||||
.collection("cloudFunctions")
|
||||
.where("buildId", "==", buildId)
|
||||
.get();
|
||||
|
||||
if (query.docs.length !== 0) {
|
||||
const update = { status };
|
||||
if (status === "SUCCESS" || status === "FAILURE") {
|
||||
update["buildDuration.end"] = serverTimestamp();
|
||||
}
|
||||
await query.docs[0].ref.update(update);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
@@ -1,33 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
import * as _ from "lodash";
|
||||
import { hasAnyRole } from "./utils/auth";
|
||||
import { auth } from "./config";
|
||||
|
||||
// Impersonator Auth callable takes email and returns JWT of user on firebaseAuth
|
||||
// requires a user admin role
|
||||
|
||||
export const ImpersonatorAuth = functions.https.onCall(
|
||||
async (data, context) => {
|
||||
try {
|
||||
if (hasAnyRole(["ADMIN"], context)) {
|
||||
const user = await auth.getUserByEmail(data.email);
|
||||
const jwt = await auth.createCustomToken(user.uid);
|
||||
return {
|
||||
success: true,
|
||||
jwt,
|
||||
message: "successfully generated token",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
message: "admin role is required",
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: JSON.stringify(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -1,158 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
|
||||
import { db } from "../config";
|
||||
|
||||
import * as _ from "lodash";
|
||||
import { replacer } from "../utils";
|
||||
import config from "../functionConfig"; // generated using generateConfig.ts
|
||||
const functionConfig: any = config;
|
||||
// returns object of fieldsToSync
|
||||
const docReducer = (docData: FirebaseFirestore.DocumentData) => (
|
||||
acc: any,
|
||||
curr: string
|
||||
) => {
|
||||
if (docData[curr] !== undefined && docData[curr] !== null)
|
||||
return { ...acc, [curr]: docData[curr] };
|
||||
else return acc;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param targetCollection
|
||||
* @param fieldsToSync
|
||||
*/
|
||||
const cloneDoc = (targetCollection: string, fieldsToSync: string[]) => (
|
||||
snapshot: FirebaseFirestore.DocumentSnapshot
|
||||
) => {
|
||||
const docId = snapshot.id;
|
||||
const docData = snapshot.data();
|
||||
if (!docData) return false; // returns if theres no data in the doc
|
||||
const syncData = fieldsToSync.reduce(docReducer(docData), {});
|
||||
if (Object.keys(syncData).length === 0) return false; // returns if theres nothing to sync
|
||||
console.log(`creating new doc or forcing update ${docId}`);
|
||||
const collectionPath = targetCollection.replace(
|
||||
/\{\{(.*?)\}\}/g,
|
||||
replacer(docData)
|
||||
);
|
||||
if (collectionPath.includes("//")) {
|
||||
console.log(`${collectionPath} is an invalid collection path`);
|
||||
return false;
|
||||
}
|
||||
db.collection(collectionPath)
|
||||
.doc(docId)
|
||||
.set({ ...syncData, syncedAt: new Date() }, { merge: true })
|
||||
.catch((error) => console.error(error));
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param targetCollection
|
||||
* @param fieldsToSync
|
||||
*/
|
||||
const syncDoc = (targetCollection: string, fieldsToSync: string[]) => async (
|
||||
snapshot: FirebaseFirestore.DocumentSnapshot
|
||||
) => {
|
||||
const docId = snapshot.id;
|
||||
const docData = snapshot.data();
|
||||
if (!docData) return false; // returns if theres no data in the doc
|
||||
const syncData = fieldsToSync.reduce(docReducer(docData), {});
|
||||
|
||||
const collectionPath = targetCollection.replace(
|
||||
/\{\{(.*?)\}\}/g,
|
||||
replacer(docData)
|
||||
);
|
||||
|
||||
if (collectionPath.includes("//")) {
|
||||
console.log(`${collectionPath} is an invalid collection path`);
|
||||
return false;
|
||||
}
|
||||
if (Object.keys(syncData).length === 0) return false; // returns if theres nothing to sync
|
||||
const targetDoc = await db.collection(collectionPath).doc(docId).get();
|
||||
if (!targetDoc.exists) return false;
|
||||
db.collection(collectionPath)
|
||||
.doc(docId)
|
||||
.update({ ...syncData, syncedAt: new Date() })
|
||||
.catch((error) => console.error(error));
|
||||
return true;
|
||||
};
|
||||
|
||||
const deleteDoc = (targetCollection: string) => async (
|
||||
snapshot: FirebaseFirestore.DocumentSnapshot,
|
||||
context: functions.EventContext
|
||||
) => {
|
||||
const { docId } = context.params;
|
||||
return db.collection(targetCollection).doc(docId).delete();
|
||||
};
|
||||
|
||||
/**
|
||||
* onUpdate change to snapshot adapter
|
||||
* @param targetCollection
|
||||
* @param fieldsToSync
|
||||
*/
|
||||
const syncDocOnUpdate = (
|
||||
targetCollection: string,
|
||||
fieldsToSync: string[],
|
||||
forcedUpdate: boolean
|
||||
) => (snapshot: functions.Change<FirebaseFirestore.DocumentSnapshot>) => {
|
||||
const afterData = snapshot.after.data();
|
||||
const beforeData = snapshot.before.data();
|
||||
const hasChanged = !_.isEqual(afterData, beforeData);
|
||||
if (hasChanged) {
|
||||
if (forcedUpdate === true) {
|
||||
return cloneDoc(targetCollection, fieldsToSync)(snapshot.after);
|
||||
} else {
|
||||
return syncDoc(targetCollection, fieldsToSync)(snapshot.after);
|
||||
}
|
||||
} else {
|
||||
console.warn("no change detected");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* returns 2 different trigger functions (onCreate,onUpdate) in an object
|
||||
* @param collectionConfig configuration object
|
||||
* onCreate
|
||||
* onUpdate
|
||||
* onDelete
|
||||
* source
|
||||
* target
|
||||
* fieldsToSync
|
||||
*
|
||||
*/
|
||||
const collectionSyncFnsGenerator = (collectionConfig) =>
|
||||
Object.entries({
|
||||
onCreate: collectionConfig.onCreate
|
||||
? functions.firestore
|
||||
.document(`${collectionConfig.source}/{docId}`)
|
||||
.onCreate(
|
||||
cloneDoc(collectionConfig.target, collectionConfig.fieldsToSync)
|
||||
)
|
||||
: null,
|
||||
onUpdate: collectionConfig.onUpdate
|
||||
? functions.firestore
|
||||
.document(`${collectionConfig.source}/{docId}`)
|
||||
.onUpdate(
|
||||
syncDocOnUpdate(
|
||||
collectionConfig.target,
|
||||
collectionConfig.fieldsToSync,
|
||||
collectionConfig.forcedUpdate
|
||||
)
|
||||
)
|
||||
: null,
|
||||
onDelete: collectionConfig.onDelete
|
||||
? functions.firestore
|
||||
.document(`${collectionConfig.source}/{docId}`)
|
||||
.onDelete(deleteDoc(collectionConfig.target))
|
||||
: null,
|
||||
}).reduce((a, [k, v]) => (v === null ? a : { ...a, [k]: v }), {});
|
||||
|
||||
//export default collectionSyncFnsGenerator;
|
||||
export const FT_sync = {
|
||||
[`${`${`${functionConfig.source}`
|
||||
.replace(/\//g, "_")
|
||||
.replace(/_{.*?}_/g, "_")}`}2${`${`${functionConfig.target}`
|
||||
.replace(/\//g, "_")
|
||||
.replace(/_{.*?}_/g, "_")}`}`]: collectionSyncFnsGenerator(functionConfig),
|
||||
};
|
||||
@@ -1,113 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
// tslint:disable-next-line: no-import-side-effect
|
||||
import "../config";
|
||||
import * as admin from "firebase-admin";
|
||||
import * as path from "path";
|
||||
import * as os from "os";
|
||||
import * as fs from "fs";
|
||||
import * as sharp from "sharp";
|
||||
import * as imagemin from "imagemin";
|
||||
import * as imageminMozjpeg from "imagemin-mozjpeg";
|
||||
import imageminPngquant from "imagemin-pngquant";
|
||||
import config_ from "../functionConfig";
|
||||
const SUPPORTED_TYPES = ["image/jpeg", "image/png"];
|
||||
const DEFAULT_SIZES = ["400x400", "200x200", "100x100"];
|
||||
const config: any = config_;
|
||||
const sizes =
|
||||
config && Array.isArray(config.sizes) && typeof config.sizes[0] === "string"
|
||||
? config.sizes
|
||||
: DEFAULT_SIZES;
|
||||
const excludePaths =
|
||||
config &&
|
||||
Array.isArray(config.excludes) &&
|
||||
typeof config.excludes[0] === "string"
|
||||
? config.excludes
|
||||
: [];
|
||||
export const FT_compressedThumbnail = functions.storage
|
||||
.object()
|
||||
.onFinalize(async (object) => {
|
||||
// Log file name, size, and content type for monitoring
|
||||
console.log(object.name, object.size, object.contentType);
|
||||
// Exit if this is triggered on a file that is not an image.
|
||||
if (!object.contentType || !SUPPORTED_TYPES.includes(object.contentType)) {
|
||||
console.log("Unsupported type", object.contentType);
|
||||
return null;
|
||||
}
|
||||
// Exit if this is already a compressed thumbnail.
|
||||
if (object.metadata?.resizedImage) {
|
||||
console.log("This is already a compressed thumbnail", object.name);
|
||||
return null;
|
||||
}
|
||||
// Get Firebase Storage download token
|
||||
const token = object.metadata?.firebaseStorageDownloadTokens;
|
||||
|
||||
const filePath: string = object.name!;
|
||||
|
||||
// Check if file should be excluded based off path
|
||||
for (const excludePath of excludePaths)
|
||||
if (filePath.startsWith(excludePath)) {
|
||||
console.log("File excluded from path", excludePath);
|
||||
return null;
|
||||
}
|
||||
const baseFileName = path.basename(filePath, path.extname(filePath));
|
||||
const tempLocalFile = path.join(
|
||||
os.tmpdir(),
|
||||
baseFileName + path.extname(filePath)
|
||||
);
|
||||
// Download file from bucket.
|
||||
const bucket = admin.storage().bucket(object.bucket);
|
||||
await bucket.file(filePath).download({ destination: tempLocalFile });
|
||||
for (const size of sizes) {
|
||||
try {
|
||||
const thumbFilePath = path.normalize(
|
||||
path.format({
|
||||
dir: path.dirname(filePath),
|
||||
name: baseFileName + "__" + size,
|
||||
ext: path.extname(filePath),
|
||||
})
|
||||
);
|
||||
const tempLocalThumbFile = path.join(
|
||||
os.tmpdir(),
|
||||
path.basename(thumbFilePath)
|
||||
);
|
||||
// Resize image to thumbnail size
|
||||
const resized = await sharp(tempLocalFile)
|
||||
.rotate()
|
||||
.resize(
|
||||
parseInt(size.split("x")[0], 10),
|
||||
parseInt(size.split("x")[1], 10),
|
||||
{
|
||||
fit: "inside",
|
||||
withoutEnlargement: true,
|
||||
}
|
||||
)
|
||||
.toBuffer();
|
||||
// Compress the image
|
||||
const compressed = await imagemin.buffer(resized, {
|
||||
plugins: [
|
||||
imageminMozjpeg({ quality: 75 }),
|
||||
imageminPngquant({ quality: [0.6, 0.8] }),
|
||||
],
|
||||
});
|
||||
fs.writeFileSync(tempLocalThumbFile, compressed);
|
||||
// Upload the image
|
||||
await bucket.upload(tempLocalThumbFile, {
|
||||
destination: thumbFilePath,
|
||||
contentType: object.contentType,
|
||||
metadata: {
|
||||
metadata: {
|
||||
firebaseStorageDownloadTokens: token,
|
||||
resizedImage: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
console.log(size, "thumbnail uploaded to Storage at", thumbFilePath);
|
||||
// Once the image has been converted delete the local files to free up disk space.
|
||||
fs.unlinkSync(tempLocalThumbFile);
|
||||
} catch (e) {
|
||||
console.error(`Failed to generate thumbnail size: ${size}`, e);
|
||||
}
|
||||
}
|
||||
fs.unlinkSync(tempLocalFile);
|
||||
return filePath;
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
// Initialize Firebase Admin
|
||||
import * as functions from "firebase-functions";
|
||||
import * as admin from "firebase-admin";
|
||||
admin.initializeApp();
|
||||
|
||||
// Initialize Cloud Firestore Database
|
||||
export const db = admin.firestore();
|
||||
// Initialize Auth
|
||||
export const auth = admin.auth();
|
||||
|
||||
const settings = { timestampsInSnapshots: true };
|
||||
db.settings(settings);
|
||||
export const env = functions.config();
|
||||
@@ -1,4 +0,0 @@
|
||||
enum Collections {
|
||||
fireMail = "firemail",
|
||||
emailOTP = "emailOTP",
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
|
||||
import { db } from "../config";
|
||||
import config, { collectionPath, functionName } from "../functionConfig";
|
||||
// generated using generateConfig.ts
|
||||
const functionConfig: any = config;
|
||||
|
||||
const shouldEvaluateReducer = (listeners, before, after) =>
|
||||
listeners.reduce((acc: Boolean, currField: string) => {
|
||||
if (acc) return true;
|
||||
else
|
||||
return (
|
||||
JSON.stringify(before[currField]) !== JSON.stringify(after[currField])
|
||||
);
|
||||
}, false);
|
||||
|
||||
export const derivativeOnChange = async (
|
||||
ref: FirebaseFirestore.DocumentReference<FirebaseFirestore.DocumentData>,
|
||||
beforeData: FirebaseFirestore.DocumentData,
|
||||
afterData: FirebaseFirestore.DocumentData
|
||||
) => {
|
||||
const update = await functionConfig.reduce(
|
||||
async (accUpdates: any, currDerivative) => {
|
||||
const shouldEval = shouldEvaluateReducer(
|
||||
currDerivative.listenerFields,
|
||||
beforeData,
|
||||
afterData
|
||||
);
|
||||
if (shouldEval) {
|
||||
const newValue = await currDerivative.eval(db)({
|
||||
row: afterData,
|
||||
ref,
|
||||
});
|
||||
if (newValue !== undefined) {
|
||||
return {
|
||||
...(await accUpdates),
|
||||
[currDerivative.fieldName]: newValue,
|
||||
};
|
||||
}
|
||||
}
|
||||
return await accUpdates;
|
||||
},
|
||||
{}
|
||||
);
|
||||
if (Object.keys(update).length !== 0) {
|
||||
return ref.update(update);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
export const derivativeOnCreate = async (
|
||||
snapshot: functions.firestore.DocumentSnapshot
|
||||
) => {
|
||||
const docData = snapshot.data();
|
||||
|
||||
if (!docData) return false;
|
||||
return derivativeOnChange(snapshot.ref, {}, docData);
|
||||
};
|
||||
|
||||
export const derivativeOnUpdate = async (
|
||||
Change: functions.Change<FirebaseFirestore.DocumentSnapshot>
|
||||
) => {
|
||||
const beforeData = Change.before.data();
|
||||
const afterData = Change.after.data();
|
||||
if (!beforeData || !afterData) return false;
|
||||
return derivativeOnChange(Change.after.ref, beforeData, afterData);
|
||||
};
|
||||
|
||||
export const FT_derivatives = {
|
||||
[functionName]: {
|
||||
u: functions.firestore
|
||||
.document(`${collectionPath}/{docId}`)
|
||||
.onUpdate(derivativeOnUpdate),
|
||||
c: functions.firestore
|
||||
.document(`${collectionPath}/{docId}`)
|
||||
.onCreate(derivativeOnCreate),
|
||||
},
|
||||
};
|
||||
@@ -1,144 +0,0 @@
|
||||
import { firestore } from "firebase-functions";
|
||||
|
||||
import { sendEmail } from "../utils/email";
|
||||
import { hasRequiredFields } from "../utils";
|
||||
import { db } from "../config";
|
||||
import _config from "../functionConfig"; // generated using generateConfig.ts
|
||||
const functionConfig: any = _config;
|
||||
type EmailOnTriggerConfig = {
|
||||
collectionPath: string;
|
||||
templateId: string;
|
||||
categories: string[];
|
||||
onCreate: Boolean;
|
||||
from: Function;
|
||||
to: Function;
|
||||
attachments?: Function;
|
||||
bcc?: Function;
|
||||
cc?: Function;
|
||||
requiredFields: string[];
|
||||
shouldSend: (
|
||||
snapshot:
|
||||
| firestore.DocumentSnapshot
|
||||
| {
|
||||
before: firestore.DocumentSnapshot;
|
||||
after: firestore.DocumentSnapshot;
|
||||
}
|
||||
) => Boolean;
|
||||
onUpdate: Boolean;
|
||||
};
|
||||
const emailOnCreate = (config: EmailOnTriggerConfig) =>
|
||||
firestore
|
||||
.document(`${config.collectionPath}/{docId}`)
|
||||
.onCreate(async (snapshot) => {
|
||||
try {
|
||||
const snapshotData = snapshot.data();
|
||||
if (!snapshotData) throw Error("no snapshot data");
|
||||
|
||||
const shouldSend = config.shouldSend(snapshot);
|
||||
const hasAllRequiredFields = hasRequiredFields(
|
||||
config.requiredFields,
|
||||
snapshotData
|
||||
);
|
||||
const from = await config.from(snapshotData, db);
|
||||
const to = await config.to(snapshotData, db);
|
||||
|
||||
const optionalFields = await ["attachments", "cc", "bcc"].reduce(
|
||||
async (accOptions, currOption) => {
|
||||
if (config[currOption]) {
|
||||
return {
|
||||
...(await accOptions),
|
||||
[currOption]: await config[currOption](snapshotData, db),
|
||||
};
|
||||
} else return await accOptions;
|
||||
},
|
||||
{}
|
||||
);
|
||||
console.log(JSON.stringify({ optionalFields }));
|
||||
if (shouldSend && hasAllRequiredFields) {
|
||||
const msg = {
|
||||
from,
|
||||
personalizations: [
|
||||
{
|
||||
to,
|
||||
cc: optionalFields["cc"],
|
||||
bcc: optionalFields["bcc"],
|
||||
dynamic_template_data: {
|
||||
...snapshotData,
|
||||
},
|
||||
},
|
||||
],
|
||||
template_id: config.templateId,
|
||||
categories: config.categories,
|
||||
attachments: optionalFields["attachments"],
|
||||
};
|
||||
console.log({ msg });
|
||||
const resp = await sendEmail(msg);
|
||||
console.log({ resp });
|
||||
return resp;
|
||||
} else {
|
||||
console.log("requirements were not met");
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Failed", JSON.stringify(error));
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
const emailOnUpdate = (config: EmailOnTriggerConfig) =>
|
||||
firestore
|
||||
.document(`${config.collectionPath}/{docId}`)
|
||||
.onUpdate(async (change) => {
|
||||
try {
|
||||
const beforeData = change.before.data();
|
||||
const afterData = change.after.data();
|
||||
if (!beforeData || !afterData) throw Error("no data found in snapshot");
|
||||
const shouldSend = config.shouldSend(change);
|
||||
const hasAllRequiredFields = hasRequiredFields(
|
||||
config.requiredFields,
|
||||
afterData
|
||||
);
|
||||
const dynamic_template_data = config.requiredFields.reduce(
|
||||
(acc: any, curr: string) => {
|
||||
return { ...acc, [curr]: afterData[curr] };
|
||||
},
|
||||
{}
|
||||
);
|
||||
if (shouldSend && hasAllRequiredFields) {
|
||||
const from = await config.from(afterData, db);
|
||||
const to = await config.to(afterData, db);
|
||||
const msg = {
|
||||
from,
|
||||
personalizations: [
|
||||
{
|
||||
to,
|
||||
dynamic_template_data,
|
||||
},
|
||||
],
|
||||
template_id: config.templateId,
|
||||
categories: config.categories,
|
||||
};
|
||||
await sendEmail(msg);
|
||||
|
||||
return true;
|
||||
} else {
|
||||
console.log("requirements were not met");
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(error);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
const emailOnTriggerFns = (config: EmailOnTriggerConfig) =>
|
||||
Object.entries({
|
||||
onCreate: config.onCreate ? emailOnCreate(config) : null,
|
||||
onUpdate: config.onUpdate ? emailOnUpdate(config) : null,
|
||||
}).reduce((a, [k, v]) => (v === null ? a : { ...a, [k]: v }), {});
|
||||
|
||||
export const FT_email = {
|
||||
[`${`${functionConfig.collectionPath}`
|
||||
.replace(/\//g, "_")
|
||||
.replace(/_{.*?}_/g, "_")}`]: emailOnTriggerFns(functionConfig),
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
export const collectionPath = ''
|
||||
export const functionName = ''
|
||||
export default {}
|
||||
@@ -1,98 +0,0 @@
|
||||
const fs = require("fs");
|
||||
// Initialize Firebase Admin
|
||||
import * as admin from "firebase-admin";
|
||||
// Initialize Firebase Admin
|
||||
//const serverTimestamp = admin.firestore.FieldValue.serverTimestamp;
|
||||
//const serviceAccount = require('../firebase-credentials.json')
|
||||
//admin.initializeApp({credential: admin.credential.cert(serviceAccount)});
|
||||
admin.initializeApp();
|
||||
const db = admin.firestore();
|
||||
const main = async (functionType: string, configString: string) => {
|
||||
let configData;
|
||||
switch (functionType) {
|
||||
case "FT_derivatives":
|
||||
const isCollectionGroup = configString.includes("/");
|
||||
const isSubtable = configString.includes("/subTables/");
|
||||
const collectionPath = `${configString}`;
|
||||
const schemaPath =
|
||||
isCollectionGroup && !isSubtable
|
||||
? `/_FIRETABLE_/settings/groupSchema/${configString.split("/").pop()}`
|
||||
: `_FIRETABLE_/settings/schema/${collectionPath}`;
|
||||
const schemaDoc = await db.doc(schemaPath).get();
|
||||
const schemaData = schemaDoc.data();
|
||||
if (!schemaData) return;
|
||||
const derivativeColumns = Object.values(schemaData.columns).filter(
|
||||
(col: any) => col.type === "DERIVATIVE"
|
||||
);
|
||||
const config = derivativeColumns.reduce((acc, currColumn: any) => {
|
||||
return `${acc}{
|
||||
fieldName:'${currColumn.key}',eval:(db)=> async ({row,ref}) =>{${
|
||||
currColumn.config.script
|
||||
}},listenerFields:[${(currColumn.config.listenerFields ?? [])
|
||||
.map((f) => `"${f}"`)
|
||||
.join(",")}]},`;
|
||||
}, ``);
|
||||
|
||||
configData = `export default [${config}]\nexport const collectionPath ="${
|
||||
isSubtable
|
||||
? ((path) => {
|
||||
const pathTables = path.split("/subTables/");
|
||||
const subcollection = pathTables.pop();
|
||||
return `${pathTables
|
||||
.map((t) => `${t}/{${t.replace(/-/g, "_")}DocId}`)
|
||||
.join("/")}/${subcollection}`;
|
||||
})(collectionPath)
|
||||
: collectionPath
|
||||
}"`;
|
||||
break;
|
||||
|
||||
case "FT_spark":
|
||||
const sparkSchemaDoc = await db
|
||||
.doc(`_FIRETABLE_/settings/schema/${configString}`)
|
||||
.get();
|
||||
const sparkSchemaData = sparkSchemaDoc.data();
|
||||
|
||||
configData = `export default [${sparkSchemaData?.sparks.join(
|
||||
",\n"
|
||||
)}]\n export const collectionPath='${configString}';`;
|
||||
case "FT_aggregates":
|
||||
const _schemaDoc = await db
|
||||
.doc(`_FIRETABLE_/settings/schema/${configString}`)
|
||||
.get();
|
||||
const _schemaData = _schemaDoc.data();
|
||||
if (!_schemaData) return;
|
||||
const aggregateColumns = Object.values(_schemaData.columns).filter(
|
||||
(col: any) => col.type === "AGGREGATE"
|
||||
);
|
||||
const _config = aggregateColumns.reduce((acc, currColumn: any) => {
|
||||
return `${acc}{
|
||||
fieldName:'${
|
||||
currColumn.key
|
||||
}',eval:(db)=> async ({aggregateState,incrementor,triggerType,change,afterData,beforeData}) =>{${
|
||||
currColumn.config.script
|
||||
}},subtables:[${currColumn.config.subtables
|
||||
.map((t) => `"${t}"`)
|
||||
.join(",")}]},`;
|
||||
}, ``);
|
||||
|
||||
configData = `export default [${_config}]\nexport const collectionPath ="${configString}"`;
|
||||
break;
|
||||
case "FT_subTableStats":
|
||||
configData = `export const collectionPath ="${configString}"\nexport default []`;
|
||||
break;
|
||||
default:
|
||||
configData = `export default ${configString}\n export const collectionPath=''`;
|
||||
break;
|
||||
}
|
||||
configData =
|
||||
configData +
|
||||
'\nexport const functionName = collectionPath.replace("-", "_").replace(/\\//g, "_").replace(/_{.*?}_/g, "_")';
|
||||
console.log({ configData });
|
||||
fs.writeFileSync("./src/functionConfig.ts", configData);
|
||||
return;
|
||||
};
|
||||
|
||||
main(process.argv[2], process.argv[3])
|
||||
.catch((err) => console.log(err))
|
||||
.then(() => console.log("this will succeed"))
|
||||
.catch(() => "obligatory catch");
|
||||
@@ -1,40 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
import * as _ from "lodash";
|
||||
import { db } from "../config";
|
||||
|
||||
import config from "../functionConfig"; // generated using generateConfig.ts
|
||||
const functionConfig: any = config;
|
||||
|
||||
const historySnapshot = (trackedFields: string[]) => async (
|
||||
change: functions.Change<FirebaseFirestore.DocumentSnapshot>
|
||||
) => {
|
||||
const before = change.before.data();
|
||||
const after = change.after.data();
|
||||
const docPath = change.after.ref.path;
|
||||
if (!before || !after) return false;
|
||||
const trackedChanges: any = {};
|
||||
trackedFields.forEach((field) => {
|
||||
if (!_.isEqual(before[field], after[field]))
|
||||
trackedChanges[field] = after[field];
|
||||
});
|
||||
if (!_.isEmpty(trackedChanges)) {
|
||||
await db
|
||||
.doc(docPath)
|
||||
.collection("historySnapshots")
|
||||
.add({ ...before, archivedAt: new Date() });
|
||||
return true;
|
||||
} else return false;
|
||||
};
|
||||
|
||||
const historySnapshotFnsGenerator = (collection) =>
|
||||
functions.firestore
|
||||
.document(`${collection.name}/{docId}`)
|
||||
.onUpdate(historySnapshot(collection.trackedFields));
|
||||
|
||||
//export default historySnapshotFnsGenerator;
|
||||
|
||||
export const FT_history = {
|
||||
[functionConfig.name
|
||||
.replace(/\//g, "_")
|
||||
.replace(/_{.*?}_/g, "_")]: historySnapshotFnsGenerator(functionConfig),
|
||||
};
|
||||
@@ -1,33 +0,0 @@
|
||||
// export { triggerCloudBuild, cloudBuildUpdates } from "./buildTriggers"; // a callable used for triggering cloudbuild to build and deploy configurable cloud functions
|
||||
// export {
|
||||
// scheduledFirestoreBackup, // callableFirestoreBackup
|
||||
// } from "./backup";
|
||||
// import * as callableFns from "./callable";
|
||||
|
||||
// export const callable = callableFns;
|
||||
|
||||
// // all the cloud functions bellow are deployed using the triggerCloudBuild callable function
|
||||
// // these functions are designed to be built and deployed based on the configuration passed through the callable
|
||||
|
||||
// export { FT_aggregates } from "./aggregates";
|
||||
// export { FT_subTableStats } from "./subTableStats";
|
||||
|
||||
// export { actionScript } from "./actionScript";
|
||||
|
||||
// export { webhook } from "./webhooks";
|
||||
|
||||
// export { FT_snapshotSync } from "./snapshotSync";
|
||||
|
||||
// export { FT_compressedThumbnail } from "./compressedThumbnail";
|
||||
|
||||
export {getAlgoliaSearchKey} from './algoliaSearchKey'
|
||||
|
||||
//deprecated, updated implementation moved to FT_build folder and used within sparks table functions
|
||||
// export { FT_derivatives } from "./derivatives";
|
||||
// export { FT_algolia } from "./algolia";
|
||||
// export { FT_email } from "./emailOnTrigger";
|
||||
// export { FT_slack } from "./slackOnTrigger";
|
||||
// export { FT_sync } from "./collectionSync";
|
||||
// export { FT_spark } from "./sparks";
|
||||
// export { FT_history } from "./history";
|
||||
// export { slackBotMessageOnCreate } from "./slackOnTrigger/trigger";
|
||||
@@ -1,111 +0,0 @@
|
||||
import { firestore } from "firebase-functions";
|
||||
import { hasRequiredFields, serverTimestamp, asyncForEach } from "../utils";
|
||||
import _config from "../functionConfig"; // generated using generateConfig.ts
|
||||
import { db } from "../config";
|
||||
const functionConfig: any = _config;
|
||||
type SlackOnTriggerConfig = {
|
||||
collectionPath: string;
|
||||
onCreate: Boolean;
|
||||
onUpdate: Boolean;
|
||||
onDelete: Boolean;
|
||||
requiredFields: string[];
|
||||
messageDocGenerator: (
|
||||
snapshot:
|
||||
| firestore.DocumentSnapshot
|
||||
| {
|
||||
before: firestore.DocumentSnapshot;
|
||||
after: firestore.DocumentSnapshot;
|
||||
}
|
||||
// db: FirebaseFirestore.Firestore
|
||||
) => Boolean | any;
|
||||
};
|
||||
const slackOnCreate = (config: SlackOnTriggerConfig) =>
|
||||
firestore
|
||||
.document(`${config.collectionPath}/{docId}`)
|
||||
.onCreate(async (snapshot) => {
|
||||
try {
|
||||
const snapshotData = snapshot.data();
|
||||
if (!snapshotData) throw Error("no snapshot data");
|
||||
const hasAllRequiredFields = hasRequiredFields(
|
||||
config.requiredFields,
|
||||
snapshotData
|
||||
);
|
||||
if (hasAllRequiredFields) {
|
||||
const messageDoc = await config.messageDocGenerator(snapshot);
|
||||
if (messageDoc && typeof messageDoc === "object") {
|
||||
await db
|
||||
.collection("slackBotMessages")
|
||||
.add({ createdAt: serverTimestamp(), ...messageDoc });
|
||||
return true;
|
||||
} else {
|
||||
console.log("message is not sent");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
console.log("requirements were not met");
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(JSON.stringify(error.response.body));
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
const slackOnUpdate = (config: SlackOnTriggerConfig) =>
|
||||
firestore
|
||||
.document(`${config.collectionPath}/{docId}`)
|
||||
.onUpdate(async (change) => {
|
||||
try {
|
||||
const beforeData = change.before.data();
|
||||
const afterData = change.after.data();
|
||||
if (!beforeData || !afterData) throw Error("no data found in snapshot");
|
||||
const hasAllRequiredFields = hasRequiredFields(
|
||||
config.requiredFields,
|
||||
afterData
|
||||
);
|
||||
if (hasAllRequiredFields) {
|
||||
const messageDoc = await config.messageDocGenerator(change);
|
||||
console.log({ messageDoc });
|
||||
if (
|
||||
(messageDoc && typeof messageDoc === "object") ||
|
||||
Array.isArray(messageDoc)
|
||||
) {
|
||||
console.log("creating slack message doc");
|
||||
if (Array.isArray(messageDoc)) {
|
||||
await asyncForEach(messageDoc, async (message) => {
|
||||
await db
|
||||
.collection("slackBotMessages")
|
||||
.add({ createdAt: serverTimestamp(), ...message });
|
||||
});
|
||||
} else {
|
||||
await db
|
||||
.collection("slackBotMessages")
|
||||
.add({ createdAt: serverTimestamp(), ...messageDoc });
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
console.log("message is not sent");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
console.log("requirements were not met");
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(error);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
const slackOnTriggerFns = (config: SlackOnTriggerConfig) =>
|
||||
Object.entries({
|
||||
onCreate: config.onCreate ? slackOnCreate(config) : null,
|
||||
onUpdate: config.onUpdate ? slackOnUpdate(config) : null,
|
||||
}).reduce((a, [k, v]) => (v === null ? a : { ...a, [k]: v }), {});
|
||||
|
||||
export const FT_slack = {
|
||||
[`${`${functionConfig.collectionPath}`
|
||||
.replace(/\//g, "_")
|
||||
.replace(/_{.*?}_/g, "_")}`]: slackOnTriggerFns(functionConfig),
|
||||
};
|
||||
@@ -1,103 +0,0 @@
|
||||
import { firestore } from "firebase-functions";
|
||||
|
||||
import { env } from "../config";
|
||||
import { WebClient } from "@slack/web-api";
|
||||
import { asyncForEach, serverTimestamp } from "../utils";
|
||||
// Initialize
|
||||
const web = new WebClient(env.slackbot ? env.slackbot.token : "NEEDS_CONFIG");
|
||||
|
||||
const messageByChannel = async ({
|
||||
text,
|
||||
channel,
|
||||
blocks,
|
||||
attachments,
|
||||
}: {
|
||||
channel: string;
|
||||
text: string;
|
||||
blocks: any[];
|
||||
attachments: any[];
|
||||
}) =>
|
||||
await web.chat.postMessage({
|
||||
link_names: true,
|
||||
text,
|
||||
channel,
|
||||
blocks,
|
||||
attachments,
|
||||
});
|
||||
const messageByEmail = async ({
|
||||
email,
|
||||
text,
|
||||
blocks,
|
||||
attachments,
|
||||
}: {
|
||||
email: string;
|
||||
text: string;
|
||||
blocks: any[];
|
||||
attachments: any[];
|
||||
}) => {
|
||||
try {
|
||||
const user = await web.users.lookupByEmail({ email });
|
||||
if (user.ok) {
|
||||
const channel = (user as any).user.id as string;
|
||||
return await messageByChannel({
|
||||
text,
|
||||
blocks,
|
||||
attachments,
|
||||
channel,
|
||||
});
|
||||
} else {
|
||||
return await false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`${error} maybe${email} is not on slack`);
|
||||
console.log(`${error}`);
|
||||
return await false;
|
||||
}
|
||||
};
|
||||
|
||||
export const slackBotMessageOnCreate = firestore
|
||||
.document(`slackBotMessages/{docId}`)
|
||||
.onCreate(async (snapshot) => {
|
||||
const docData = snapshot.data();
|
||||
if (!docData) {
|
||||
return snapshot.ref.update({
|
||||
delivered: false,
|
||||
error: "undefined doc",
|
||||
});
|
||||
}
|
||||
try {
|
||||
const channels = docData.channel ? [docData.channel] : docData.channels;
|
||||
const emails = docData.email ? [docData.email] : docData.emails;
|
||||
if (channels) {
|
||||
await asyncForEach(channels, async (channel: string) => {
|
||||
await messageByChannel({
|
||||
text: docData.text,
|
||||
blocks: docData.blocks,
|
||||
attachments: docData.attachments,
|
||||
channel,
|
||||
});
|
||||
});
|
||||
} else if (emails) {
|
||||
await asyncForEach(emails, async (email: string) => {
|
||||
await messageByEmail({
|
||||
text: docData.text,
|
||||
blocks: docData.blocks ?? [],
|
||||
attachments: docData.attachments ?? [],
|
||||
email,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return snapshot.ref.update({
|
||||
delivered: true,
|
||||
updatedAt: serverTimestamp(),
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return snapshot.ref.update({
|
||||
delivered: false,
|
||||
updatedAt: serverTimestamp(),
|
||||
error: JSON.stringify(error),
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,205 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
|
||||
import { db } from "../config";
|
||||
|
||||
import * as _ from "lodash";
|
||||
import { replacer, identifyTriggerType } from "../utils";
|
||||
|
||||
import Config from "../functionConfig"; // generated using generateConfig.ts
|
||||
const functionConfig: any = Config;
|
||||
|
||||
enum TargetTypes {
|
||||
subCollection = "subCollection",
|
||||
document = "document",
|
||||
}
|
||||
/**
|
||||
* returns object with only keys included in fieldsToSync
|
||||
* @param docData
|
||||
*/
|
||||
const docReducer = (docData: FirebaseFirestore.DocumentData) => (
|
||||
acc: any,
|
||||
curr: string
|
||||
) => {
|
||||
if (docData[curr] !== undefined && docData[curr] !== null) {
|
||||
return { ...acc, [curr]: docData[curr] };
|
||||
} else return acc;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param targetPath
|
||||
* @param fieldsToSync
|
||||
*/
|
||||
const syncSubCollection = async (
|
||||
targetPath: string,
|
||||
snapshotField: string,
|
||||
syncData: any,
|
||||
snapshot: FirebaseFirestore.DocumentSnapshot<FirebaseFirestore.DocumentData>
|
||||
) => {
|
||||
const targetDocs = await db.collection(targetPath).get();
|
||||
if (targetDocs.empty) return false;
|
||||
for (const doc of targetDocs.docs) {
|
||||
await doc.ref.update({
|
||||
[snapshotField]: {
|
||||
docPath: snapshot.ref.path,
|
||||
snapshot: syncData,
|
||||
},
|
||||
});
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const syncDocSnapshot = async (
|
||||
targetPath,
|
||||
isArray,
|
||||
snapshotField,
|
||||
newSnapshotData,
|
||||
snapshot
|
||||
) => {
|
||||
console.log({
|
||||
targetPath,
|
||||
isArray,
|
||||
snapshotField,
|
||||
});
|
||||
const targetRef = db.doc(targetPath);
|
||||
const targetSnapshot = await targetRef.get();
|
||||
const targetData = targetSnapshot.data();
|
||||
if (!targetData) {
|
||||
console.warn("target does not exist");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isArray) {
|
||||
const oldSnapshotsArray = targetData[snapshotField];
|
||||
if (!oldSnapshotsArray) {
|
||||
return targetRef.update({
|
||||
[snapshotField]: [
|
||||
{ docPath: snapshot.ref.path, snapshot: newSnapshotData },
|
||||
],
|
||||
});
|
||||
} else {
|
||||
const snapshotDocPath = snapshot.ref.path;
|
||||
const oldSnapshot = _.find(oldSnapshotsArray, {
|
||||
docPath: snapshotDocPath,
|
||||
});
|
||||
if (oldSnapshot) {
|
||||
return targetRef.update({
|
||||
[snapshotField]: oldSnapshotsArray.map(
|
||||
(item: { docPath: string; snapshot: any }) => {
|
||||
if (item.docPath === snapshotDocPath) {
|
||||
return {
|
||||
...oldSnapshot,
|
||||
docPath: snapshotDocPath,
|
||||
snapshot: newSnapshotData,
|
||||
};
|
||||
} else return item;
|
||||
}
|
||||
),
|
||||
});
|
||||
} else {
|
||||
return targetRef.update({
|
||||
[snapshotField]: [
|
||||
...oldSnapshotsArray,
|
||||
{ docPath: snapshotDocPath, snapshot: newSnapshotData },
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return targetRef.update({
|
||||
[snapshotField]: {
|
||||
...targetData[snapshotField],
|
||||
snapshot: newSnapshotData,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* onUpdate change to snapshot adapter
|
||||
* @param targetCollection
|
||||
* @param fieldsToSync
|
||||
*/
|
||||
const syncDocOnWrite = (config: {
|
||||
target: string;
|
||||
snapshotField: string;
|
||||
targetType: TargetTypes;
|
||||
fieldsToSync: string[];
|
||||
isArray: boolean;
|
||||
}) => (snapshot: functions.Change<FirebaseFirestore.DocumentSnapshot>) => {
|
||||
const { fieldsToSync, target, snapshotField, targetType, isArray } = config;
|
||||
|
||||
const afterDocData = snapshot.after.data();
|
||||
const beforeDocData = snapshot.before.data();
|
||||
|
||||
const triggerType = identifyTriggerType(beforeDocData, afterDocData);
|
||||
|
||||
const afterData = fieldsToSync.reduce(docReducer(afterDocData ?? {}), {});
|
||||
const beforeData = fieldsToSync.reduce(docReducer(beforeDocData ?? {}), {});
|
||||
const hasChanged = !_.isEqual(afterData, beforeData);
|
||||
console.log("nothing important changed");
|
||||
if (Object.keys(afterData).length === 0) return false; // returns if theres nothing to sync
|
||||
|
||||
const targetPath = target.replace(
|
||||
/\{\{(.*?)\}\}/g,
|
||||
replacer({ ...snapshot.after.data(), id: snapshot.after.id })
|
||||
);
|
||||
console.log({ targetPath });
|
||||
if (targetPath === "") {
|
||||
console.log("unspecified target");
|
||||
return false;
|
||||
}
|
||||
console.log({ hasChanged, targetType });
|
||||
if (hasChanged) {
|
||||
switch (targetType) {
|
||||
case TargetTypes.subCollection:
|
||||
return triggerType === "update"
|
||||
? syncSubCollection(
|
||||
targetPath,
|
||||
snapshotField,
|
||||
{ ...afterData, objectID: snapshot.after.ref.id },
|
||||
snapshot.after
|
||||
)
|
||||
: false;
|
||||
|
||||
case TargetTypes.document:
|
||||
return triggerType !== "delete"
|
||||
? syncDocSnapshot(
|
||||
targetPath,
|
||||
isArray,
|
||||
snapshotField,
|
||||
{ ...afterData, objectID: snapshot.after.ref.id },
|
||||
snapshot.after
|
||||
)
|
||||
: false;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
console.warn("no change detected");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* returns 2 different trigger functions (onCreate,onUpdate) in an object
|
||||
* @param config configuration object
|
||||
*/
|
||||
const snapshotSyncFnsGenerator = (config) =>
|
||||
functions.firestore
|
||||
.document(`${config.source}/{docId}`)
|
||||
.onWrite(syncDocOnWrite(config));
|
||||
|
||||
//export default snapshotSyncFnsGenerator;
|
||||
|
||||
export const FT_snapshotSync = functionConfig.fnName
|
||||
? { [functionConfig.fnName]: snapshotSyncFnsGenerator(functionConfig) }
|
||||
: {
|
||||
[`${`${`${functionConfig.source}`
|
||||
.replace(/\//g, "_")
|
||||
.replace(/_{.*?}_/g, "_")}`}2${`${`${functionConfig.target}`
|
||||
.replace(/\//g, "_")
|
||||
.replace(/_{.*?}_/g, "_")}`}`]: snapshotSyncFnsGenerator(
|
||||
functionConfig
|
||||
),
|
||||
};
|
||||
@@ -1,37 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
import * as admin from "firebase-admin";
|
||||
|
||||
import { collectionPath } from "./functionConfig"; // generated using generateConfig.ts
|
||||
const increment = admin.firestore.FieldValue.increment(1);
|
||||
const decrement = admin.firestore.FieldValue.increment(-1);
|
||||
const docCreated = (
|
||||
snapshot: functions.firestore.DocumentSnapshot,
|
||||
context: functions.EventContext
|
||||
) => {
|
||||
const { subCollectionId } = context.params;
|
||||
return snapshot.ref.parent.parent?.update({
|
||||
[`${subCollectionId}.count`]: increment,
|
||||
});
|
||||
};
|
||||
|
||||
const docDelete = (
|
||||
snapshot: functions.firestore.DocumentSnapshot,
|
||||
context: functions.EventContext
|
||||
) => {
|
||||
const { subCollectionId } = context.params;
|
||||
return snapshot.ref.parent.parent?.update({
|
||||
[subCollectionId]: decrement,
|
||||
});
|
||||
};
|
||||
const subTableFnsGenerator = {
|
||||
onCreate: functions.firestore
|
||||
.document(`${collectionPath}/{parentId}/{subCollectionId}/{docId}`)
|
||||
.onCreate(docCreated),
|
||||
onDelete: functions.firestore
|
||||
.document(`${collectionPath}/{parentId}/{subCollectionId}/{docId}`)
|
||||
.onDelete(docDelete),
|
||||
};
|
||||
|
||||
export const FT_subTableStats = {
|
||||
[collectionPath]: { ...subTableFnsGenerator },
|
||||
};
|
||||
@@ -1,17 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
|
||||
export const hasAnyRole = (
|
||||
authorizedRoles: string[],
|
||||
context: functions.https.CallableContext
|
||||
) => {
|
||||
if (!context.auth || !context.auth.token.roles) return false;
|
||||
const userRoles = context.auth.token.roles as string[];
|
||||
const authorization = authorizedRoles.reduce(
|
||||
(authorized: boolean, role: string) => {
|
||||
if (userRoles.includes(role)) return true;
|
||||
else return authorized;
|
||||
},
|
||||
false
|
||||
);
|
||||
return authorization;
|
||||
};
|
||||
@@ -1,6 +0,0 @@
|
||||
const sgMail = require("@sendgrid/mail");
|
||||
import { env } from "../config";
|
||||
sgMail.setSubstitutionWrappers("{{", "}}");
|
||||
if (env.send_grid) sgMail.setApiKey(env.send_grid.key);
|
||||
|
||||
export const sendEmail = (msg: any) => sgMail.send(msg);
|
||||
@@ -1,41 +0,0 @@
|
||||
import * as admin from "firebase-admin";
|
||||
import * as _ from "lodash";
|
||||
export const serverTimestamp = admin.firestore.FieldValue.serverTimestamp;
|
||||
import { sendEmail } from "./email";
|
||||
import { hasAnyRole } from "./auth";
|
||||
|
||||
const characters =
|
||||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
export function generateId(length) {
|
||||
let result = "";
|
||||
const charactersLength = characters.length;
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export default { generateId, sendEmail, serverTimestamp, hasAnyRole };
|
||||
export const replacer = (data: any) => (m: string, key: string) => {
|
||||
const objKey = key.split(":")[0];
|
||||
const defaultValue = key.split(":")[1] || "";
|
||||
return _.get(data, objKey, defaultValue);
|
||||
};
|
||||
|
||||
export const hasRequiredFields = (requiredFields: string[], data: any) =>
|
||||
requiredFields.reduce((acc: boolean, currField: string) => {
|
||||
if (data[currField] === undefined || data[currField] === null) return false;
|
||||
else return acc;
|
||||
}, true);
|
||||
export async function asyncForEach(array: any[], callback: Function) {
|
||||
for (let index = 0; index < array.length; index++) {
|
||||
await callback(array[index], index, array);
|
||||
}
|
||||
}
|
||||
|
||||
export const identifyTriggerType = (beforeData, afterData) =>
|
||||
Boolean(beforeData) && Boolean(afterData)
|
||||
? "update"
|
||||
: Boolean(afterData)
|
||||
? "create"
|
||||
: "delete";
|
||||
@@ -1,84 +0,0 @@
|
||||
import { db } from "../config";
|
||||
import * as functions from "firebase-functions";
|
||||
// const fetch = require("node-fetch");
|
||||
|
||||
//import * as crypto from "crypto";
|
||||
|
||||
//const TYPEFORM_SECRET = "testsecret123";
|
||||
//const verifySignature = function (secret, receivedSignature, payload) {
|
||||
// const hash = crypto
|
||||
// .createHmac("sha256", secret)
|
||||
// .update(payload)
|
||||
// .digest("base64");
|
||||
// console.log(receivedSignature, `sha256=${hash}`);
|
||||
// return receivedSignature === `sha256=${hash}`;
|
||||
// };
|
||||
|
||||
//const file = bucket.file('path/to/image.jpg');
|
||||
|
||||
const typeformParser = (body) => ({
|
||||
_ft_createdAt: body.form_response.submitted_at,
|
||||
...body.form_response.hidden,
|
||||
...body.form_response.answers.reduce((accRow, currAnswer) => {
|
||||
switch (currAnswer.type) {
|
||||
case "date":
|
||||
return {
|
||||
...accRow,
|
||||
[currAnswer.field.ref]: new Date(currAnswer[currAnswer.type]),
|
||||
};
|
||||
case "choice":
|
||||
return {
|
||||
...accRow,
|
||||
[currAnswer.field.ref]: currAnswer[currAnswer.type].label,
|
||||
};
|
||||
case "choices":
|
||||
return {
|
||||
...accRow,
|
||||
[currAnswer.field.ref]: currAnswer[currAnswer.type].labels,
|
||||
};
|
||||
case "file_url":
|
||||
default:
|
||||
return {
|
||||
...accRow,
|
||||
[currAnswer.field.ref]: currAnswer[currAnswer.type],
|
||||
};
|
||||
}
|
||||
}, {}),
|
||||
});
|
||||
|
||||
export const webhook = functions.https.onRequest(async (req, res) => {
|
||||
const { body, url, query } = req;
|
||||
console.log(JSON.stringify({ body, url, query }));
|
||||
const schemaDocPath = `_FIRETABLE_/settings/schema/${decodeURIComponent(
|
||||
query.tablePath as string
|
||||
)}`;
|
||||
const schemaDoc = await db.doc(schemaDocPath).get();
|
||||
const schemaDocData = schemaDoc.data();
|
||||
if (!schemaDocData) {
|
||||
res.sendStatus(404);
|
||||
}
|
||||
if (!schemaDocData?.webhooks.enabled) {
|
||||
res.sendStatus(401);
|
||||
}
|
||||
|
||||
if (query.type === "CUSTOM") {
|
||||
console.log({ schemaDocData });
|
||||
} else if (query.type === "TYPE_FORM") {
|
||||
// const receivedSignature = req.header("Typeform-Signature");
|
||||
const secret = schemaDocData?.webhooks.secret;
|
||||
// const isValidSignature = verifySignature(
|
||||
// TYPEFORM_SECRET,
|
||||
// receivedSignature,
|
||||
// req.body.toString()
|
||||
// );
|
||||
if (req.query.secret === secret) {
|
||||
const newRow = typeformParser(req.body);
|
||||
await db
|
||||
.collection(decodeURIComponent(req.query.tablePath as string))
|
||||
.add(newRow);
|
||||
} else {
|
||||
res.sendStatus(403);
|
||||
}
|
||||
}
|
||||
res.sendStatus(200);
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedLocals": true,
|
||||
"outDir": "lib",
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"noImplicitAny": false,
|
||||
"resolveJsonModule": true,
|
||||
"target": "es2017"
|
||||
},
|
||||
"compileOnSave": true,
|
||||
"include": ["src", "generateConfig.ts"]
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
{
|
||||
"rules": {
|
||||
// -- Strict errors --
|
||||
// These lint rules are likely always a good idea.
|
||||
|
||||
// Force function overloads to be declared together. This ensures readers understand APIs.
|
||||
"adjacent-overload-signatures": true,
|
||||
|
||||
// Do not allow the subtle/obscure comma operator.
|
||||
"ban-comma-operator": true,
|
||||
|
||||
// Do not allow internal modules or namespaces . These are deprecated in favor of ES6 modules.
|
||||
"no-namespace": true,
|
||||
|
||||
// Do not allow parameters to be reassigned. To avoid bugs, developers should instead assign new values to new vars.
|
||||
"no-parameter-reassignment": true,
|
||||
|
||||
// Force the use of ES6-style imports instead of /// <reference path=> imports.
|
||||
"no-reference": true,
|
||||
|
||||
// Do not allow type assertions that do nothing. This is a big warning that the developer may not understand the
|
||||
// code currently being edited (they may be incorrectly handling a different type case that does not exist).
|
||||
"no-unnecessary-type-assertion": true,
|
||||
|
||||
// Disallow nonsensical label usage.
|
||||
"label-position": true,
|
||||
|
||||
// Disallows the (often typo) syntax if (var1 = var2). Replace with if (var2) { var1 = var2 }.
|
||||
"no-conditional-assignment": true,
|
||||
|
||||
// Disallows constructors for primitive types (e.g. new Number('123'), though Number('123') is still allowed).
|
||||
"no-construct": true,
|
||||
|
||||
// Do not allow super() to be called twice in a constructor.
|
||||
"no-duplicate-super": true,
|
||||
|
||||
// Do not allow the same case to appear more than once in a switch block.
|
||||
"no-duplicate-switch-case": true,
|
||||
|
||||
// Do not allow a variable to be declared more than once in the same block. Consider function parameters in this
|
||||
// rule.
|
||||
"no-duplicate-variable": [true, "check-parameters"],
|
||||
|
||||
// Disallows a variable definition in an inner scope from shadowing a variable in an outer scope. Developers should
|
||||
// instead use a separate variable name.
|
||||
"no-shadowed-variable": true,
|
||||
|
||||
// Empty blocks are almost never needed. Allow the one general exception: empty catch blocks.
|
||||
"no-empty": [true, "allow-empty-catch"],
|
||||
|
||||
// Functions must either be handled directly (e.g. with a catch() handler) or returned to another function.
|
||||
// This is a major source of errors in Cloud Functions and the team strongly recommends leaving this rule on.
|
||||
"no-floating-promises": true,
|
||||
|
||||
// Do not allow any imports for modules that are not in package.json. These will almost certainly fail when
|
||||
// deployed.
|
||||
"no-implicit-dependencies": true,
|
||||
|
||||
// The 'this' keyword can only be used inside of classes.
|
||||
"no-invalid-this": true,
|
||||
|
||||
// Do not allow strings to be thrown because they will not include stack traces. Throw Errors instead.
|
||||
"no-string-throw": true,
|
||||
|
||||
// Disallow control flow statements, such as return, continue, break, and throw in finally blocks.
|
||||
"no-unsafe-finally": true,
|
||||
|
||||
// Do not allow variables to be used before they are declared.
|
||||
"no-use-before-declare": true,
|
||||
|
||||
// Expressions must always return a value. Avoids common errors like const myValue = functionReturningVoid();
|
||||
"no-void-expression": [true, "ignore-arrow-function-shorthand"],
|
||||
|
||||
// Disallow duplicate imports in the same file.
|
||||
"no-duplicate-imports": true,
|
||||
|
||||
// -- Strong Warnings --
|
||||
// These rules should almost never be needed, but may be included due to legacy code.
|
||||
// They are left as a warning to avoid frustration with blocked deploys when the developer
|
||||
// understand the warning and wants to deploy anyway.
|
||||
|
||||
// Warn when an empty interface is defined. These are generally not useful.
|
||||
"no-empty-interface": { "severity": "warning" },
|
||||
|
||||
// Warn when an import will have side effects.
|
||||
"no-import-side-effect": { "severity": "warning" },
|
||||
|
||||
// Warn when variables are defined with var. Var has subtle meaning that can lead to bugs. Strongly prefer const for
|
||||
// most values and let for values that will change.
|
||||
"no-var-keyword": { "severity": "warning" },
|
||||
|
||||
// Prefer === and !== over == and !=. The latter operators support overloads that are often accidental.
|
||||
"triple-equals": { "severity": "warning" },
|
||||
|
||||
// Warn when using deprecated APIs.
|
||||
"deprecation": { "severity": "warning" },
|
||||
|
||||
// -- Light Warnings --
|
||||
// These rules are intended to help developers use better style. Simpler code has fewer bugs. These would be "info"
|
||||
// if TSLint supported such a level.
|
||||
|
||||
// prefer for( ... of ... ) to an index loop when the index is only used to fetch an object from an array.
|
||||
// (Even better: check out utils like .map if transforming an array!)
|
||||
"prefer-for-of": { "severity": "warning" },
|
||||
|
||||
// Warns if function overloads could be unified into a single function with optional or rest parameters.
|
||||
"unified-signatures": { "severity": "warning" },
|
||||
|
||||
// Prefer const for values that will not change. This better documents code.
|
||||
"prefer-const": { "severity": "warning" },
|
||||
|
||||
// Multi-line object literals and function calls should have a trailing comma. This helps avoid merge conflicts.
|
||||
"trailing-comma": { "severity": "warning" }
|
||||
},
|
||||
"linterOptions": {
|
||||
"exclude": ["./generator/templates/**"]
|
||||
},
|
||||
"defaultSeverity": "error"
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
// Initialize Firebase Admin
|
||||
import * as admin from "firebase-admin";
|
||||
// Initialize Firebase Admin
|
||||
const serverTimestamp = admin.firestore.FieldValue.serverTimestamp;
|
||||
admin.initializeApp();
|
||||
const db = admin.firestore();
|
||||
|
||||
const main = async (deployRequestPath: string, currentBuild) => {
|
||||
await db.doc(deployRequestPath).update({
|
||||
deployedAt: serverTimestamp(),
|
||||
currentBuild: currentBuild ?? "",
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
main(process.argv[2], process.argv[3])
|
||||
.catch((err) => console.log(err))
|
||||
.then(() => console.log("this will succeed"))
|
||||
.catch(() => "obligatory catch");
|
||||
@@ -2,7 +2,6 @@ steps:
|
||||
- name: node:10.17.0
|
||||
entrypoint: yarn
|
||||
args: ["install"]
|
||||
dir: "www"
|
||||
- name: node:10.17.0
|
||||
entrypoint: yarn
|
||||
args:
|
||||
@@ -11,11 +10,9 @@ steps:
|
||||
- "${_FIREBASE_WEB_API_KEY}"
|
||||
- "${_ALGOLIA_APP_ID}"
|
||||
- "${_ALGOLIA_APP_KEY}"
|
||||
dir: "www"
|
||||
- name: node:10.17.0
|
||||
entrypoint: yarn
|
||||
args: ["build"]
|
||||
dir: "www"
|
||||
- name: node:10.17.0
|
||||
entrypoint: yarn
|
||||
args:
|
||||
@@ -23,7 +20,6 @@ steps:
|
||||
- "${_HOSTING_TARGET}"
|
||||
- --project
|
||||
- "${_PROJECT_ID}"
|
||||
dir: "www"
|
||||
- name: node:10.17.0
|
||||
entrypoint: yarn
|
||||
args:
|
||||
@@ -35,7 +31,6 @@ steps:
|
||||
- "${_FIREBASE_TOKEN}"
|
||||
- --only
|
||||
- hosting
|
||||
dir: "www"
|
||||
substitutions:
|
||||
_PROJECT_ID: "project-id" # default value
|
||||
options:
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
steps:
|
||||
# - name: "gcr.io/kaniko-project/executor:latest"
|
||||
# args:
|
||||
# - --destination=gcr.io/$PROJECT_ID/image
|
||||
# - --cache=true
|
||||
# - --cache-ttl=24h
|
||||
- name: node:10.15.1
|
||||
entrypoint: yarn
|
||||
args: ["install"]
|
||||
dir: "cloud_functions/functions"
|
||||
- name: node:10.15.1
|
||||
entrypoint: yarn
|
||||
args:
|
||||
- "generateConfig"
|
||||
- "${_FUNCTIONS_GROUP}"
|
||||
- "${_FUNCTION_CONFIG}"
|
||||
dir: "cloud_functions/functions"
|
||||
- name: node:10.15.1
|
||||
entrypoint: yarn
|
||||
args:
|
||||
- "deployFT"
|
||||
- "--project"
|
||||
- "${_PROJECT_ID}"
|
||||
- "--token"
|
||||
- "${_FIREBASE_TOKEN}"
|
||||
- "--only"
|
||||
- "functions:${_FUNCTIONS_GROUP}"
|
||||
dir: "cloud_functions/functions"
|
||||
# - name: gcr.io/cloud-builders/gcloud
|
||||
# args:
|
||||
# - functions
|
||||
# - deploy
|
||||
# - "${_FUNCTIONS_GROUP}"
|
||||
# dir: "cloud_functions/functions"
|
||||
- name: node:10.15.1
|
||||
entrypoint: yarn
|
||||
args:
|
||||
- "updateStatus"
|
||||
- "${_REQUEST_DOC_PATH}"
|
||||
- "${_FUNCTION_CONFIG}"
|
||||
dir: "cloud_functions/functions"
|
||||
|
||||
substitutions:
|
||||
_PROJECT_ID: "project-id" # default value
|
||||
_FUNCTIONS_GROUP: "exportTable" # default value
|
||||
options:
|
||||
machineType: "N1_HIGHCPU_8"
|
||||
30
craco.config.js
Normal file
@@ -0,0 +1,30 @@
|
||||
const CracoAlias = require("craco-alias");
|
||||
const CracoSwcPlugin = require("craco-swc");
|
||||
|
||||
module.exports = {
|
||||
plugins: [
|
||||
{
|
||||
plugin: CracoAlias,
|
||||
options: {
|
||||
source: "tsconfig",
|
||||
baseUrl: "./src",
|
||||
tsConfigPath: "./tsconfig.extend.json",
|
||||
},
|
||||
},
|
||||
{
|
||||
plugin: CracoSwcPlugin,
|
||||
options: {
|
||||
swcLoaderOptions: {
|
||||
jsc: {
|
||||
target: "es2019",
|
||||
transform: {
|
||||
react: {
|
||||
runtime: "automatic",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
1
e2e/.gitignore
vendored
@@ -1 +0,0 @@
|
||||
firebase-credentials.json
|
||||
20
e2e/auth.ts
@@ -1,20 +0,0 @@
|
||||
import { auth } from "./credentials";
|
||||
|
||||
export const authenticateUser = async (page, email = "shams@antler.co") => {
|
||||
const user = await auth.getUserByEmail(email);
|
||||
const jwt = await auth.createCustomToken(user.uid);
|
||||
// Go to http://localhost:3000/jwtAuth
|
||||
await page.goto("http://localhost:3000/jwtAuth");
|
||||
|
||||
// Click input[name="JWT"]
|
||||
await page.click('input[name="JWT"]');
|
||||
|
||||
// Fill input[name="JWT"]
|
||||
await page.fill('input[name="JWT"]', jwt);
|
||||
|
||||
// Click text="Sign in"
|
||||
return await Promise.all([
|
||||
page.waitForNavigation(/*{ url: 'http://localhost:3000/' }*/),
|
||||
page.click('text="Sign in"'),
|
||||
]);
|
||||
};
|
||||
@@ -1,12 +0,0 @@
|
||||
// Initialize Firebase Admin
|
||||
import * as admin from "firebase-admin";
|
||||
// Initialize Firebase Admin
|
||||
const serverTimestamp = admin.firestore.FieldValue.serverTimestamp;
|
||||
const serviceAccount = require("./firebase-credentials.json");
|
||||
|
||||
admin.initializeApp({
|
||||
credential: admin.credential.cert(serviceAccount),
|
||||
databaseURL: `https://${serviceAccount.project_id}.firebaseio.com`,
|
||||
});
|
||||
export const db = admin.firestore();
|
||||
export const auth = admin.auth();
|
||||
123
e2e/index.ts
@@ -1,123 +0,0 @@
|
||||
import { chromium } from "playwright";
|
||||
import { authenticateUser } from "./auth";
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
headless: false,
|
||||
});
|
||||
const context = await browser.newContext();
|
||||
|
||||
// Open new page
|
||||
const page = await context.newPage();
|
||||
|
||||
await authenticateUser(page);
|
||||
|
||||
await page.goto("http://localhost:3000/table/test");
|
||||
// Click text="Add Column"
|
||||
await page.click(
|
||||
"//div[starts-with(normalize-space(.), 'EdwardKnightEd has had a multi decade career in European banking and capital mar') and normalize-space(@role)='row']/div[2][normalize-space(@role)='gridcell']/div/div/div/div[normalize-space(@role)='button']"
|
||||
);
|
||||
|
||||
// Click //li[normalize-space(.)='LON3' and normalize-space(@role)='option']/*[local-name()="svg"]
|
||||
await page.click(
|
||||
"//li[normalize-space(.)='LON3' and normalize-space(@role)='option']/*[local-name()=\"svg\"]"
|
||||
);
|
||||
|
||||
// Click //div[normalize-space(.)='Beijing' and normalize-space(@role)='button']
|
||||
await page.click(
|
||||
"//div[normalize-space(.)='Beijing' and normalize-space(@role)='button']"
|
||||
);
|
||||
|
||||
// Click //li[normalize-space(.)='India' and normalize-space(@role)='option']/*[local-name()="svg"]
|
||||
await page.click(
|
||||
"//li[normalize-space(.)='India' and normalize-space(@role)='option']/*[local-name()=\"svg\"]"
|
||||
);
|
||||
|
||||
// Click //li[normalize-space(.)='Oslo' and normalize-space(@role)='option']
|
||||
await page.click(
|
||||
"//li[normalize-space(.)='Oslo' and normalize-space(@role)='option']"
|
||||
);
|
||||
|
||||
// Click text="Add Row"
|
||||
await page.click('text="Add Row"');
|
||||
|
||||
// Click //button[normalize-space(.)='Hide']
|
||||
await page.click("//button[normalize-space(.)='Hide']");
|
||||
|
||||
// Click li[role="option"] >> text="Department"
|
||||
await page.click('li[role="option"] >> text="Department"');
|
||||
|
||||
// Click li[role="option"] >> text="Location"
|
||||
await page.click('li[role="option"] >> text="Location"');
|
||||
|
||||
// Click li[role="option"] >> text="Designation"
|
||||
await page.click('li[role="option"] >> text="Designation"');
|
||||
|
||||
// Click li[role="option"] >> text="Employment Type"
|
||||
await page.click('li[role="option"] >> text="Employment Type"');
|
||||
|
||||
// Click text="Done"
|
||||
await page.click('text="Done"');
|
||||
|
||||
// Click .MuiGrid-root.MuiGrid-item .MuiGrid-root .MuiButtonBase-root .MuiButton-label .MuiButton-startIcon .MuiSvgIcon-root path
|
||||
await page.click(
|
||||
".MuiGrid-root.MuiGrid-item .MuiGrid-root .MuiButtonBase-root .MuiButton-label .MuiButton-startIcon .MuiSvgIcon-root path"
|
||||
);
|
||||
|
||||
// Click //div[normalize-space(.)='Select Column']
|
||||
await page.click("//div[normalize-space(.)='Select Column']");
|
||||
|
||||
// Click //li[normalize-space(.)='Last Name' and normalize-space(@role)='option']
|
||||
await page.click(
|
||||
"//li[normalize-space(.)='Last Name' and normalize-space(@role)='option']"
|
||||
);
|
||||
|
||||
// Click div[role="presentation"] div[role="button"]
|
||||
await page.click('div[role="presentation"] div[role="button"]');
|
||||
|
||||
// Click //li[normalize-space(.)='Employment Type' and normalize-space(@role)='option']
|
||||
await page.click(
|
||||
"//li[normalize-space(.)='Employment Type' and normalize-space(@role)='option']"
|
||||
);
|
||||
|
||||
// Click //div[normalize-space(.)='Select Condition' and normalize-space(@role)='button']
|
||||
await page.click(
|
||||
"//div[normalize-space(.)='Select Condition' and normalize-space(@role)='button']"
|
||||
);
|
||||
|
||||
// Click //li[normalize-space(.)='Equals' and normalize-space(@role)='option']
|
||||
await page.click(
|
||||
"//li[normalize-space(.)='Equals' and normalize-space(@role)='option']"
|
||||
);
|
||||
|
||||
// Click //div[normalize-space(.)='Equals' and normalize-space(@role)='button']
|
||||
await page.click(
|
||||
"//div[normalize-space(.)='Equals' and normalize-space(@role)='button']"
|
||||
);
|
||||
|
||||
// Click //div[normalize-space(.)='Select ConditionEqualsmatches any of' and normalize-space(@role)='presentation']/div[1]
|
||||
await page.click(
|
||||
"//div[normalize-space(.)='Select ConditionEqualsmatches any of' and normalize-space(@role)='presentation']/div[1]"
|
||||
);
|
||||
|
||||
// Click //div[normalize-space(.)='' and normalize-space(@role)='button']
|
||||
await page.click(
|
||||
"//div[normalize-space(.)='' and normalize-space(@role)='button']"
|
||||
);
|
||||
|
||||
// Click //li[normalize-space(.)='Part Time' and normalize-space(@role)='option']/*[local-name()="svg"]
|
||||
await page.click(
|
||||
"//li[normalize-space(.)='Part Time' and normalize-space(@role)='option']/*[local-name()=\"svg\"]"
|
||||
);
|
||||
|
||||
// Click text="Apply"
|
||||
await page.click('text="Apply"');
|
||||
|
||||
// Click //div[normalize-space(.)='employmentType == Part Time' and normalize-space(@role)='button']/*[local-name()="svg"]
|
||||
await page.click(
|
||||
"//div[normalize-space(.)='employmentType == Part Time' and normalize-space(@role)='button']/*[local-name()=\"svg\"]"
|
||||
);
|
||||
|
||||
// ---------------------
|
||||
await context.close();
|
||||
await browser.close();
|
||||
})();
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"devDependencies": {
|
||||
"@types/node": "^14.14.33",
|
||||
"playwright": "^1.9.2",
|
||||
"playwright-cli": "^0.180.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"firebase-admin": "^9.5.0"
|
||||
}
|
||||
}
|
||||
1196
e2e/yarn.lock
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"hosting": {
|
||||
"target": "firetable",
|
||||
"target": "rowy",
|
||||
"public": "build",
|
||||
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
|
||||
"rewrites": [
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"functions": {
|
||||
"predeploy": [
|
||||
"npm --prefix \"$RESOURCE_DIR\" run lint",
|
||||
"npm --prefix \"$RESOURCE_DIR\" run build"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
module.exports = {
|
||||
env: {
|
||||
browser: true,
|
||||
es6: true,
|
||||
node: true,
|
||||
},
|
||||
extends: ["plugin:import/errors", "plugin:import/warnings"],
|
||||
parser: "@typescript-eslint/parser",
|
||||
parserOptions: {
|
||||
project: "tsconfig.json",
|
||||
sourceType: "module",
|
||||
},
|
||||
plugins: ["@typescript-eslint", "import"],
|
||||
rules: {
|
||||
"@typescript-eslint/adjacent-overload-signatures": "error",
|
||||
"@typescript-eslint/no-empty-function": "error",
|
||||
"@typescript-eslint/no-empty-interface": "warn",
|
||||
"@typescript-eslint/no-floating-promises": "error",
|
||||
"@typescript-eslint/no-namespace": "error",
|
||||
"@typescript-eslint/no-unnecessary-type-assertion": "error",
|
||||
"@typescript-eslint/prefer-for-of": "warn",
|
||||
"@typescript-eslint/triple-slash-reference": "error",
|
||||
"@typescript-eslint/unified-signatures": "warn",
|
||||
"comma-dangle": "warn",
|
||||
"constructor-super": "error",
|
||||
eqeqeq: ["warn", "always"],
|
||||
"import/no-deprecated": "warn",
|
||||
"import/no-extraneous-dependencies": "error",
|
||||
"import/no-unassigned-import": "warn",
|
||||
"no-cond-assign": "error",
|
||||
"no-duplicate-case": "error",
|
||||
"no-duplicate-imports": "error",
|
||||
"no-empty": [
|
||||
"error",
|
||||
{
|
||||
allowEmptyCatch: true,
|
||||
},
|
||||
],
|
||||
"no-invalid-this": "error",
|
||||
"no-new-wrappers": "error",
|
||||
"no-param-reassign": "error",
|
||||
"no-redeclare": "error",
|
||||
"no-sequences": "error",
|
||||
"no-shadow": [
|
||||
"error",
|
||||
{
|
||||
hoist: "all",
|
||||
},
|
||||
],
|
||||
"no-throw-literal": "error",
|
||||
"no-unsafe-finally": "error",
|
||||
"no-unused-labels": "error",
|
||||
"no-var": "warn",
|
||||
"no-void": "error",
|
||||
"prefer-const": "warn",
|
||||
},
|
||||
settings: {
|
||||
jsdoc: {
|
||||
tagNamePreference: {
|
||||
returns: "return",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
12
ft_actions/functions/.gitignore
vendored
@@ -1,12 +0,0 @@
|
||||
# Compiled JavaScript files
|
||||
**/*.js
|
||||
**/*.js.map
|
||||
|
||||
# Except the ESLint config file
|
||||
!.eslintrc.js
|
||||
|
||||
# TypeScript v1 declaration files
|
||||
typings/
|
||||
|
||||
# Node.js dependency directory
|
||||
node_modules/
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"name": "functions",
|
||||
"scripts": {
|
||||
"lint": "tslint --project tsconfig.json",
|
||||
"build": "tsc",
|
||||
"serve": "npm run build && firebase serve --only functions",
|
||||
"shell": "npm run build && firebase functions:shell",
|
||||
"start": "npm run shell",
|
||||
"deployFT": "echo 'n\n' | firebase deploy --interactive",
|
||||
"logs": "firebase functions:log"
|
||||
},
|
||||
"engines": {
|
||||
"node": "14"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"dependencies": {
|
||||
"firebase-admin": "^9.11.0",
|
||||
"firebase-functions": "^3.14.1",
|
||||
"lodash": "^4.17.21"
|
||||
},
|
||||
"devDependencies": {
|
||||
"firebase-tools": "^8.7.0",
|
||||
"husky": "^4.2.5",
|
||||
"prettier": "^2.1.1",
|
||||
"pretty-quick": "^3.0.0",
|
||||
"ts-node": "^8.6.2",
|
||||
"tslint": "^6.1.0",
|
||||
"typescript": "^3.2.2"
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {
|
||||
"pre-commit": "pretty-quick --staged"
|
||||
}
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// Initialize Firebase Admin
|
||||
import * as functions from "firebase-functions";
|
||||
import * as admin from "firebase-admin";
|
||||
admin.initializeApp();
|
||||
|
||||
// Initialize Cloud Firestore Database
|
||||
export const db = admin.firestore();
|
||||
// Initialize Auth
|
||||
export const auth = admin.auth();
|
||||
|
||||
const settings = { timestampsInSnapshots: true, ignoreUndefinedProperties: true};
|
||||
db.settings(settings);
|
||||
export const env = functions.config();
|
||||
@@ -1,113 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
import * as _ from "lodash";
|
||||
import { db, auth } from "./firebaseConfig";
|
||||
import * as admin from "firebase-admin";
|
||||
import utilFns from "./utils";
|
||||
type ActionData = {
|
||||
ref: {
|
||||
id: string;
|
||||
path: string;
|
||||
parentId: string;
|
||||
tablePath: string;
|
||||
};
|
||||
schemaDocPath?: string;
|
||||
column: any;
|
||||
action: "run" | "redo" | "undo";
|
||||
actionParams: any;
|
||||
};
|
||||
|
||||
const missingFieldsReducer = (data: any) => (acc: string[], curr: string) => {
|
||||
if (data[curr] === undefined) {
|
||||
return [...acc, curr];
|
||||
} else return acc;
|
||||
};
|
||||
|
||||
const generateSchemaDocPath = (tablePath) => {
|
||||
const pathComponents = tablePath.split("/");
|
||||
return `_FIRETABLE_/settings/${
|
||||
pathComponents[1] === "table" ? "schema" : "groupSchema"
|
||||
}/${pathComponents[2]}`;
|
||||
};
|
||||
const serverTimestamp = admin.firestore.FieldValue.serverTimestamp;
|
||||
|
||||
export const actionScript = functions.https.onCall(
|
||||
async (data: ActionData, context: functions.https.CallableContext) => {
|
||||
try {
|
||||
if (!context) {
|
||||
throw Error(`You are unauthenticated`);
|
||||
}
|
||||
|
||||
const { ref, actionParams, column, action, schemaDocPath } = data;
|
||||
const _schemaDocPath =
|
||||
schemaDocPath ?? generateSchemaDocPath(ref.tablePath);
|
||||
const [schemaDoc, rowQuery] = await Promise.all([
|
||||
db.doc(_schemaDocPath).get(),
|
||||
db.doc(ref.path).get(),
|
||||
]);
|
||||
const row = rowQuery.data();
|
||||
const schemaDocData = schemaDoc.data();
|
||||
if (!schemaDocData) {
|
||||
return {
|
||||
success: false,
|
||||
message: "no schema found",
|
||||
};
|
||||
}
|
||||
const config = schemaDocData.columns[column.key].config;
|
||||
const { script, requiredRoles, requiredFields } = config;
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
throw Error(`You need to specify at least one role to run this script`);
|
||||
}
|
||||
if (!utilFns.hasAnyRole(requiredRoles, context)) {
|
||||
throw Error(`You don't have the required roles permissions`);
|
||||
}
|
||||
|
||||
const missingRequiredFields = requiredFields
|
||||
? requiredFields.reduce(missingFieldsReducer(row), [])
|
||||
: [];
|
||||
if (missingRequiredFields.length > 0) {
|
||||
throw new Error(
|
||||
`Missing required fields:${missingRequiredFields.join(", ")}`
|
||||
);
|
||||
}
|
||||
const result: {
|
||||
message: string;
|
||||
status: string;
|
||||
success: boolean;
|
||||
} = await eval(
|
||||
`async({row,db, ref,auth,utilFns,actionParams,context})=>{${
|
||||
action === "undo" ? config["undo.script"] : script
|
||||
}}`
|
||||
)({ row, db, auth, utilFns, ref, actionParams, context });
|
||||
if (result.success){
|
||||
const cellValue = {
|
||||
redo: config["redo.enabled"],
|
||||
status: result.status,
|
||||
completedAt: serverTimestamp(),
|
||||
ranBy: context.auth!.token.email,
|
||||
undo: config["undo.enabled"],
|
||||
}
|
||||
const userDoc = await db.collection("_FT_USERS").doc(context.auth!.uid).get()
|
||||
const user = userDoc?.get('user')
|
||||
await db.doc(ref.path).update({[column.key]:cellValue, _ft_updatedBy:user? {
|
||||
...user,
|
||||
...context.auth!,
|
||||
timestamp: new Date(),
|
||||
}:null })
|
||||
return {
|
||||
...result,
|
||||
cellValue,
|
||||
}
|
||||
}
|
||||
else return {
|
||||
success: false,
|
||||
message: result.message,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -1,17 +0,0 @@
|
||||
import * as functions from "firebase-functions";
|
||||
|
||||
export const hasAnyRole = (
|
||||
authorizedRoles: string[],
|
||||
context: functions.https.CallableContext
|
||||
) => {
|
||||
if (!context.auth || !context.auth.token.roles) return false;
|
||||
const userRoles = context.auth.token.roles as string[];
|
||||
const authorization = authorizedRoles.reduce(
|
||||
(authorized: boolean, role: string) => {
|
||||
if (userRoles.includes(role)) return true;
|
||||
else return authorized;
|
||||
},
|
||||
false
|
||||
);
|
||||
return authorization;
|
||||
};
|
||||
@@ -1,40 +0,0 @@
|
||||
import * as admin from "firebase-admin";
|
||||
export const serverTimestamp = admin.firestore.FieldValue.serverTimestamp;
|
||||
import { hasAnyRole } from "./auth";
|
||||
|
||||
const characters =
|
||||
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
export function generateId(length: number): string {
|
||||
let result = "";
|
||||
const charactersLength = characters.length;
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const hasRequiredFields = (requiredFields: string[], data: any) =>
|
||||
requiredFields.reduce((acc: boolean, currField: string) => {
|
||||
if (data[currField] === undefined || data[currField] === null) return false;
|
||||
else return acc;
|
||||
}, true);
|
||||
async function asyncForEach(array: any[], callback: Function) {
|
||||
for (let index = 0; index < array.length; index++) {
|
||||
await callback(array[index], index, array);
|
||||
}
|
||||
}
|
||||
const identifyTriggerType = (beforeData: any, afterData: any) =>
|
||||
Boolean(beforeData) && Boolean(afterData)
|
||||
? "update"
|
||||
: Boolean(afterData)
|
||||
? "create"
|
||||
: "delete";
|
||||
|
||||
export default {
|
||||
hasRequiredFields,
|
||||
generateId,
|
||||
serverTimestamp,
|
||||
hasAnyRole,
|
||||
asyncForEach,
|
||||
identifyTriggerType,
|
||||
};
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "CommonJS",
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedLocals": true,
|
||||
"outDir": "lib",
|
||||
"sourceMap": true,
|
||||
"strict": true,
|
||||
"noImplicitAny": false,
|
||||
"target": "ESNext"
|
||||
},
|
||||
"compileOnSave": true,
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
{
|
||||
"rules": {
|
||||
// -- Strict errors --
|
||||
// These lint rules are likely always a good idea.
|
||||
|
||||
// Force function overloads to be declared together. This ensures readers understand APIs.
|
||||
"adjacent-overload-signatures": true,
|
||||
|
||||
// Do not allow the subtle/obscure comma operator.
|
||||
"ban-comma-operator": true,
|
||||
|
||||
// Do not allow internal modules or namespaces . These are deprecated in favor of ES6 modules.
|
||||
"no-namespace": true,
|
||||
|
||||
// Do not allow parameters to be reassigned. To avoid bugs, developers should instead assign new values to new vars.
|
||||
"no-parameter-reassignment": true,
|
||||
|
||||
// Force the use of ES6-style imports instead of /// <reference path=> imports.
|
||||
"no-reference": true,
|
||||
|
||||
// Do not allow type assertions that do nothing. This is a big warning that the developer may not understand the
|
||||
// code currently being edited (they may be incorrectly handling a different type case that does not exist).
|
||||
"no-unnecessary-type-assertion": true,
|
||||
|
||||
// Disallow nonsensical label usage.
|
||||
"label-position": true,
|
||||
|
||||
// Disallows the (often typo) syntax if (var1 = var2). Replace with if (var2) { var1 = var2 }.
|
||||
"no-conditional-assignment": true,
|
||||
|
||||
// Disallows constructors for primitive types (e.g. new Number('123'), though Number('123') is still allowed).
|
||||
"no-construct": true,
|
||||
|
||||
// Do not allow super() to be called twice in a constructor.
|
||||
"no-duplicate-super": true,
|
||||
|
||||
// Do not allow the same case to appear more than once in a switch block.
|
||||
"no-duplicate-switch-case": true,
|
||||
|
||||
// Do not allow a variable to be declared more than once in the same block. Consider function parameters in this
|
||||
// rule.
|
||||
"no-duplicate-variable": [true, "check-parameters"],
|
||||
|
||||
// Disallows a variable definition in an inner scope from shadowing a variable in an outer scope. Developers should
|
||||
// instead use a separate variable name.
|
||||
"no-shadowed-variable": true,
|
||||
|
||||
// Empty blocks are almost never needed. Allow the one general exception: empty catch blocks.
|
||||
"no-empty": [true, "allow-empty-catch"],
|
||||
|
||||
// Functions must either be handled directly (e.g. with a catch() handler) or returned to another function.
|
||||
// This is a major source of errors in Cloud Functions and the team strongly recommends leaving this rule on.
|
||||
"no-floating-promises": true,
|
||||
|
||||
// Do not allow any imports for modules that are not in package.json. These will almost certainly fail when
|
||||
// deployed.
|
||||
"no-implicit-dependencies": true,
|
||||
|
||||
// The 'this' keyword can only be used inside of classes.
|
||||
"no-invalid-this": true,
|
||||
|
||||
// Do not allow strings to be thrown because they will not include stack traces. Throw Errors instead.
|
||||
"no-string-throw": true,
|
||||
|
||||
// Disallow control flow statements, such as return, continue, break, and throw in finally blocks.
|
||||
"no-unsafe-finally": true,
|
||||
|
||||
// Do not allow variables to be used before they are declared.
|
||||
"no-use-before-declare": true,
|
||||
|
||||
// Expressions must always return a value. Avoids common errors like const myValue = functionReturningVoid();
|
||||
"no-void-expression": [true, "ignore-arrow-function-shorthand"],
|
||||
|
||||
// Disallow duplicate imports in the same file.
|
||||
"no-duplicate-imports": true,
|
||||
|
||||
// -- Strong Warnings --
|
||||
// These rules should almost never be needed, but may be included due to legacy code.
|
||||
// They are left as a warning to avoid frustration with blocked deploys when the developer
|
||||
// understand the warning and wants to deploy anyway.
|
||||
|
||||
// Warn when an empty interface is defined. These are generally not useful.
|
||||
"no-empty-interface": { "severity": "warning" },
|
||||
|
||||
// Warn when an import will have side effects.
|
||||
"no-import-side-effect": { "severity": "warning" },
|
||||
|
||||
// Warn when variables are defined with var. Var has subtle meaning that can lead to bugs. Strongly prefer const for
|
||||
// most values and let for values that will change.
|
||||
"no-var-keyword": { "severity": "warning" },
|
||||
|
||||
// Prefer === and !== over == and !=. The latter operators support overloads that are often accidental.
|
||||
"triple-equals": { "severity": "warning" },
|
||||
|
||||
// Warn when using deprecated APIs.
|
||||
"deprecation": { "severity": "warning" },
|
||||
|
||||
// -- Light Warnings --
|
||||
// These rules are intended to help developers use better style. Simpler code has fewer bugs. These would be "info"
|
||||
// if TSLint supported such a level.
|
||||
|
||||
// prefer for( ... of ... ) to an index loop when the index is only used to fetch an object from an array.
|
||||
// (Even better: check out utils like .map if transforming an array!)
|
||||
"prefer-for-of": { "severity": "warning" },
|
||||
|
||||
// Warns if function overloads could be unified into a single function with optional or rest parameters.
|
||||
"unified-signatures": { "severity": "warning" },
|
||||
|
||||
// Prefer const for values that will not change. This better documents code.
|
||||
"prefer-const": { "severity": "warning" },
|
||||
|
||||
// Multi-line object literals and function calls should have a trailing comma. This helps avoid merge conflicts.
|
||||
"trailing-comma": { "severity": "warning" }
|
||||
},
|
||||
"linterOptions": {
|
||||
"exclude": ["./generator/templates/**"]
|
||||
},
|
||||
"defaultSeverity": "error"
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
# yarn lockfile v1
|
||||
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
export const dependencies = {
|
||||
// --- Add your dependencies
|
||||
// algoliasearch: "^4.8.3",
|
||||
};
|
||||
// Define your spark
|
||||
const sparkName = async (data, sparkContext) => {
|
||||
|
||||
// Your spark inputs
|
||||
const { row, targetPath, fieldsToSync } = data;
|
||||
const { triggerType, change } = sparkContext;
|
||||
|
||||
// ---------------------------------------------
|
||||
// --- Utilise your dependencies ---
|
||||
// const algoliasearch = require("algoliasearch");
|
||||
|
||||
// ---------------------------------------------
|
||||
// --- Get the secret from Secrets Manager
|
||||
// Example: Algolia Secret
|
||||
// const { getSecret } = require("../utils");
|
||||
// const { appId, adminKey } = await getSecret("algolia");
|
||||
|
||||
// ---------------------------------------------
|
||||
// --- Connect to any third party extensions ---
|
||||
// Example Algolia
|
||||
// const client = algoliasearch(appId, adminKey);
|
||||
// const _index = client.initIndex(index);
|
||||
|
||||
|
||||
// ---------------------------------------------
|
||||
// --- Handle required trigger actions ---
|
||||
switch (triggerType) {
|
||||
|
||||
case "create":
|
||||
// create trigger actions
|
||||
break;
|
||||
|
||||
case "update":
|
||||
// update trigger actions
|
||||
break;
|
||||
|
||||
case "delete":
|
||||
// delete trigger actions
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
|
||||
|
||||
};
|
||||
|
||||
export default sparkName;
|
||||
BIN
icon.png
|
Before Width: | Height: | Size: 956 B After Width: | Height: | Size: 1.1 KiB |
@@ -1,26 +1,31 @@
|
||||
{
|
||||
"name": "Firetable",
|
||||
"version": "1.4.1",
|
||||
"homepage": "https://firetable.io/",
|
||||
"name": "Rowy",
|
||||
"version": "2.0.0-rc.0",
|
||||
"homepage": "https://rowy.io",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/FiretableProject/firetable.git"
|
||||
"url": "https://github.com/rowyio/rowy.git"
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@antlerengineering/form-builder": "^2.10.3",
|
||||
"@antlerengineering/multiselect": "^0.9.7",
|
||||
"@craco/craco": "^6.2.0",
|
||||
"@date-io/date-fns": "1.x",
|
||||
"@material-ui/core": "^4.12.2",
|
||||
"@material-ui/icons": "^4.11.2",
|
||||
"@material-ui/lab": "^4.0.0-alpha.56",
|
||||
"@material-ui/pickers": "^3.3.10",
|
||||
"@emotion/react": "^11.4.0",
|
||||
"@emotion/styled": "^11.3.0",
|
||||
"@mdi/js": "^5.9.55",
|
||||
"@monaco-editor/react": "^4.1.0",
|
||||
"@tinymce/tinymce-react": "^3.4.0",
|
||||
"@mui/icons-material": "^5.0.0",
|
||||
"@mui/lab": "^5.0.0-alpha.47",
|
||||
"@mui/material": "^5.0.0",
|
||||
"@mui/styles": "^5.0.0",
|
||||
"@rowy/form-builder": "^0.1.2",
|
||||
"@rowy/multiselect": "^0.1.12",
|
||||
"@tinymce/tinymce-react": "^3.12.6",
|
||||
"algoliasearch": "^4.8.6",
|
||||
"ansi-to-react": "^6.1.5",
|
||||
"chroma-js": "^2.1.0",
|
||||
"chroma-js": "^2.1.2",
|
||||
"colord": "^2.7.0",
|
||||
"craco-swc": "^0.1.3",
|
||||
"csv-parse": "^4.15.3",
|
||||
"date-fns": "^2.19.0",
|
||||
"dompurify": "^2.2.6",
|
||||
@@ -30,30 +35,35 @@
|
||||
"json-format": "^1.0.1",
|
||||
"json2csv": "^5.0.6",
|
||||
"jszip": "^3.6.0",
|
||||
"jwt-decode": "^3.1.2",
|
||||
"lodash": "^4.17.21",
|
||||
"moment": "^2.29.1",
|
||||
"notistack": "^1.0.6-next.3",
|
||||
"query-string": "^6.8.3",
|
||||
"react": "^17.0.2",
|
||||
"react-beautiful-dnd": "^13.0.0",
|
||||
"react-color": "^2.17.3",
|
||||
"react-data-grid": "7.0.0-canary.30",
|
||||
"react-div-100vh": "^0.3.8",
|
||||
"react-color-palette": "^6.1.0",
|
||||
"react-data-grid": "^7.0.0-beta.5",
|
||||
"react-div-100vh": "^0.6.0",
|
||||
"react-dnd": "^11.1.3",
|
||||
"react-dnd-html5-backend": "^11.1.3",
|
||||
"react-dom": "^17.0.2",
|
||||
"react-dropzone": "^10.1.8",
|
||||
"react-element-scroll-hook": "^1.1.0",
|
||||
"react-firebaseui": "^5.0.2",
|
||||
"react-helmet": "^6.1.0",
|
||||
"react-hook-form": "^6",
|
||||
"react-image": "^4.0.3",
|
||||
"react-joyride": "^2.3.0",
|
||||
"react-json-view": "^1.19.1",
|
||||
"react-router-dom": "^5.0.1",
|
||||
"react-router-hash-link": "^2.4.3",
|
||||
"react-scripts": "^4.0.3",
|
||||
"react-scroll-sync": "^0.8.0",
|
||||
"react-usestateref": "^1.0.5",
|
||||
"serve": "^11.3.2",
|
||||
"tinymce": "^5.2.0",
|
||||
"typescript": "^4.3.5",
|
||||
"tinymce": "^5.9.2",
|
||||
"typescript": "^4.4.2",
|
||||
"use-algolia": "^1.4.1",
|
||||
"use-debounce": "^3.3.0",
|
||||
"use-persisted-state": "^0.3.3",
|
||||
@@ -61,13 +71,14 @@
|
||||
"yup": "^0.32.9"
|
||||
},
|
||||
"scripts": {
|
||||
"upstream": "git fetch upstream;git merge upstream/v2;git commit -m'merge upstream';git push",
|
||||
"serve": "serve -s build",
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test --env=jsdom",
|
||||
"eject": "react-scripts eject",
|
||||
"start": "craco start",
|
||||
"build": "craco build",
|
||||
"test": "craco test --env=jsdom",
|
||||
"eject": "craco eject",
|
||||
"env": "node createDotEnv",
|
||||
"target": "firebase target:apply hosting firetable",
|
||||
"target": "firebase target:apply hosting rowy",
|
||||
"deploy": "firebase deploy"
|
||||
},
|
||||
"engines": {
|
||||
@@ -99,14 +110,18 @@
|
||||
"@types/react-color": "^3.0.1",
|
||||
"@types/react-div-100vh": "^0.3.0",
|
||||
"@types/react-dom": "^17.0.8",
|
||||
"@types/react-helmet": "^6.1.2",
|
||||
"@types/react-router-dom": "^5.1.7",
|
||||
"@types/react-router-hash-link": "^2.4.1",
|
||||
"@types/use-persisted-state": "^0.3.0",
|
||||
"craco-alias": "^3.0.1",
|
||||
"firebase-tools": "^8.12.1",
|
||||
"husky": "^4.2.5",
|
||||
"monaco-editor": "^0.21.2",
|
||||
"playwright": "^1.5.2",
|
||||
"prettier": "^2.2.1",
|
||||
"pretty-quick": "^3.0.0"
|
||||
"pretty-quick": "^3.0.0",
|
||||
"raw-loader": "^4.0.2"
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {
|
||||
0
www/public/auth.d.ts → public/auth.d.ts
vendored
@@ -3,7 +3,7 @@
|
||||
<msapplication>
|
||||
<tile>
|
||||
<square150x150logo src="/mstile-150x150.png"/>
|
||||
<TileColor>#ED4746</TileColor>
|
||||
<TileColor>#4200ff</TileColor>
|
||||
</tile>
|
||||
</msapplication>
|
||||
</browserconfig>
|
||||
BIN
public/favicon.ico
Normal file
|
After Width: | Height: | Size: 15 KiB |
BIN
public/favicon/android-chrome-192x192.png
Normal file
|
After Width: | Height: | Size: 2.1 KiB |
BIN
public/favicon/android-chrome-512x512.png
Normal file
|
After Width: | Height: | Size: 5.6 KiB |
BIN
public/favicon/apple-touch-icon.png
Normal file
|
After Width: | Height: | Size: 2.3 KiB |
BIN
public/favicon/favicon-16x16.png
Normal file
|
After Width: | Height: | Size: 620 B |
BIN
public/favicon/favicon-32x32.png
Normal file
|
After Width: | Height: | Size: 810 B |
3
public/favicon/icon.svg
Executable file
@@ -0,0 +1,3 @@
|
||||
<svg width="16" height="16" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M13 0a3 3 0 010 6l-2-.001V6H6v7a3 3 0 01-6 0V3a3 3 0 015.501-1.657A2.989 2.989 0 018 0h5zM5 11H1v2a2 2 0 001.85 1.995L3 15a2 2 0 001.995-1.85L5 13v-2zm0-5H1v4h4V6zM3 1a2 2 0 00-1.995 1.85L1 3v2h4V3a2 2 0 00-1.85-1.995L3 1zm8.001 0v4H13a2 2 0 001.995-1.85L15 3a2 2 0 00-1.85-1.995L13 1h-1.999zM10 1H8a2 2 0 00-1.995 1.85L6 3v2h4V1z" fill="#4200FF" fill-rule="nonzero"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 451 B |
BIN
public/favicon/mstile-144x144.png
Normal file
|
After Width: | Height: | Size: 2.5 KiB |
BIN
public/favicon/mstile-150x150.png
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
public/favicon/mstile-310x150.png
Normal file
|
After Width: | Height: | Size: 3.1 KiB |
BIN
public/favicon/mstile-310x310.png
Normal file
|
After Width: | Height: | Size: 5.7 KiB |
BIN
public/favicon/mstile-70x70.png
Normal file
|
After Width: | Height: | Size: 1.9 KiB |
33
public/favicon/safari-pinned-tab.svg
Normal file
@@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
|
||||
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
|
||||
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
|
||||
width="700.000000pt" height="700.000000pt" viewBox="0 0 700.000000 700.000000"
|
||||
preserveAspectRatio="xMidYMid meet">
|
||||
<metadata>
|
||||
Created by potrace 1.14, written by Peter Selinger 2001-2017
|
||||
</metadata>
|
||||
<g transform="translate(0.000000,700.000000) scale(0.100000,-0.100000)"
|
||||
fill="#000000" stroke="none">
|
||||
<path d="M1105 6984 c-512 -91 -904 -436 -1050 -925 -23 -76 -28 -99 -45 -209
|
||||
-11 -72 -11 -4640 0 -4705 5 -27 12 -67 15 -88 17 -99 74 -260 131 -365 188
|
||||
-346 512 -584 909 -669 118 -25 392 -24 505 2 14 4 38 9 54 11 49 9 197 64
|
||||
271 101 314 157 564 449 669 781 62 196 59 113 60 1859 1 1054 4 1593 11 1594
|
||||
6 1 725 2 1600 4 1739 3 1652 0 1847 61 142 44 312 135 424 225 16 13 70 64
|
||||
119 114 176 176 301 411 352 663 18 90 25 344 11 422 -5 30 -11 66 -12 80 -2
|
||||
14 -9 45 -15 70 -131 493 -516 858 -1022 967 -79 17 -164 18 -1329 18 -685 0
|
||||
-1265 -3 -1290 -7 -95 -16 -117 -21 -196 -44 -252 -73 -529 -267 -678 -476
|
||||
l-40 -55 -45 61 c-183 251 -482 438 -799 503 -105 21 -354 25 -457 7z m444
|
||||
-455 c267 -72 493 -283 587 -550 46 -131 52 -206 50 -704 l-1 -460 -867 -2
|
||||
c-606 -1 -870 2 -875 10 -8 13 -7 879 1 962 39 399 389 743 784 771 48 4 88 7
|
||||
89 8 8 6 170 -18 232 -35z m2811 32 c13 -1 15 -103 14 -863 -1 -475 -2 -868
|
||||
-3 -874 -2 -17 -1738 -17 -1743 -1 -6 19 -1 948 5 991 19 121 78 269 148 373
|
||||
45 66 162 180 232 226 125 83 260 130 415 145 51 5 848 8 932 3z m1425 -4
|
||||
c198 -22 377 -109 520 -253 166 -165 256 -384 256 -619 -1 -389 -272 -744
|
||||
-642 -840 -107 -28 -147 -30 -634 -30 l-470 0 -1 872 -1 872 51 3 c88 5 868 1
|
||||
921 -5z m-3604 -2186 c4 0 6 -394 5 -873 l-1 -873 -868 0 c-511 0 -871 4 -874
|
||||
9 -8 12 -8 1720 -1 1732 5 7 1704 12 1739 5z m7 -2665 c-1 -435 -3 -490 -21
|
||||
-571 -102 -481 -571 -782 -1050 -675 -285 64 -534 286 -629 560 -47 137 -51
|
||||
186 -50 680 0 234 1 439 1 456 l1 32 874 0 874 0 0 -482z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.9 KiB |
@@ -2,10 +2,24 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta name="description" content="Excel for your database" />
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, viewport-fit=cover"
|
||||
/>
|
||||
<meta
|
||||
name="theme-color"
|
||||
content="#FAF9FB"
|
||||
media="(prefers-color-scheme: light)"
|
||||
/>
|
||||
<meta
|
||||
name="theme-color"
|
||||
content="#0F0F12"
|
||||
media="(prefers-color-scheme: dark)"
|
||||
/>
|
||||
<meta name="color-scheme" content="default" />
|
||||
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
|
||||
<!--
|
||||
Generated from https://realfavicongenerator.net/
|
||||
@@ -27,15 +41,20 @@
|
||||
sizes="16x16"
|
||||
href="/favicon/favicon-16x16.png"
|
||||
/>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon/firetable.svg" />
|
||||
<link
|
||||
rel="icon"
|
||||
type="image/svg+xml"
|
||||
href="/favicon/icon.svg"
|
||||
id="favicon-svg"
|
||||
/>
|
||||
<link rel="manifest" href="/site.webmanifest" />
|
||||
<link
|
||||
rel="mask-icon"
|
||||
href="/favicon/safari-pinned-tab.svg"
|
||||
color="#ED4746"
|
||||
color="#4200FF"
|
||||
/>
|
||||
<meta name="msapplication-TileColor" content="#ED4746" />
|
||||
<meta name="theme-color" content="#ffffff" />
|
||||
<meta name="msapplication-TileColor" content="#4200FF" />
|
||||
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
@@ -50,18 +69,16 @@
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<link rel="stylesheet" href="https://use.typekit.net/ngg8buf.css" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" />
|
||||
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link rel="stylesheet" href="https://rsms.me/inter/inter.css" />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700,700i&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono&display=swap"
|
||||
rel="stylesheet"
|
||||
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&display=swap"
|
||||
/>
|
||||
|
||||
<title>Firetable</title>
|
||||
<title>Rowy</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"short_name": "Firetable",
|
||||
"name": "Firetable",
|
||||
"short_name": "Rowy",
|
||||
"name": "Rowy",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
19
public/site.webmanifest
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "Rowy",
|
||||
"short_name": "Rowy",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/android-chrome-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/android-chrome-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
],
|
||||
"theme_color": "#4200ff",
|
||||
"background_color": "#4200ff",
|
||||
"display": "standalone"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable @typescript-eslint/ban-types */
|
||||
|
||||
// firetable/ft_build/functions/node_modules/@google-cloud/storage/build/src/bucket.d.ts
|
||||
// node_modules/@google-cloud/storage/build/src/bucket.d.ts
|
||||
declare class Bucket {
|
||||
/**
|
||||
* The bucket's name.
|
||||
222
src/App.tsx
Normal file
@@ -0,0 +1,222 @@
|
||||
import { lazy, Suspense } from "react";
|
||||
import { Route, Switch, Redirect } from "react-router-dom";
|
||||
import LocalizationProvider from "@mui/lab/LocalizationProvider";
|
||||
import AdapterDateFns from "@mui/lab/AdapterDateFns";
|
||||
|
||||
import { StyledEngineProvider } from "@mui/material/styles";
|
||||
import "./space-grotesk.css";
|
||||
|
||||
import CustomBrowserRouter from "utils/CustomBrowserRouter";
|
||||
import PrivateRoute from "utils/PrivateRoute";
|
||||
import ErrorBoundary from "components/ErrorBoundary";
|
||||
import Loading from "components/Loading";
|
||||
import Navigation from "components/Navigation";
|
||||
import Logo from "assets/Logo";
|
||||
|
||||
import ConfirmationProvider from "components/ConfirmationDialog/Provider";
|
||||
import { AppProvider } from "contexts/AppContext";
|
||||
import { ProjectContextProvider } from "contexts/ProjectContext";
|
||||
import { SnackbarProvider } from "contexts/SnackbarContext";
|
||||
import { SnackLogProvider } from "contexts/SnackLogContext";
|
||||
import routes from "constants/routes";
|
||||
|
||||
import AuthPage from "pages/Auth";
|
||||
import SignOutPage from "pages/Auth/SignOut";
|
||||
import SignUpPage from "pages/Auth/SignUp";
|
||||
import DeployPage from "pages/Deploy";
|
||||
import TestPage from "pages/Test";
|
||||
import RowyRunTestPage from "pages/RowyRunTest";
|
||||
import PageNotFound from "pages/PageNotFound";
|
||||
|
||||
import Favicon from "assets/Favicon";
|
||||
import "analytics";
|
||||
|
||||
// prettier-ignore
|
||||
const AuthSetupGuidePage = lazy(() => import("pages/Auth/SetupGuide" /* webpackChunkName: "AuthSetupGuide" */));
|
||||
// prettier-ignore
|
||||
const ImpersonatorAuthPage = lazy(() => import("./pages/Auth/ImpersonatorAuth" /* webpackChunkName: "ImpersonatorAuthPage" */));
|
||||
// prettier-ignore
|
||||
const JwtAuthPage = lazy(() => import("./pages/Auth/JwtAuth" /* webpackChunkName: "JwtAuthPage" */));
|
||||
|
||||
// prettier-ignore
|
||||
const HomePage = lazy(() => import("./pages/Home" /* webpackChunkName: "HomePage" */));
|
||||
// prettier-ignore
|
||||
const TablePage = lazy(() => import("./pages/Table" /* webpackChunkName: "TablePage" */));
|
||||
|
||||
// prettier-ignore
|
||||
const ProjectSettingsPage = lazy(() => import("./pages/Settings/ProjectSettings" /* webpackChunkName: "ProjectSettingsPage" */));
|
||||
// prettier-ignore
|
||||
const UserSettingsPage = lazy(() => import("./pages/Settings/UserSettings" /* webpackChunkName: "UserSettingsPage" */));
|
||||
// prettier-ignore
|
||||
const UserManagementPage = lazy(() => import("./pages/Settings/UserManagement" /* webpackChunkName: "UserManagementPage" */));
|
||||
// prettier-ignore
|
||||
const SetupPage = lazy(() => import("pages/Setup" /* webpackChunkName: "SetupPage" */));
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<StyledEngineProvider injectFirst>
|
||||
<ErrorBoundary>
|
||||
<LocalizationProvider dateAdapter={AdapterDateFns}>
|
||||
<AppProvider>
|
||||
<Favicon />
|
||||
<SnackbarProvider>
|
||||
<ConfirmationProvider>
|
||||
<SnackLogProvider>
|
||||
<CustomBrowserRouter>
|
||||
<Suspense fallback={<Loading fullScreen />}>
|
||||
<Switch>
|
||||
<Route
|
||||
exact
|
||||
path={routes.auth}
|
||||
render={() => <AuthPage />}
|
||||
/>
|
||||
<Route
|
||||
exact
|
||||
path={routes.authSetup}
|
||||
render={() => <AuthSetupGuidePage />}
|
||||
/>
|
||||
<Route
|
||||
exact
|
||||
path={routes.jwtAuth}
|
||||
render={() => <JwtAuthPage />}
|
||||
/>
|
||||
<Route
|
||||
exact
|
||||
path={routes.signOut}
|
||||
render={() => <SignOutPage />}
|
||||
/>
|
||||
<Route
|
||||
exact
|
||||
path={routes.signUp}
|
||||
render={() => <SignUpPage />}
|
||||
/>
|
||||
<Route
|
||||
exact
|
||||
path={routes.setup}
|
||||
render={() => <SetupPage />}
|
||||
/>
|
||||
<Route
|
||||
exact
|
||||
path={routes.deploy}
|
||||
render={() => <DeployPage />}
|
||||
/>
|
||||
|
||||
<Route
|
||||
exact
|
||||
path={"/test"}
|
||||
render={() => <TestPage />}
|
||||
/>
|
||||
|
||||
<PrivateRoute
|
||||
exact
|
||||
path={[
|
||||
routes.home,
|
||||
routes.tableWithId,
|
||||
routes.tableGroupWithId,
|
||||
routes.settings,
|
||||
routes.projectSettings,
|
||||
routes.userSettings,
|
||||
routes.userManagement,
|
||||
routes.impersonatorAuth,
|
||||
routes.rowyRunTest,
|
||||
]}
|
||||
render={() => (
|
||||
<ProjectContextProvider>
|
||||
<Switch>
|
||||
<Route
|
||||
exact
|
||||
path={routes.impersonatorAuth}
|
||||
render={() => <ImpersonatorAuthPage />}
|
||||
/>
|
||||
<Route
|
||||
exact
|
||||
path={routes.rowyRunTest}
|
||||
render={() => <RowyRunTestPage />}
|
||||
/>
|
||||
<PrivateRoute
|
||||
exact
|
||||
path={routes.home}
|
||||
render={() => (
|
||||
<Navigation
|
||||
title="Home"
|
||||
titleComponent={(open, pinned) =>
|
||||
!(open && pinned) && (
|
||||
<Logo
|
||||
style={{
|
||||
display: "block",
|
||||
margin: "0 auto",
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
>
|
||||
<HomePage />
|
||||
</Navigation>
|
||||
)}
|
||||
/>
|
||||
<PrivateRoute
|
||||
path={routes.tableWithId}
|
||||
render={() => <TablePage />}
|
||||
/>
|
||||
<PrivateRoute
|
||||
path={routes.tableGroupWithId}
|
||||
render={() => <TablePage />}
|
||||
/>
|
||||
|
||||
<PrivateRoute
|
||||
exact
|
||||
path={routes.settings}
|
||||
render={() => (
|
||||
<Redirect to={routes.userSettings} />
|
||||
)}
|
||||
/>
|
||||
<PrivateRoute
|
||||
exact
|
||||
path={routes.projectSettings}
|
||||
render={() => (
|
||||
<Navigation title="Project Settings">
|
||||
<ProjectSettingsPage />
|
||||
</Navigation>
|
||||
)}
|
||||
/>
|
||||
<PrivateRoute
|
||||
exact
|
||||
path={routes.userSettings}
|
||||
render={() => (
|
||||
<Navigation title="Settings">
|
||||
<UserSettingsPage />
|
||||
</Navigation>
|
||||
)}
|
||||
/>
|
||||
<PrivateRoute
|
||||
exact
|
||||
path={routes.userManagement}
|
||||
render={() => (
|
||||
<Navigation title="User Management">
|
||||
<UserManagementPage />
|
||||
</Navigation>
|
||||
)}
|
||||
/>
|
||||
</Switch>
|
||||
</ProjectContextProvider>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Route
|
||||
exact
|
||||
path={routes.pageNotFound}
|
||||
render={() => <PageNotFound />}
|
||||
/>
|
||||
<Route render={() => <PageNotFound />} />
|
||||
</Switch>
|
||||
</Suspense>
|
||||
</CustomBrowserRouter>
|
||||
</SnackLogProvider>
|
||||
</ConfirmationProvider>
|
||||
</SnackbarProvider>
|
||||
</AppProvider>
|
||||
</LocalizationProvider>
|
||||
</ErrorBoundary>
|
||||
</StyledEngineProvider>
|
||||
);
|
||||
}
|
||||
17
src/analytics.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import firebase from "firebase/app";
|
||||
import "firebase/analytics";
|
||||
|
||||
const firebaseConfig = {
|
||||
apiKey: "AIzaSyArABiYGK7dZgwSk0pw_6vKbOt6U1ZRPpc",
|
||||
authDomain: "rowy-service.firebaseapp.com",
|
||||
projectId: "rowy-service",
|
||||
storageBucket: "rowy-service.appspot.com",
|
||||
messagingSenderId: "305614947641",
|
||||
appId: "1:305614947641:web:cb10467e7c11c93d6e14e8",
|
||||
measurementId: "G-0VWE25LFZJ",
|
||||
};
|
||||
|
||||
// Initialize Firebase
|
||||
const rowyServiceApp = firebase.initializeApp(firebaseConfig, "rowy-service");
|
||||
|
||||
export const analytics = firebase.analytics(rowyServiceApp);
|
||||
74
src/assets/BrandedBackground.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
import Helmet from "react-helmet";
|
||||
import { use100vh } from "react-div-100vh";
|
||||
|
||||
import { useTheme, alpha } from "@mui/material/styles";
|
||||
import { Box, BoxProps } from "@mui/material";
|
||||
|
||||
import bgPattern from "assets/bg-pattern.svg";
|
||||
import bgPatternDark from "assets/bg-pattern-dark.svg";
|
||||
|
||||
export default function BrandedBackground() {
|
||||
const theme = useTheme();
|
||||
|
||||
return (
|
||||
<Helmet>
|
||||
<style type="text/css">
|
||||
{`
|
||||
body {
|
||||
background-size: 100%;
|
||||
background-image: ${
|
||||
// prettier-ignore
|
||||
[
|
||||
`radial-gradient(circle at 85% 100%, ${theme.palette.background.paper} 20%, ${alpha(theme.palette.background.paper, 0)})`,
|
||||
`radial-gradient(80% 80% at 15% 100%, ${alpha("#FA0", 0.1)} 25%, ${alpha("#F0A", 0.1)} 50%, ${alpha("#F0A", 0)} 100%)`,
|
||||
`linear-gradient(to top, ${alpha(theme.palette.background.paper, 1)}, ${alpha(theme.palette.background.paper, 0)})`,
|
||||
`radial-gradient(60% 180% at 100% 15%, ${alpha("#0FA", 0.3)} 25%, ${alpha("#0AF", 0.2)} 50%, ${alpha("#0AF", 0)} 100%)`,
|
||||
`linear-gradient(${alpha(theme.palette.primary.main, 0.2)}, ${alpha(theme.palette.primary.main, 0.2)})`,
|
||||
].join(", ")
|
||||
};
|
||||
}
|
||||
body::before {
|
||||
content: "";
|
||||
display: block;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: -1;
|
||||
|
||||
background-image: url('${
|
||||
theme.palette.mode === "dark" ? bgPatternDark : bgPattern
|
||||
}');
|
||||
background-size: ${(480 * 10) / 14}px;
|
||||
mix-blend-mode: overlay;
|
||||
}
|
||||
`}
|
||||
</style>
|
||||
</Helmet>
|
||||
);
|
||||
}
|
||||
|
||||
export function Wrapper(props: BoxProps) {
|
||||
const fullScreenHeight = use100vh() ?? 0;
|
||||
|
||||
return (
|
||||
<Box
|
||||
{...props}
|
||||
sx={{
|
||||
display: "grid",
|
||||
placeItems: "center",
|
||||
alignContent: "center",
|
||||
gap: (theme) => ({ xs: theme.spacing(2), sm: theme.spacing(3) }),
|
||||
gridAutoRows: "max-content",
|
||||
minHeight: fullScreenHeight > 0 ? `${fullScreenHeight}px` : "100vh",
|
||||
|
||||
pt: (theme) => `max(env(safe-area-inset-top), ${theme.spacing(1)})`,
|
||||
pb: (theme) => `max(env(safe-area-inset-bottom), ${theme.spacing(1)})`,
|
||||
pl: (theme) => `max(env(safe-area-inset-left), ${theme.spacing(1)})`,
|
||||
pr: (theme) => `max(env(safe-area-inset-right), ${theme.spacing(1)})`,
|
||||
...props.sx,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
25
src/assets/Favicon.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import { useEffect } from "react";
|
||||
import { useTheme } from "@mui/material";
|
||||
|
||||
export default function Favicon() {
|
||||
const theme = useTheme();
|
||||
|
||||
useEffect(() => {
|
||||
const svg = `<svg width="16" height="16" xmlns="http://www.w3.org/2000/svg">
|
||||
<path
|
||||
d="M13 0a3 3 0 010 6l-2-.001V6H6v7a3 3 0 01-6 0V3a3 3 0 015.501-1.657A2.989 2.989 0 018 0h5zM5 11H1v2a2 2 0 001.85 1.995L3 15a2 2 0 001.995-1.85L5 13v-2zm0-5H1v4h4V6zM3 1a2 2 0 00-1.995 1.85L1 3v2h4V3a2 2 0 00-1.85-1.995L3 1zm8.001 0v4H13a2 2 0 001.995-1.85L15 3a2 2 0 00-1.85-1.995L13 1h-1.999zM10 1H8a2 2 0 00-1.995 1.85L6 3v2h4V1z"
|
||||
fill="${theme.palette.primary.main}"
|
||||
fill-rule="nonzero"
|
||||
/>
|
||||
</svg>`;
|
||||
|
||||
document.getElementById("favicon-svg")?.setAttribute(
|
||||
"href",
|
||||
`data:image/svg+xml;utf8,${encodeURIComponent(svg)
|
||||
.replace(/\n/g, "")
|
||||
.replace(/\s{2,}/g, "")}`
|
||||
);
|
||||
}, [theme.palette.mode, theme.palette.primary.main]);
|
||||
|
||||
return null;
|
||||
}
|
||||
33
src/assets/Logo.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { SVGProps } from "react";
|
||||
import { useTheme } from "@mui/material";
|
||||
|
||||
export interface ILogoProps extends SVGProps<SVGSVGElement> {
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export default function Logo({ size = 1.5, ...props }: ILogoProps) {
|
||||
const theme = useTheme();
|
||||
|
||||
return (
|
||||
<svg
|
||||
width={Math.round(68 * size)}
|
||||
height={Math.round(21 * size)}
|
||||
viewBox="0 -1.5 68 21"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
aria-labelledby="rowy-logo-title"
|
||||
role="img"
|
||||
{...props}
|
||||
>
|
||||
<title id="rowy-logo-title">rowy</title>
|
||||
|
||||
<path
|
||||
d="M58 3l4 9 4-9h2l-7 16h-2l2-4.5L56 3h2zm-26-.25a6.25 6.25 0 110 12.5 6.25 6.25 0 010-12.5zM26 3v2h-4v10h-2V3h6zm14 0l3 9 3-9h2l3 9 3-9h2l-4 12h-2l-3-9-3 9h-2L38 3h2zm-8 1.75a4.25 4.25 0 100 8.5 4.25 4.25 0 000-8.5z"
|
||||
fill={theme.palette.text.primary}
|
||||
/>
|
||||
<path
|
||||
d="M13 0a3 3 0 010 6l-2-.001V6H6v7a3 3 0 01-6 0V3a3 3 0 015.501-1.657A2.989 2.989 0 018 0h5zM5 11H1v2a2 2 0 001.85 1.995L3 15a2 2 0 001.995-1.85L5 13v-2zm0-5H1v4h4V6zM3 1a2 2 0 00-1.995 1.85L1 3v2h4V3a2 2 0 00-1.85-1.995L3 1zm8.001 0v4H13a2 2 0 001.995-1.85L15 3a2 2 0 00-1.85-1.995L13 1h-1.999zM10 1H8a2 2 0 00-1.995 1.85L6 3v2h4V1z"
|
||||
fill={theme.palette.primary.main}
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||