1
0
Fork 0
mirror of synced 2024-06-20 19:30:28 +12:00

apps being served correctly

This commit is contained in:
Martin McKeaveney 2020-05-04 17:13:57 +01:00
parent 427cdafeda
commit 2c361f3d1d
130 changed files with 113 additions and 10303 deletions

View file

@ -113,7 +113,7 @@ const setPackage = (store, initial) => async (pkg) => {
initial.pages = pkg.pages
initial.hasAppPackage = true
initial.screens = values(pkg.screens)
initial.templates = pkg.components.templates
// initial.templates = pkg.components.templates
initial.builtins = [getBuiltin("##builtin/screenslot")]
initial.appInstances = pkg.application.instances
initial.appId = pkg.application._id

View file

@ -36,7 +36,7 @@
const componentDefinition = components[component._component];
events = Object.keys(componentDefinition.props)
.filter(
propName => componentDefinition.props[propName].type === EVENT_TYPE
propName => componentDefinition.props[propName] === EVENT_TYPE
)
.map(propName => ({
name: propName,

View file

@ -66,7 +66,7 @@ import {
// const isEventList = e => isArray(e) && every(isEvent)(e)
// // const EMPTY_STATE = () => ({ [BB_STATE_BINDINGPATH]: "" });
// const EMPTY_STATE = () => ({ [BB_STATE_BINDINGPATH]: "" });
// export const types = {
// string: propType("", isString, defaultDef("string")),

View file

@ -56,7 +56,7 @@ export default {
commonProps: {},
children: [
{
_component: "@budibase/standard-components/textfield",
_component: "@budibase/standard-components/input",
name: "Textfield",
description: "A textfield component that allows the user to input text.",
icon: 'ri-edit-box-line',
@ -147,6 +147,7 @@ export default {
children: [
{
name: 'Table',
_component: "@budibase/materialdesign-components/Datatable",
description: 'A component that generates a table from your data.',
icon: 'ri-archive-drawer-fill',
commonProps: {},

View file

@ -10,8 +10,6 @@
// Get Package and set store
export let application
let ready = false
let promise = getPackage()
async function getPackage() {
@ -62,7 +60,7 @@
<span
class:active={false}
class="topnavitemright"
on:click={() => console.log}>
on:click={() => location = `/${application}`}>
<PreviewIcon />
</span>
</div>

View file

@ -12,11 +12,6 @@ export const createApp = (
uiFunctions,
window
) => {
// const coreApi = createCoreApi(backendDefinition, user)
// backendDefinition.hierarchy = coreApi.templateApi.constructHierarchy(
// backendDefinition.hierarchy
// )
let routeTo
let currentUrl
let screenStateManager

View file

@ -40,12 +40,12 @@ export const attachChildren = initialiseOpts => (htmlElement, options) => {
if (!componentName || !libName) return
const componentConstructor = componentLibraries[libName][componentName]
const ComponentConstructor = componentLibraries[libName][componentName]
const childNodesThisIteration = prepareRenderComponent({
props: childProps,
parentNode: treeNode,
componentConstructor,
ComponentConstructor,
uiFunctions,
htmlElement,
anchor,

View file

@ -1,5 +1,5 @@
export const prepareRenderComponent = ({
componentConstructor,
ComponentConstructor,
uiFunctions,
htmlElement,
anchor,
@ -26,7 +26,7 @@ export const prepareRenderComponent = ({
nodesToRender.push(thisNode)
thisNode.render = initialProps => {
thisNode.component = new componentConstructor({
thisNode.component = new ComponentConstructor({
target: htmlElement,
props: initialProps,
hydrate: false,

View file

@ -1,12 +0,0 @@
{
"presets": ["@babel/preset-env"],
"sourceMaps": "inline",
"retainLines": true,
"plugins": [
["@babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}

View file

@ -1,43 +0,0 @@
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
.eslintcache
# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
node_modules
node_modules_ubuntu
node_modules_windows
# OSX
.DS_Store
# flow-typed
flow-typed/npm/*
!flow-typed/npm/module_vx.x.x.js
.idea
npm-debug.log.*
lib

View file

@ -1,2 +0,0 @@
*
!dist/*

View file

@ -1,11 +0,0 @@
sudo: required
notifications:
slack: budibase:Nx2QNi9CP87Nn7ah2A4Qdzyy
script:
- npm install
- npm install -g jest
- node node_modules/eslint/bin/eslint src/**/*.js
- jest

View file

@ -1,14 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}\\index.js"
}
]
}

View file

@ -1,22 +0,0 @@
### Contributing to budibase-core
* The contributors are listed in [AUTHORS.md](https://github.com/budibase/budibase-core/blob/master/AUTHORS.md) (add yourself).
* This project uses a modified version of the MPLv2 license, see [LICENSE](https://github.com/budibase/budibase-core/blob/master/LICENSE).
* We use the [C4 (Collective Code Construction Contract)](https://rfc.zeromq.org/spec:42/C4/) process for contributions.
Please read this if you are unfamiliar with it.
* Please maintain the existing code style.
* Please try to keep your commits small and focussed.
* If the project diverges from your branch, please rebase instead of merging. This makes the commit graph easier to read.
#### p.S...
I am using contribution guidelines from the fantastic [ZeroMQ](https://github.com/zeromq) community. If you are interested why, it's because I believe in the ethos laid out by this community, and written about in depth in the book ["Social Architecture"](https://www.amazon.com/Social-Architecture-Building-line-Communities/dp/1533112452) by Pieter Hintjens.
I am very much open to evolving this to suit our needs.
Love from [Mike](https://github.com/mikebudi).

View file

@ -1,373 +0,0 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View file

@ -1,129 +0,0 @@
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = exports.apiWrapperSync = exports.apiWrapper = void 0;var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _fp = require("lodash/fp");
var _shortid = require("shortid");
var _errors = require("./errors");
var apiWrapper = /*#__PURE__*/function () {var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(
app,
eventNamespace,
isAuthorized,
eventContext,
func) {var startDate,elapsed,_len,params,_key,result,_args = arguments;return _regenerator["default"].wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
pushCallStack(app, eventNamespace);if (
isAuthorized(app)) {_context.next = 4;break;}
handleNotAuthorized(app, eventContext, eventNamespace);return _context.abrupt("return");case 4:
startDate = Date.now();
elapsed = function elapsed() {return Date.now() - startDate;};_context.prev = 6;_context.next = 9;return (
app.publish(eventNamespace.onBegin, eventContext));case 9:for (_len = _args.length, params = new Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) {params[_key - 5] = _args[_key];}_context.next = 12;return (
func.apply(void 0, params));case 12:result = _context.sent;_context.next = 15;return (
publishComplete(app, eventContext, eventNamespace, elapsed, result));case 15:return _context.abrupt("return",
result);case 18:_context.prev = 18;_context.t0 = _context["catch"](6);_context.next = 22;return (
publishError(app, eventContext, eventNamespace, elapsed, _context.t0));case 22:throw _context.t0;case 23:case "end":return _context.stop();}}}, _callee, null, [[6, 18]]);}));return function apiWrapper(_x, _x2, _x3, _x4, _x5) {return _ref.apply(this, arguments);};}();exports.apiWrapper = apiWrapper;
var apiWrapperSync = function apiWrapperSync(
app,
eventNamespace,
isAuthorized,
eventContext,
func)
{
pushCallStack(app, eventNamespace);
if (!isAuthorized(app)) {
handleNotAuthorized(app, eventContext, eventNamespace);
return;
}
var startDate = Date.now();
var elapsed = function elapsed() {return Date.now() - startDate;};
try {
app.publish(eventNamespace.onBegin, eventContext);for (var _len2 = arguments.length, params = new Array(_len2 > 5 ? _len2 - 5 : 0), _key2 = 5; _key2 < _len2; _key2++) {params[_key2 - 5] = arguments[_key2];}
var result = func.apply(void 0, params);
publishComplete(app, eventContext, eventNamespace, elapsed, result);
return result;
} catch (error) {
publishError(app, eventContext, eventNamespace, elapsed, error);
throw error;
}
};exports.apiWrapperSync = apiWrapperSync;
var handleNotAuthorized = function handleNotAuthorized(app, eventContext, eventNamespace) {
var err = new _errors.UnauthorisedError("Unauthorized: ".concat(eventNamespace));
publishError(app, eventContext, eventNamespace, function () {return 0;}, err);
throw err;
};
var pushCallStack = function pushCallStack(app, eventNamespace, seedCallId) {
var callId = (0, _shortid.generate)();
var createCallStack = function createCallStack() {return {
seedCallId: !(0, _fp.isUndefined)(seedCallId) ? seedCallId : callId,
threadCallId: callId,
stack: [] };};
if ((0, _fp.isUndefined)(app.calls)) {
app.calls = createCallStack();
}
app.calls.stack.push({
namespace: eventNamespace,
callId: callId });
};
var popCallStack = function popCallStack(app) {
app.calls.stack.pop();
if (app.calls.stack.length === 0) {
delete app.calls;
}
};
var publishError = /*#__PURE__*/function () {var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(
app,
eventContext,
eventNamespace,
elapsed,
err) {var ctx;return _regenerator["default"].wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
ctx = (0, _fp.cloneDeep)(eventContext);
ctx.error = err;
ctx.elapsed = elapsed();_context2.next = 5;return (
app.publish(eventNamespace.onError, ctx));case 5:
popCallStack(app);case 6:case "end":return _context2.stop();}}}, _callee2);}));return function publishError(_x6, _x7, _x8, _x9, _x10) {return _ref2.apply(this, arguments);};}();
var publishComplete = /*#__PURE__*/function () {var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(
app,
eventContext,
eventNamespace,
elapsed,
result) {var endcontext;return _regenerator["default"].wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
endcontext = (0, _fp.cloneDeep)(eventContext);
endcontext.result = result;
endcontext.elapsed = elapsed();_context3.next = 5;return (
app.publish(eventNamespace.onComplete, endcontext));case 5:
popCallStack(app);return _context3.abrupt("return",
result);case 7:case "end":return _context3.stop();}}}, _callee3);}));return function publishComplete(_x11, _x12, _x13, _x14, _x15) {return _ref3.apply(this, arguments);};}();var _default =
apiWrapper;exports["default"] = _default;
//# sourceMappingURL=apiWrapper.js.map

File diff suppressed because one or more lines are too long

View file

@ -1,27 +0,0 @@
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.compileCode = void 0;var _compilerUtil = require("@nx-js/compiler-util");
var _fp = require("lodash/fp");
var compileCode = function compileCode(code) {
var func;
var safeCode;
if ((0, _fp.includes)("return ")(code)) {
safeCode = code;
} else {
var trimmed = code.trim();
trimmed = trimmed.endsWith(";") ?
trimmed.substring(0, trimmed.length - 1) :
trimmed;
safeCode = "return (".concat(trimmed, ")");
}
try {
func = (0, _compilerUtil.compileCode)(safeCode);
} catch (e) {
e.message = "Error compiling code : ".concat(code, " : ").concat(e.message);
throw e;
}
return func;
};exports.compileCode = compileCode;
//# sourceMappingURL=compileCode.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../src/common/compileCode.js"],"names":["compileCode","code","func","safeCode","trimmed","trim","endsWith","substring","length","e","message"],"mappings":"wGAAA;AACA;;AAEO,IAAMA,WAAW,GAAG,SAAdA,WAAc,CAAAC,IAAI,EAAI;AACjC,MAAIC,IAAJ;AACA,MAAIC,QAAJ;;AAEA,MAAI,kBAAS,SAAT,EAAoBF,IAApB,CAAJ,EAA+B;AAC7BE,IAAAA,QAAQ,GAAGF,IAAX;AACD,GAFD,MAEO;AACL,QAAIG,OAAO,GAAGH,IAAI,CAACI,IAAL,EAAd;AACAD,IAAAA,OAAO,GAAGA,OAAO,CAACE,QAAR,CAAiB,GAAjB;AACNF,IAAAA,OAAO,CAACG,SAAR,CAAkB,CAAlB,EAAqBH,OAAO,CAACI,MAAR,GAAiB,CAAtC,CADM;AAENJ,IAAAA,OAFJ;AAGAD,IAAAA,QAAQ,qBAAcC,OAAd,MAAR;AACD;;AAED,MAAI;AACFF,IAAAA,IAAI,GAAG,+BAAMC,QAAN,CAAP;AACD,GAFD,CAEE,OAAOM,CAAP,EAAU;AACVA,IAAAA,CAAC,CAACC,OAAF,oCAAsCT,IAAtC,gBAAgDQ,CAAC,CAACC,OAAlD;AACA,UAAMD,CAAN;AACD;;AAED,SAAOP,IAAP;AACD,CAtBM,C","sourcesContent":["import { compileCode as cCode } from \"@nx-js/compiler-util\"\nimport { includes } from \"lodash/fp\"\n\nexport const compileCode = code => {\n let func\n let safeCode\n\n if (includes(\"return \")(code)) {\n safeCode = code\n } else {\n let trimmed = code.trim()\n trimmed = trimmed.endsWith(\";\")\n ? trimmed.substring(0, trimmed.length - 1)\n : trimmed\n safeCode = `return (${trimmed})`\n }\n\n try {\n func = cCode(safeCode)\n } catch (e) {\n e.message = `Error compiling code : ${code} : ${e.message}`\n throw e\n }\n\n return func\n}\n"],"file":"compileCode.js"}

View file

@ -1,34 +0,0 @@
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorisedError = exports.BadRequestError = void 0;var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));function _createSuper(Derived) {return function () {var Super = (0, _getPrototypeOf2["default"])(Derived),result;if (_isNativeReflectConstruct()) {var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor;result = Reflect.construct(Super, arguments, NewTarget);} else {result = Super.apply(this, arguments);}return (0, _possibleConstructorReturn2["default"])(this, result);};}function _isNativeReflectConstruct() {if (typeof Reflect === "undefined" || !Reflect.construct) return false;if (Reflect.construct.sham) return false;if (typeof Proxy === "function") return true;try {Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));return true;} catch (e) {return false;}}var BadRequestError = /*#__PURE__*/function (_Error) {(0, _inherits2["default"])(BadRequestError, _Error);var _super = _createSuper(BadRequestError);
function BadRequestError(message) {var _this;(0, _classCallCheck2["default"])(this, BadRequestError);
_this = _super.call(this, message);
_this.httpStatusCode = 400;return _this;
}return BadRequestError;}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));exports.BadRequestError = BadRequestError;var
UnauthorisedError = /*#__PURE__*/function (_Error2) {(0, _inherits2["default"])(UnauthorisedError, _Error2);var _super2 = _createSuper(UnauthorisedError);
function UnauthorisedError(message) {var _this2;(0, _classCallCheck2["default"])(this, UnauthorisedError);
_this2 = _super2.call(this, message);
_this2.httpStatusCode = 401;return _this2;
}return UnauthorisedError;}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));exports.UnauthorisedError = UnauthorisedError;var
ForbiddenError = /*#__PURE__*/function (_Error3) {(0, _inherits2["default"])(ForbiddenError, _Error3);var _super3 = _createSuper(ForbiddenError);
function ForbiddenError(message) {var _this3;(0, _classCallCheck2["default"])(this, ForbiddenError);
_this3 = _super3.call(this, message);
_this3.httpStatusCode = 403;return _this3;
}return ForbiddenError;}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));exports.ForbiddenError = ForbiddenError;var
NotFoundError = /*#__PURE__*/function (_Error4) {(0, _inherits2["default"])(NotFoundError, _Error4);var _super4 = _createSuper(NotFoundError);
function NotFoundError(message) {var _this4;(0, _classCallCheck2["default"])(this, NotFoundError);
_this4 = _super4.call(this, message);
_this4.httpStatusCode = 404;return _this4;
}return NotFoundError;}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));exports.NotFoundError = NotFoundError;var
ConflictError = /*#__PURE__*/function (_Error5) {(0, _inherits2["default"])(ConflictError, _Error5);var _super5 = _createSuper(ConflictError);
function ConflictError(message) {var _this5;(0, _classCallCheck2["default"])(this, ConflictError);
_this5 = _super5.call(this, message);
_this5.httpStatusCode = 409;return _this5;
}return ConflictError;}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error));exports.ConflictError = ConflictError;
//# sourceMappingURL=errors.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../src/common/errors.js"],"names":["BadRequestError","message","httpStatusCode","Error","UnauthorisedError","ForbiddenError","NotFoundError","ConflictError"],"mappings":"i9CAAaA,e;AACX,2BAAYC,OAAZ,EAAqB;AACnB,8BAAMA,OAAN;AACA,UAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,yEAJkCC,K;;;AAOxBC,iB;AACX,6BAAYH,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,2EAJoCC,K;;;AAO1BE,c;AACX,0BAAYJ,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,wEAJiCC,K;;;AAOvBG,a;AACX,yBAAYL,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,uEAJgCC,K;;;AAOtBI,a;AACX,yBAAYN,OAAZ,EAAqB;AACnB,gCAAMA,OAAN;AACA,WAAKC,cAAL,GAAsB,GAAtB,CAFmB;AAGpB,G,uEAJgCC,K","sourcesContent":["export class BadRequestError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 400\n }\n}\n\nexport class UnauthorisedError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 401\n }\n}\n\nexport class ForbiddenError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 403\n }\n}\n\nexport class NotFoundError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 404\n }\n}\n\nexport class ConflictError extends Error {\n constructor(message) {\n super(message)\n this.httpStatusCode = 409\n }\n}\n"],"file":"errors.js"}

View file

@ -1,28 +0,0 @@
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = exports.createEventAggregator = void 0;var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _fp = require("lodash/fp");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}
var publish = function publish(handlers) {return /*#__PURE__*/function () {var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(eventName) {var context,_iterator,_step,handler,_args = arguments;return _regenerator["default"].wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:context = _args.length > 1 && _args[1] !== undefined ? _args[1] : {};if (
(0, _fp.has)(eventName)(handlers)) {_context.next = 3;break;}return _context.abrupt("return");case 3:_iterator = _createForOfIteratorHelper(
handlers[eventName]);_context.prev = 4;_iterator.s();case 6:if ((_step = _iterator.n()).done) {_context.next = 12;break;}handler = _step.value;_context.next = 10;return (
handler(eventName, context));case 10:_context.next = 6;break;case 12:_context.next = 17;break;case 14:_context.prev = 14;_context.t0 = _context["catch"](4);_iterator.e(_context.t0);case 17:_context.prev = 17;_iterator.f();return _context.finish(17);case 20:case "end":return _context.stop();}}}, _callee, null, [[4, 14, 17, 20]]);}));return function (_x) {return _ref.apply(this, arguments);};}();};
var subscribe = function subscribe(handlers) {return function (eventName, handler) {
if (!(0, _fp.has)(eventName)(handlers)) {
handlers[eventName] = [];
}
handlers[eventName].push(handler);
};};
var createEventAggregator = function createEventAggregator() {
var handlers = {};
var eventAggregator = {
publish: publish(handlers),
subscribe: subscribe(handlers) };
return eventAggregator;
};exports.createEventAggregator = createEventAggregator;var _default =
createEventAggregator;exports["default"] = _default;
//# sourceMappingURL=eventAggregator.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../src/common/eventAggregator.js"],"names":["publish","handlers","eventName","context","handler","subscribe","push","createEventAggregator","eventAggregator"],"mappings":"iZAAA,+B;;AAEA,IAAMA,OAAO,GAAG,SAAVA,OAAU,CAAAC,QAAQ,6HAAI,iBAAOC,SAAP,oLAAkBC,OAAlB,2DAA4B,EAA5B;AACrB,2BAAID,SAAJ,EAAeD,QAAf,CADqB;;AAGJA,cAAAA,QAAQ,CAACC,SAAD,CAHJ,sGAGfE,OAHe;AAIlBA,gBAAAA,OAAO,CAACF,SAAD,EAAYC,OAAZ,CAJW,gTAAJ,mEAAxB;;;;AAQA,IAAME,SAAS,GAAG,SAAZA,SAAY,CAAAJ,QAAQ,UAAI,UAACC,SAAD,EAAYE,OAAZ,EAAwB;AACpD,QAAI,CAAC,aAAIF,SAAJ,EAAeD,QAAf,CAAL,EAA+B;AAC7BA,MAAAA,QAAQ,CAACC,SAAD,CAAR,GAAsB,EAAtB;AACD;AACDD,IAAAA,QAAQ,CAACC,SAAD,CAAR,CAAoBI,IAApB,CAAyBF,OAAzB;AACD,GALyB,EAA1B;;AAOO,IAAMG,qBAAqB,GAAG,SAAxBA,qBAAwB,GAAM;AACzC,MAAMN,QAAQ,GAAG,EAAjB;AACA,MAAMO,eAAe,GAAG;AACtBR,IAAAA,OAAO,EAAEA,OAAO,CAACC,QAAD,CADM;AAEtBI,IAAAA,SAAS,EAAEA,SAAS,CAACJ,QAAD,CAFE,EAAxB;;AAIA,SAAOO,eAAP;AACD,CAPM,C;;AASQD,qB","sourcesContent":["import { has } from \"lodash/fp\"\n\nconst publish = handlers => async (eventName, context = {}) => {\n if (!has(eventName)(handlers)) return\n\n for (const handler of handlers[eventName]) {\n await handler(eventName, context)\n }\n}\n\nconst subscribe = handlers => (eventName, handler) => {\n if (!has(eventName)(handlers)) {\n handlers[eventName] = []\n }\n handlers[eventName].push(handler)\n}\n\nexport const createEventAggregator = () => {\n const handlers = {}\n const eventAggregator = {\n publish: publish(handlers),\n subscribe: subscribe(handlers),\n }\n return eventAggregator\n}\n\nexport default createEventAggregator\n"],"file":"eventAggregator.js"}

View file

@ -1,86 +0,0 @@
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = exports.eventsList = exports.events = void 0;var _fp = require("lodash/fp");
var commonPlus = function commonPlus(extra) {return (0, _fp.union)(["onBegin", "onComplete", "onError"])(extra);};
var common = function common() {return commonPlus([]);};
var _events = {
recordApi: {
save: commonPlus(["onInvalid", "onRecordUpdated", "onRecordCreated"]),
"delete": common(),
getContext: common(),
getNew: common(),
load: common(),
validate: common(),
uploadFile: common(),
downloadFile: common() },
indexApi: {
buildIndex: common(),
listItems: common(),
"delete": common(),
aggregates: common() },
collectionApi: {
getAllowedRecordTypes: common(),
initialise: common(),
"delete": common() },
authApi: {
authenticate: common(),
authenticateTemporaryAccess: common(),
createTemporaryAccess: common(),
createUser: common(),
enableUser: common(),
disableUser: common(),
loadAccessLevels: common(),
getNewAccessLevel: common(),
getNewUser: common(),
getNewUserAuth: common(),
getUsers: common(),
saveAccessLevels: common(),
isAuthorized: common(),
changeMyPassword: common(),
setPasswordFromTemporaryCode: common(),
scorePassword: common(),
isValidPassword: common(),
validateUser: common(),
validateAccessLevels: common(),
setUserAccessLevels: common() },
templateApi: {
saveApplicationHierarchy: common(),
saveActionsAndTriggers: common() },
actionsApi: {
execute: common() } };
var _eventsList = [];
var makeEvent = function makeEvent(area, method, name) {return "".concat(area, ":").concat(method, ":").concat(name);};var _loop = function _loop(
areaKey) {var _loop2 = function _loop2(
_methodKey) {
_events[areaKey][_methodKey] = (0, _fp.reduce)(function (obj, s) {
obj[s] = makeEvent(areaKey, _methodKey, s);
return obj;
}, {})(_events[areaKey][_methodKey]);};for (var _methodKey in _events[areaKey]) {_loop2(_methodKey);
}};for (var areaKey in _events) {_loop(areaKey);
}
for (var _areaKey in _events) {
for (var methodKey in _events[_areaKey]) {
for (var name in _events[_areaKey][methodKey]) {
_eventsList.push(_events[_areaKey][methodKey][name]);
}
}
}
var events = _events;exports.events = events;
var eventsList = _eventsList;exports.eventsList = eventsList;var _default =
{ events: _events, eventsList: _eventsList };exports["default"] = _default;
//# sourceMappingURL=events.js.map

File diff suppressed because one or more lines are too long

View file

@ -1,307 +0,0 @@
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });Object.defineProperty(exports, "events", { enumerable: true, get: function get() {return _events.events;} });exports["default"] = exports.retry = exports.pause = exports.pushAll = exports.isArrayOfString = exports.toNumberOrNull = exports.toBoolOrNull = exports.toDateOrNull = exports.isSafeInteger = exports.awEx = exports.getHashCode = exports.contains = exports.StartsWith = exports.memberMatches = exports.defaultCase = exports.isOneOf = exports.isValue = exports.switchCase = exports.handleErrorWithUndefined = exports.handleErrorWith = exports.executesWithoutException = exports.causesException = exports.tryAwaitOrIgnore = exports.tryOrIgnore = exports.defineError = exports.tryAwaitOr = exports.tryOr = exports.isNonEmptyString = exports.isNonEmptyArray = exports.isAsync = exports.isNotEmpty = exports.all = exports.none = exports.mapIfSomethingOrBlank = exports.mapIfSomethingOrDefault = exports.somethingOrDefault = exports.somethingOrGetDefault = exports.isNothingOrEmpty = exports.isNothing = exports.isSomething = exports.insensitiveEquals = exports.anyTrue = exports.allTrue = exports.isNotNaN = exports.isNonNull = exports.isDefined = exports.not = exports.getOrDefault = exports.ifExists = exports.getIndexKeyFromFileKey = exports.dirIndex = exports.appDefinitionFile = exports.templateDefinitions = exports.fieldDefinitions = exports.configFolder = exports.getFileFromKey = exports.getDirFomKey = exports.splitKey = exports.joinKey = exports.safeKey = exports.keySep = exports.$ = exports.$$ = void 0;var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _lodash = require("lodash");
var _fp = require("lodash/fp");
var _events = require("./events.js");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}
// this is the combinator function
var $$ = function $$() {for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {funcs[_key] = arguments[_key];}return function (arg) {return (0, _lodash.flow)(funcs)(arg);};};
// this is the pipe function
exports.$$ = $$;var $ = function $(arg, funcs) {return $$.apply(void 0, (0, _toConsumableArray2["default"])(funcs))(arg);};exports.$ = $;
var keySep = "/";exports.keySep = keySep;
var trimKeySep = function trimKeySep(str) {return (0, _lodash.trim)(str, keySep);};
var splitByKeySep = function splitByKeySep(str) {return (0, _fp.split)(keySep)(str);};
var safeKey = function safeKey(key) {return (
(0, _lodash.replace)("".concat(keySep).concat(trimKeySep(key)), "".concat(keySep).concat(keySep), keySep));};exports.safeKey = safeKey;
var joinKey = function joinKey() {for (var _len2 = arguments.length, strs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {strs[_key2] = arguments[_key2];}
var paramsOrArray = strs.length === 1 & (0, _fp.isArray)(strs[0]) ? strs[0] : strs;
return $(paramsOrArray, [
(0, _fp.filter)(function (s) {return !(0, _fp.isUndefined)(s) && !(0, _fp.isNull)(s) && s.toString().length > 0;}),
(0, _fp.join)(keySep),
safeKey]);
};exports.joinKey = joinKey;
var splitKey = $$(trimKeySep, splitByKeySep);exports.splitKey = splitKey;
var getDirFomKey = $$(splitKey, _lodash.dropRight, function (p) {return joinKey.apply(void 0, (0, _toConsumableArray2["default"])(p));});exports.getDirFomKey = getDirFomKey;
var getFileFromKey = $$(splitKey, _lodash.takeRight, _lodash.head);exports.getFileFromKey = getFileFromKey;
var configFolder = "".concat(keySep, ".config");exports.configFolder = configFolder;
var fieldDefinitions = joinKey(configFolder, "fields.json");exports.fieldDefinitions = fieldDefinitions;
var templateDefinitions = joinKey(configFolder, "templates.json");exports.templateDefinitions = templateDefinitions;
var appDefinitionFile = joinKey(configFolder, "appDefinition.json");exports.appDefinitionFile = appDefinitionFile;
var dirIndex = function dirIndex(folderPath) {return (
joinKey.apply(void 0, [configFolder, "dir"].concat((0, _toConsumableArray2["default"])(splitKey(folderPath)), ["dir.idx"])));};exports.dirIndex = dirIndex;
var getIndexKeyFromFileKey = $$(getDirFomKey, dirIndex);exports.getIndexKeyFromFileKey = getIndexKeyFromFileKey;
var ifExists = function ifExists(val, exists, notExists) {return (
(0, _fp.isUndefined)(val) ?
(0, _fp.isUndefined)(notExists) ?
function () {}() :
notExists() :
exists());};exports.ifExists = ifExists;
var getOrDefault = function getOrDefault(val, defaultVal) {return (
ifExists(
val,
function () {return val;},
function () {return defaultVal;}));};exports.getOrDefault = getOrDefault;
var not = function not(func) {return function (val) {return !func(val);};};exports.not = not;
var isDefined = not(_fp.isUndefined);exports.isDefined = isDefined;
var isNonNull = not(_fp.isNull);exports.isNonNull = isNonNull;
var isNotNaN = not(_fp.isNaN);exports.isNotNaN = isNotNaN;
var allTrue = function allTrue() {for (var _len3 = arguments.length, funcArgs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {funcArgs[_key3] = arguments[_key3];}return function (val) {return (
(0, _fp.reduce)(
function (result, conditionFunc) {return (
((0, _fp.isNull)(result) || result == true) && conditionFunc(val));},
null)(
funcArgs));};};exports.allTrue = allTrue;
var anyTrue = function anyTrue() {for (var _len4 = arguments.length, funcArgs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {funcArgs[_key4] = arguments[_key4];}return function (val) {return (
(0, _fp.reduce)(
function (result, conditionFunc) {return result == true || conditionFunc(val);},
null)(
funcArgs));};};exports.anyTrue = anyTrue;
var insensitiveEquals = function insensitiveEquals(str1, str2) {return (
str1.trim().toLowerCase() === str2.trim().toLowerCase());};exports.insensitiveEquals = insensitiveEquals;
var isSomething = allTrue(isDefined, isNonNull, isNotNaN);exports.isSomething = isSomething;
var isNothing = not(isSomething);exports.isNothing = isNothing;
var isNothingOrEmpty = function isNothingOrEmpty(v) {return isNothing(v) || (0, _fp.isEmpty)(v);};exports.isNothingOrEmpty = isNothingOrEmpty;
var somethingOrGetDefault = function somethingOrGetDefault(getDefaultFunc) {return function (val) {return (
isSomething(val) ? val : getDefaultFunc());};};exports.somethingOrGetDefault = somethingOrGetDefault;
var somethingOrDefault = function somethingOrDefault(val, defaultVal) {return (
somethingOrGetDefault((0, _fp.constant)(defaultVal))(val));};exports.somethingOrDefault = somethingOrDefault;
var mapIfSomethingOrDefault = function mapIfSomethingOrDefault(mapFunc, defaultVal) {return function (val) {return (
isSomething(val) ? mapFunc(val) : defaultVal);};};exports.mapIfSomethingOrDefault = mapIfSomethingOrDefault;
var mapIfSomethingOrBlank = function mapIfSomethingOrBlank(mapFunc) {return (
mapIfSomethingOrDefault(mapFunc, ""));};exports.mapIfSomethingOrBlank = mapIfSomethingOrBlank;
var none = function none(predicate) {return function (collection) {return !(0, _fp.some)(predicate)(collection);};};exports.none = none;
var all = function all(predicate) {return function (collection) {return (
none(function (v) {return !predicate(v);})(collection));};};exports.all = all;
var isNotEmpty = function isNotEmpty(ob) {return !(0, _fp.isEmpty)(ob);};exports.isNotEmpty = isNotEmpty;
var isAsync = function isAsync(fn) {return fn.constructor.name === "AsyncFunction";};exports.isAsync = isAsync;
var isNonEmptyArray = allTrue(_fp.isArray, isNotEmpty);exports.isNonEmptyArray = isNonEmptyArray;
var isNonEmptyString = allTrue(_fp.isString, isNotEmpty);exports.isNonEmptyString = isNonEmptyString;
var tryOr = function tryOr(failFunc) {return function (func) {
try {for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {args[_key5 - 1] = arguments[_key5];}
return func.apply.apply(func, [null].concat(args));
} catch (_) {
return failFunc();
}
};};exports.tryOr = tryOr;
var tryAwaitOr = function tryAwaitOr(failFunc) {return /*#__PURE__*/function () {var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(func) {var _len6,args,_key6,_args = arguments;return _regenerator["default"].wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:_context.prev = 0;for (_len6 = _args.length, args = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {args[_key6 - 1] = _args[_key6];}_context.next = 4;return (
func.apply.apply(func, [null].concat(args)));case 4:return _context.abrupt("return", _context.sent);case 7:_context.prev = 7;_context.t0 = _context["catch"](0);_context.next = 11;return (
failFunc());case 11:return _context.abrupt("return", _context.sent);case 12:case "end":return _context.stop();}}}, _callee, null, [[0, 7]]);}));return function (_x) {return _ref.apply(this, arguments);};}();};exports.tryAwaitOr = tryAwaitOr;
var defineError = function defineError(func, errorPrefix) {
try {
return func();
} catch (err) {
err.message = "".concat(errorPrefix, " : ").concat(err.message);
throw err;
}
};exports.defineError = defineError;
var tryOrIgnore = tryOr(function () {});exports.tryOrIgnore = tryOrIgnore;
var tryAwaitOrIgnore = tryAwaitOr( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {return _regenerator["default"].wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:case "end":return _context2.stop();}}}, _callee2);})));exports.tryAwaitOrIgnore = tryAwaitOrIgnore;
var causesException = function causesException(func) {
try {
func();
return false;
} catch (e) {
return true;
}
};exports.causesException = causesException;
var executesWithoutException = function executesWithoutException(func) {return !causesException(func);};exports.executesWithoutException = executesWithoutException;
var handleErrorWith = function handleErrorWith(returnValInError) {return (
tryOr((0, _fp.constant)(returnValInError)));};exports.handleErrorWith = handleErrorWith;
var handleErrorWithUndefined = handleErrorWith(undefined);exports.handleErrorWithUndefined = handleErrorWithUndefined;
var switchCase = function switchCase() {for (var _len7 = arguments.length, cases = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {cases[_key7] = arguments[_key7];}return function (value) {
var nextCase = function nextCase() {return (0, _lodash.head)(cases)[0](value);};
var nextResult = function nextResult() {return (0, _lodash.head)(cases)[1](value);};
if ((0, _fp.isEmpty)(cases)) return; // undefined
if (nextCase() === true) return nextResult();
return switchCase.apply(void 0, (0, _toConsumableArray2["default"])((0, _lodash.tail)(cases)))(value);
};};exports.switchCase = switchCase;
var isValue = function isValue(val1) {return function (val2) {return val1 === val2;};};exports.isValue = isValue;
var isOneOf = function isOneOf() {for (var _len8 = arguments.length, vals = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {vals[_key8] = arguments[_key8];}return function (val) {return (0, _fp.includes)(val)(vals);};};exports.isOneOf = isOneOf;
var defaultCase = (0, _fp.constant)(true);exports.defaultCase = defaultCase;
var memberMatches = function memberMatches(member, match) {return function (obj) {return match(obj[member]);};};exports.memberMatches = memberMatches;
var StartsWith = function StartsWith(searchFor) {return function (searchIn) {return (
(0, _lodash.startsWith)(searchIn, searchFor));};};exports.StartsWith = StartsWith;
var contains = function contains(val) {return function (array) {return (0, _lodash.findIndex)(array, function (v) {return v === val;}) > -1;};};exports.contains = contains;
var getHashCode = function getHashCode(s) {
var hash = 0;
var i;
var _char;
var l;
if (s.length == 0) return hash;
for (i = 0, l = s.length; i < l; i++) {
_char = s.charCodeAt(i);
hash = (hash << 5) - hash + _char;
hash |= 0; // Convert to 32bit integer
}
// converting to string, but dont want a "-" prefixed
if (hash < 0) {
return "n".concat((hash * -1).toString());
}
return hash.toString();
};
// thanks to https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/
exports.getHashCode = getHashCode;var awEx = /*#__PURE__*/function () {var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(promise) {var result;return _regenerator["default"].wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:_context3.prev = 0;_context3.next = 3;return (
promise);case 3:result = _context3.sent;return _context3.abrupt("return",
[undefined, result]);case 7:_context3.prev = 7;_context3.t0 = _context3["catch"](0);return _context3.abrupt("return",
[_context3.t0, undefined]);case 10:case "end":return _context3.stop();}}}, _callee3, null, [[0, 7]]);}));return function awEx(_x2) {return _ref3.apply(this, arguments);};}();exports.awEx = awEx;
var isSafeInteger = function isSafeInteger(n) {return (
(0, _fp.isInteger)(n) &&
n <= Number.MAX_SAFE_INTEGER &&
n >= 0 - Number.MAX_SAFE_INTEGER);};exports.isSafeInteger = isSafeInteger;
var toDateOrNull = function toDateOrNull(s) {return (
(0, _fp.isNull)(s) ? null : (0, _fp.isDate)(s) ? s : new Date(s));};exports.toDateOrNull = toDateOrNull;
var toBoolOrNull = function toBoolOrNull(s) {return (0, _fp.isNull)(s) ? null : s === "true" || s === true;};exports.toBoolOrNull = toBoolOrNull;
var toNumberOrNull = function toNumberOrNull(s) {return (0, _fp.isNull)(s) ? null : (0, _fp.toNumber)(s);};exports.toNumberOrNull = toNumberOrNull;
var isArrayOfString = function isArrayOfString(opts) {return (0, _fp.isArray)(opts) && all(_fp.isString)(opts);};exports.isArrayOfString = isArrayOfString;
var pushAll = function pushAll(target, items) {var _iterator = _createForOfIteratorHelper(
items),_step;try {for (_iterator.s(); !(_step = _iterator.n()).done;) {var i = _step.value;target.push(i);}} catch (err) {_iterator.e(err);} finally {_iterator.f();}
};exports.pushAll = pushAll;
var pause = /*#__PURE__*/function () {var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(duration) {return _regenerator["default"].wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:return _context4.abrupt("return",
new Promise(function (res) {return setTimeout(res, duration);}));case 1:case "end":return _context4.stop();}}}, _callee4);}));return function pause(_x3) {return _ref4.apply(this, arguments);};}();exports.pause = pause;
var retry = /*#__PURE__*/function () {var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(fn, retries, delay) {var _len9,args,_key9,_args6 = arguments;return _regenerator["default"].wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:for (_len9 = _args6.length, args = new Array(_len9 > 3 ? _len9 - 3 : 0), _key9 = 3; _key9 < _len9; _key9++) {args[_key9 - 3] = _args6[_key9];}_context6.prev = 1;_context6.next = 4;return (
fn.apply(void 0, args));case 4:return _context6.abrupt("return", _context6.sent);case 7:_context6.prev = 7;_context6.t0 = _context6["catch"](1);if (!(
retries > 1)) {_context6.next = 13;break;}_context6.next = 12;return (
pause(delay).then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(
function _callee5() {return _regenerator["default"].wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:_context5.next = 2;return retry.apply(void 0, [fn, retries - 1, delay].concat(args));case 2:return _context5.abrupt("return", _context5.sent);case 3:case "end":return _context5.stop();}}}, _callee5);}))));case 12:return _context6.abrupt("return", _context6.sent);case 13:throw _context6.t0;case 14:case "end":return _context6.stop();}}}, _callee6, null, [[1, 7]]);}));return function retry(_x4, _x5, _x6) {return _ref5.apply(this, arguments);};}();exports.retry = retry;var _default =
{
ifExists: ifExists,
getOrDefault: getOrDefault,
isDefined: isDefined,
isNonNull: isNonNull,
isNotNaN: isNotNaN,
allTrue: allTrue,
isSomething: isSomething,
mapIfSomethingOrDefault: mapIfSomethingOrDefault,
mapIfSomethingOrBlank: mapIfSomethingOrBlank,
configFolder: configFolder,
fieldDefinitions: fieldDefinitions,
isNothing: isNothing,
not: not,
switchCase: switchCase,
defaultCase: defaultCase,
StartsWith: StartsWith,
contains: contains,
templateDefinitions: templateDefinitions,
handleErrorWith: handleErrorWith,
handleErrorWithUndefined: handleErrorWithUndefined,
tryOr: tryOr,
tryOrIgnore: tryOrIgnore,
tryAwaitOr: tryAwaitOr,
tryAwaitOrIgnore: tryAwaitOrIgnore,
dirIndex: dirIndex,
keySep: keySep,
$: $,
$$: $$,
getDirFomKey: getDirFomKey,
getFileFromKey: getFileFromKey,
splitKey: splitKey,
somethingOrDefault: somethingOrDefault,
getIndexKeyFromFileKey: getIndexKeyFromFileKey,
joinKey: joinKey,
somethingOrGetDefault: somethingOrGetDefault,
appDefinitionFile: appDefinitionFile,
isValue: isValue,
all: all,
isOneOf: isOneOf,
memberMatches: memberMatches,
defineError: defineError,
anyTrue: anyTrue,
isNonEmptyArray: isNonEmptyArray,
causesException: causesException,
executesWithoutException: executesWithoutException,
none: none,
getHashCode: getHashCode,
awEx: awEx,
events: _events.events,
eventsList: _events.eventsList,
isNothingOrEmpty: isNothingOrEmpty,
isSafeInteger: isSafeInteger,
toNumber: _fp.toNumber,
toDate: toDateOrNull,
toBool: toBoolOrNull,
isArrayOfString: isArrayOfString,
insensitiveEquals: insensitiveEquals,
pause: pause,
retry: retry,
pushAll: pushAll };exports["default"] = _default;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View file

@ -1,15 +0,0 @@
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports.applyRule = exports.applyRuleSet = exports.validationError = exports.makerule = exports.stringNotEmpty = void 0;var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _fp = require("lodash/fp");
var _index = require("./index");function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {return Object.getOwnPropertyDescriptor(object, sym).enumerable;});keys.push.apply(keys, symbols);}return keys;}function _objectSpread(target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(Object(source), true).forEach(function (key) {(0, _defineProperty2["default"])(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(Object(source)).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}
var stringNotEmpty = function stringNotEmpty(s) {return (0, _index.isSomething)(s) && s.trim().length > 0;};exports.stringNotEmpty = stringNotEmpty;
var makerule = function makerule(field, error, isValid) {return { field: field, error: error, isValid: isValid };};exports.makerule = makerule;
var validationError = function validationError(rule, item) {return _objectSpread({}, rule, { item: item });};exports.validationError = validationError;
var applyRuleSet = function applyRuleSet(ruleSet) {return function (itemToValidate) {return (
(0, _index.$)(ruleSet, [(0, _fp.map)(applyRule(itemToValidate)), (0, _fp.filter)(_index.isSomething)]));};};exports.applyRuleSet = applyRuleSet;
var applyRule = function applyRule(itemTovalidate) {return function (rule) {return (
rule.isValid(itemTovalidate) ? null : validationError(rule, itemTovalidate));};};exports.applyRule = applyRule;
//# sourceMappingURL=validationCommon.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../src/common/validationCommon.js"],"names":["stringNotEmpty","s","trim","length","makerule","field","error","isValid","validationError","rule","item","applyRuleSet","ruleSet","itemToValidate","applyRule","isSomething","itemTovalidate"],"mappings":"wXAAA;AACA,gC;;AAEO,IAAMA,cAAc,GAAG,SAAjBA,cAAiB,CAAAC,CAAC,UAAI,wBAAYA,CAAZ,KAAkBA,CAAC,CAACC,IAAF,GAASC,MAAT,GAAkB,CAAxC,EAAxB,C;;AAEA,IAAMC,QAAQ,GAAG,SAAXA,QAAW,CAACC,KAAD,EAAQC,KAAR,EAAeC,OAAf,UAA4B,EAAEF,KAAK,EAALA,KAAF,EAASC,KAAK,EAALA,KAAT,EAAgBC,OAAO,EAAPA,OAAhB,EAA5B,EAAjB,C;;AAEA,IAAMC,eAAe,GAAG,SAAlBA,eAAkB,CAACC,IAAD,EAAOC,IAAP,4BAAsBD,IAAtB,IAA4BC,IAAI,EAAJA,IAA5B,KAAxB,C;;AAEA,IAAMC,YAAY,GAAG,SAAfA,YAAe,CAAAC,OAAO,UAAI,UAAAC,cAAc;AACnD,oBAAED,OAAF,EAAW,CAAC,aAAIE,SAAS,CAACD,cAAD,CAAb,CAAD,EAAiC,gBAAOE,kBAAP,CAAjC,CAAX,CADmD,GAAlB,EAA5B,C;;AAGA,IAAMD,SAAS,GAAG,SAAZA,SAAY,CAAAE,cAAc,UAAI,UAAAP,IAAI;AAC7CA,MAAAA,IAAI,CAACF,OAAL,CAAaS,cAAb,IAA+B,IAA/B,GAAsCR,eAAe,CAACC,IAAD,EAAOO,cAAP,CADR,GAAR,EAAhC,C","sourcesContent":["import { filter, map } from \"lodash/fp\"\nimport { $, isSomething } from \"./index\"\n\nexport const stringNotEmpty = s => isSomething(s) && s.trim().length > 0\n\nexport const makerule = (field, error, isValid) => ({ field, error, isValid })\n\nexport const validationError = (rule, item) => ({ ...rule, item })\n\nexport const applyRuleSet = ruleSet => itemToValidate =>\n $(ruleSet, [map(applyRule(itemToValidate)), filter(isSomething)])\n\nexport const applyRule = itemTovalidate => rule =>\n rule.isValid(itemTovalidate) ? null : validationError(rule, itemTovalidate)\n"],"file":"validationCommon.js"}

View file

@ -1,4 +0,0 @@
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });Object.defineProperty(exports, "events", { enumerable: true, get: function get() {return _events.events;} });Object.defineProperty(exports, "safeParseField", { enumerable: true, get: function get() {return _types.safeParseField;} });Object.defineProperty(exports, "schemaValidator", { enumerable: true, get: function get() {return _schemaValidation["default"];} });var _events = require("./common/events");
var _types = require("./schema/types");
var _schemaValidation = _interopRequireDefault(require("./schemaValidation"));
//# sourceMappingURL=index.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../src/index.js"],"names":[],"mappings":"6gBAAA;AACA;AACA","sourcesContent":["export { events } from \"./common/events\";\nexport { safeParseField } from \"./schema/types\";\nexport { default as schemaValidator } from \"./schemaValidation\";"],"file":"index.js"}

View file

@ -1,22 +0,0 @@
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.createAction = exports.createTrigger = void 0;var createTrigger = function createTrigger() {return {
actionName: "",
eventName: "",
// function, has access to event context,
// returns object that is used as parameter to action
// only used if triggered by event
optionsCreator: "",
// action runs if true,
// has access to event context
condition: "" };};exports.createTrigger = createTrigger;
var createAction = function createAction() {return {
name: "",
behaviourSource: "",
// name of function in actionSource
behaviourName: "",
// parameter passed into behaviour.
// any other parms passed at runtime e.g.
// by trigger, or manually, will be merged into this
initialOptions: {} };};exports.createAction = createAction;
//# sourceMappingURL=createActions.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../src/schema/createActions.js"],"names":["createTrigger","actionName","eventName","optionsCreator","condition","createAction","name","behaviourSource","behaviourName","initialOptions"],"mappings":"iIAAO,IAAMA,aAAa,GAAG,SAAhBA,aAAgB,WAAO;AAClCC,IAAAA,UAAU,EAAE,EADsB;AAElCC,IAAAA,SAAS,EAAE,EAFuB;AAGlC;AACA;AACA;AACAC,IAAAA,cAAc,EAAE,EANkB;AAOlC;AACA;AACAC,IAAAA,SAAS,EAAE,EATuB,EAAP,EAAtB,C;;;AAYA,IAAMC,YAAY,GAAG,SAAfA,YAAe,WAAO;AACjCC,IAAAA,IAAI,EAAE,EAD2B;AAEjCC,IAAAA,eAAe,EAAE,EAFgB;AAGjC;AACAC,IAAAA,aAAa,EAAE,EAJkB;AAKjC;AACA;AACA;AACAC,IAAAA,cAAc,EAAE,EARiB,EAAP,EAArB,C","sourcesContent":["export const createTrigger = () => ({\n actionName: \"\",\n eventName: \"\",\n // function, has access to event context,\n // returns object that is used as parameter to action\n // only used if triggered by event\n optionsCreator: \"\",\n // action runs if true,\n // has access to event context\n condition: \"\",\n})\n\nexport const createAction = () => ({\n name: \"\",\n behaviourSource: \"\",\n // name of function in actionSource\n behaviourName: \"\",\n // parameter passed into behaviour.\n // any other parms passed at runtime e.g.\n // by trigger, or manually, will be merged into this\n initialOptions: {},\n})\n"],"file":"createActions.js"}

View file

@ -1,97 +0,0 @@
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports.addField = exports.validateAllFields = exports.validateField = exports.getNewField = exports.allowedTypes = exports.fieldErrors = void 0;var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _fp = require("lodash/fp");
var _common = require("../common");
var _index = require("./types/index.js");
var _validationCommon = require("../common/validationCommon");
var _errors = require("../common/errors");
var _shortid = require("shortid");
var fieldErrors = {
AddFieldValidationFailed: "Add field validation: " };exports.fieldErrors = fieldErrors;
var allowedTypes = function allowedTypes() {return (0, _fp.keys)(_index.all);};exports.allowedTypes = allowedTypes;
var getNewField = function getNewField(type) {return {
id: (0, _shortid.generate)(),
name: "", // how field is referenced internally
type: type,
typeOptions: (0, _index.getDefaultOptions)(type),
label: "", // how field is displayed
getInitialValue: "default", // function that gets value when initially created
getUndefinedValue: "default" // function that gets value when field undefined on record
};};exports.getNewField = getNewField;
var fieldRules = function fieldRules(allFields) {return [
(0, _validationCommon.makerule)("name", "field name is not set", function (f) {return (0, _common.isNonEmptyString)(f.name);}),
(0, _validationCommon.makerule)("type", "field type is not set", function (f) {return (0, _common.isNonEmptyString)(f.type);}),
(0, _validationCommon.makerule)("label", "field label is not set", function (f) {return (0, _common.isNonEmptyString)(f.label);}),
(0, _validationCommon.makerule)("getInitialValue", "getInitialValue function is not set", function (f) {return (
(0, _common.isNonEmptyString)(f.getInitialValue));}),
(0, _validationCommon.makerule)("getUndefinedValue", "getUndefinedValue function is not set", function (f) {return (
(0, _common.isNonEmptyString)(f.getUndefinedValue));}),
(0, _validationCommon.makerule)(
"name",
"field name is duplicated",
function (f) {return (0, _common.isNothingOrEmpty)(f.name) || (0, _fp.countBy)("name")(allFields)[f.name] === 1;}),
(0, _validationCommon.makerule)(
"type",
"type is unknown",
function (f) {return (0, _common.isNothingOrEmpty)(f.type) || (0, _fp.some)(function (t) {return f.type === t;})(allowedTypes());})];};
var typeOptionsRules = function typeOptionsRules(field) {
var type = _index.all[field.type];
if ((0, _common.isNothing)(type)) return [];
var def = function def(optName) {return type.optionDefinitions[optName];};
return (0, _common.$)(field.typeOptions, [
_fp.keys,
(0, _fp.filter)(function (o) {return (0, _common.isSomething)(def(o)) && (0, _common.isSomething)(def(o).isValid);}),
(0, _fp.map)(function (o) {return (
(0, _validationCommon.makerule)("typeOptions.".concat(o), "".concat(def(o).requirementDescription), function (field) {return (
def(o).isValid(field.typeOptions[o]));}));})]);
};
var validateField = function validateField(allFields) {return function (field) {
var everySingleField = (0, _fp.includes)(field)(allFields) ?
allFields : [].concat((0, _toConsumableArray2["default"])(
allFields), [field]);
return (0, _validationCommon.applyRuleSet)([].concat((0, _toConsumableArray2["default"])(
fieldRules(everySingleField)), (0, _toConsumableArray2["default"])(
typeOptionsRules(field))))(
field);
};};exports.validateField = validateField;
var validateAllFields = function validateAllFields(recordNode) {return (
(0, _common.$)(recordNode.fields, [(0, _fp.map)(validateField(recordNode.fields)), _fp.flatten]));};exports.validateAllFields = validateAllFields;
var addField = function addField(recordTemplate, field) {
if ((0, _common.isNothingOrEmpty)(field.label)) {
field.label = field.name;
}
var validationMessages = validateField([].concat((0, _toConsumableArray2["default"])(recordTemplate.fields), [field]))(
field);
if (validationMessages.length > 0) {
var errors = (0, _fp.map)(function (m) {return m.error;})(validationMessages);
throw new _errors.BadRequestError("".concat(
fieldErrors.AddFieldValidationFailed, " ").concat(errors.join(", ")));
}
recordTemplate.fields.push(field);
};exports.addField = addField;
//# sourceMappingURL=fields.js.map

File diff suppressed because one or more lines are too long

View file

@ -1,34 +0,0 @@
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.fullSchema = void 0;var fullSchema = function fullSchema(models, views) {
var findModel = function findModel(idOrName) {return (
models.find(
function (m) {return m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase();}));};
var findView = function findView(idOrName) {return (
views.find(
function (m) {return m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase();}));};
var findField = function findField(modelIdOrName, fieldName) {
var model = models.find(
function (m) {return (
m.id === modelIdOrName ||
m.name.toLowerCase() === modelIdOrName.toLowerCase());});
return model.fields.find(
function (f) {return f.name.toLowerCase() === fieldName.toLowerCase();});
};
var viewsForModel = function viewsForModel(modelId) {return views.filter(function (v) {return v.modelId === modelId;});};
return {
models: models,
views: views,
findModel: findModel,
findField: findField,
findView: findView,
viewsForModel: viewsForModel };
};exports.fullSchema = fullSchema;
//# sourceMappingURL=fullSchema.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../src/schema/fullSchema.js"],"names":["fullSchema","models","views","findModel","idOrName","find","m","id","name","toLowerCase","findView","findField","modelIdOrName","fieldName","model","fields","f","viewsForModel","modelId","filter","v"],"mappings":"uGAAO,IAAMA,UAAU,GAAG,SAAbA,UAAa,CAACC,MAAD,EAASC,KAAT,EAAmB;AAC3C,MAAMC,SAAS,GAAG,SAAZA,SAAY,CAAAC,QAAQ;AACxBH,MAAAA,MAAM,CAACI,IAAP;AACE,gBAAAC,CAAC,UAAIA,CAAC,CAACC,EAAF,KAASH,QAAT,IAAqBE,CAAC,CAACE,IAAF,CAAOC,WAAP,OAAyBL,QAAQ,CAACK,WAAT,EAAlD,EADH,CADwB,GAA1B;;;AAKA,MAAMC,QAAQ,GAAG,SAAXA,QAAW,CAAAN,QAAQ;AACvBF,MAAAA,KAAK,CAACG,IAAN;AACE,gBAAAC,CAAC,UAAIA,CAAC,CAACC,EAAF,KAASH,QAAT,IAAqBE,CAAC,CAACE,IAAF,CAAOC,WAAP,OAAyBL,QAAQ,CAACK,WAAT,EAAlD,EADH,CADuB,GAAzB;;;AAKA,MAAME,SAAS,GAAG,SAAZA,SAAY,CAACC,aAAD,EAAgBC,SAAhB,EAA8B;AAC9C,QAAMC,KAAK,GAAGb,MAAM,CAACI,IAAP;AACZ,cAAAC,CAAC;AACCA,QAAAA,CAAC,CAACC,EAAF,KAASK,aAAT;AACAN,QAAAA,CAAC,CAACE,IAAF,CAAOC,WAAP,OAAyBG,aAAa,CAACH,WAAd,EAF1B,GADW,CAAd;;AAKA,WAAOK,KAAK,CAACC,MAAN,CAAaV,IAAb;AACL,cAAAW,CAAC,UAAIA,CAAC,CAACR,IAAF,CAAOC,WAAP,OAAyBI,SAAS,CAACJ,WAAV,EAA7B,EADI,CAAP;;AAGD,GATD;;AAWA,MAAMQ,aAAa,GAAG,SAAhBA,aAAgB,CAAAC,OAAO,UAAIhB,KAAK,CAACiB,MAAN,CAAa,UAAAC,CAAC,UAAIA,CAAC,CAACF,OAAF,KAAcA,OAAlB,EAAd,CAAJ,EAA7B;;AAEA,SAAO;AACLjB,IAAAA,MAAM,EAANA,MADK;AAELC,IAAAA,KAAK,EAALA,KAFK;AAGLC,IAAAA,SAAS,EAATA,SAHK;AAILQ,IAAAA,SAAS,EAATA,SAJK;AAKLD,IAAAA,QAAQ,EAARA,QALK;AAMLO,IAAAA,aAAa,EAAbA,aANK,EAAP;;AAQD,CAhCM,C","sourcesContent":["export const fullSchema = (models, views) => {\n const findModel = idOrName =>\n models.find(\n m => m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase()\n )\n\n const findView = idOrName =>\n views.find(\n m => m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase()\n )\n\n const findField = (modelIdOrName, fieldName) => {\n const model = models.find(\n m =>\n m.id === modelIdOrName ||\n m.name.toLowerCase() === modelIdOrName.toLowerCase()\n )\n return model.fields.find(\n f => f.name.toLowerCase() === fieldName.toLowerCase()\n )\n }\n\n const viewsForModel = modelId => views.filter(v => v.modelId === modelId)\n\n return {\n models,\n views,\n findModel,\n findField,\n findView,\n viewsForModel,\n }\n}\n"],"file":"fullSchema.js"}

View file

@ -1,43 +0,0 @@
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.canDeleteModel = exports.newModel = void 0;var _shortid = require("shortid");function _createForOfIteratorHelper(o) {if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) {var i = 0;var F = function F() {};return { s: F, n: function n() {if (i >= o.length) return { done: true };return { done: false, value: o[i++] };}, e: function e(_e) {throw _e;}, f: F };}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var it,normalCompletion = true,didErr = false,err;return { s: function s() {it = o[Symbol.iterator]();}, n: function n() {var step = it.next();normalCompletion = step.done;return step;}, e: function e(_e2) {didErr = true;err = _e2;}, f: function f() {try {if (!normalCompletion && it["return"] != null) it["return"]();} finally {if (didErr) throw err;}} };}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(n);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}
var newModel = function newModel() {return {
_id: (0, _shortid.generate)(),
name: "",
type: "model",
key: "name",
schema: {
type: "object",
properties: {
name: { type: "string" } },
required: ["name"] } };};
/**
*
* @param {Array} models
* @param {string} modelId
* @returns {}
*/exports.newModel = newModel;
var canDeleteModel = function canDeleteModel(models, modelId) {
var errors = [];var _iterator = _createForOfIteratorHelper(
models),_step;try {for (_iterator.s(); !(_step = _iterator.n()).done;) {var model = _step.value;
var links = model.fields.filter(
function (f) {return f.type === "link" && f.typeOptions.modelId === modelId;});var _iterator2 = _createForOfIteratorHelper(
links),_step2;try {for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {var link = _step2.value;
errors.push("The \"".concat(
model.name, "\" model links to this model, via field \"").concat(link.name, "\""));
}} catch (err) {_iterator2.e(err);} finally {_iterator2.f();}
}} catch (err) {_iterator.e(err);} finally {_iterator.f();}
return {
errors: errors,
canDelete: errors.length > 0 };
};exports.canDeleteModel = canDeleteModel;
//# sourceMappingURL=models.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../src/schema/models.js"],"names":["newModel","_id","name","type","key","schema","properties","required","canDeleteModel","models","modelId","errors","model","links","fields","filter","f","typeOptions","link","push","canDelete","length"],"mappings":"8HAAA,kC;;AAEO,IAAMA,QAAQ,GAAG,SAAXA,QAAW,WAAO;AAC7BC,IAAAA,GAAG,EAAE,wBADwB;AAE7BC,IAAAA,IAAI,EAAE,EAFuB;AAG7BC,IAAAA,IAAI,EAAE,OAHuB;AAI7BC,IAAAA,GAAG,EAAE,MAJwB;AAK7BC,IAAAA,MAAM,EAAE;AACNF,MAAAA,IAAI,EAAE,QADA;AAENG,MAAAA,UAAU,EAAE;AACVJ,QAAAA,IAAI,EAAE,EAAEC,IAAI,EAAE,QAAR,EADI,EAFN;;AAKNI,MAAAA,QAAQ,EAAE,CAAC,MAAD,CALJ,EALqB,EAAP,EAAjB;;;;AAcP;;;;;;AAMO,IAAMC,cAAc,GAAG,SAAjBA,cAAiB,CAACC,MAAD,EAASC,OAAT,EAAqB;AACjD,MAAMC,MAAM,GAAG,EAAf,CADiD;;AAG/BF,EAAAA,MAH+B,aAGjD,oDAA0B,KAAjBG,KAAiB;AACxB,UAAMC,KAAK,GAAGD,KAAK,CAACE,MAAN,CAAaC,MAAb;AACZ,gBAAAC,CAAC,UAAIA,CAAC,CAACb,IAAF,KAAW,MAAX,IAAqBa,CAAC,CAACC,WAAF,CAAcP,OAAd,KAA0BA,OAAnD,EADW,CAAd,CADwB;;;AAKPG,MAAAA,KALO,cAKxB,uDAAwB,KAAfK,IAAe;AACtBP,UAAAA,MAAM,CAACQ,IAAP;AACUP,UAAAA,KAAK,CAACV,IADhB,uDAC+DgB,IAAI,CAAChB,IADpE;;AAGD,SATuB;AAUzB,KAbgD;;AAejD,SAAO;AACLS,IAAAA,MAAM,EAANA,MADK;AAELS,IAAAA,SAAS,EAAET,MAAM,CAACU,MAAP,GAAgB,CAFtB,EAAP;;AAID,CAnBM,C","sourcesContent":["import { generate } from \"shortid\"\n\nexport const newModel = () => ({\n _id: generate(),\n name: \"\",\n type: \"model\",\n key: \"name\",\n schema: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n },\n required: [\"name\"],\n },\n})\n\n/**\n *\n * @param {Array} models\n * @param {string} modelId\n * @returns {}\n */\nexport const canDeleteModel = (models, modelId) => {\n const errors = []\n\n for (let model of models) {\n const links = model.fields.filter(\n f => f.type === \"link\" && f.typeOptions.modelId === modelId\n )\n\n for (let link of links) {\n errors.push(\n `The \"${model.name}\" model links to this model, via field \"${link.name}\"`\n )\n }\n }\n\n return {\n errors,\n canDelete: errors.length > 0,\n }\n}\n"],"file":"models.js"}

View file

@ -1,18 +0,0 @@
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _default2 = {
isType: function isType(schema) {return (
schema.anyOf &&
schema.anyOf.filter(function (s) {return s.type === "string" && s.format === "date-time";}).
length > 0);},
fromSchema: function fromSchema(schema) {return {
type: "datetime",
"default": schema["default"] };},
toSchema: function toSchema() {return {
anyOf: [{ type: "string", format: "date-time" }, { "const": "" }],
"default": "" };},
"default": function _default() {return {
type: "datetime",
"default": "" };} };exports["default"] = _default2;
//# sourceMappingURL=datetime.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../../src/schema/types/datetime.js"],"names":["isType","schema","anyOf","filter","s","type","format","length","fromSchema","toSchema"],"mappings":"uHAAe;AACbA,EAAAA,MAAM,EAAE,gBAAAC,MAAM;AACZA,MAAAA,MAAM,CAACC,KAAP;AACAD,MAAAA,MAAM,CAACC,KAAP,CAAaC,MAAb,CAAoB,UAAAC,CAAC,UAAIA,CAAC,CAACC,IAAF,KAAW,QAAX,IAAuBD,CAAC,CAACE,MAAF,KAAa,WAAxC,EAArB;AACGC,MAAAA,MADH,GACY,CAHA,GADD;;AAMbC,EAAAA,UAAU,EAAE,oBAAAP,MAAM,UAAK;AACrBI,MAAAA,IAAI,EAAE,UADe;AAErB,iBAASJ,MAAM,WAFM,EAAL,EANL;;AAUbQ,EAAAA,QAAQ,EAAE,4BAAO;AACfP,MAAAA,KAAK,EAAE,CAAC,EAAEG,IAAI,EAAE,QAAR,EAAkBC,MAAM,EAAE,WAA1B,EAAD,EAA0C,EAAE,SAAO,EAAT,EAA1C,CADQ;AAEf,iBAAS,EAFM,EAAP,EAVG;;AAcb,aAAS,4BAAO;AACdD,MAAAA,IAAI,EAAE,UADQ;AAEd,iBAAS,EAFK,EAAP,EAdI,E","sourcesContent":["export default {\n isType: schema =>\n schema.anyOf &&\n schema.anyOf.filter(s => s.type === \"string\" && s.format === \"date-time\")\n .length > 0,\n\n fromSchema: schema => ({\n type: \"datetime\",\n default: schema.default,\n }),\n toSchema: () => ({\n anyOf: [{ type: \"string\", format: \"date-time\" }, { const: \"\" }],\n default: \"\",\n }),\n default: () => ({\n type: \"datetime\",\n default: \"\",\n }),\n}\n"],"file":"datetime.js"}

View file

@ -1,54 +0,0 @@
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports.listTypes = listTypes;exports.newField = newField;exports.fieldsToSchema = fieldsToSchema;exports.schemaToFields = schemaToFields;var _boolean2 = _interopRequireDefault(require("./boolean"));
var _datetime = _interopRequireDefault(require("./datetime"));
var _link = _interopRequireDefault(require("./link"));
var _number = _interopRequireDefault(require("./number"));
var _select = _interopRequireDefault(require("./select"));
var _text = _interopRequireDefault(require("./text"));
var allTypes = {
"boolean": _boolean2["default"],
datetime: _datetime["default"],
link: _link["default"],
number: _number["default"],
select: _select["default"],
text: _text["default"] };
function listTypes() {
return Object.keys(allTypes);
}
function newField(name, type) {
var field = allTypes[type]["default"]();
field.name = name;
field.required = false;
return field;
}
function fieldsToSchema(fields) {
var required = fields.filter(function (f) {return f.required;}).map(function (f) {return f.name;});
return {
type: "object",
required: required,
properties: fields.reduce(function (sch, field) {
sch[field.name] = allTypes[field.type].toSchema(field);
return sch;
}, {}) };
}
function schemaToFields(modelSchema) {
return Object.keys(modelSchema.properties).map(function (key) {
var schema = modelSchema.properties[key];
for (var type in allTypes) {
if (allTypes[type].isType(schema)) {
var field = allTypes[type].fromSchema(schema);
field.required = modelSchema.required.includes(key);
field.name = key;
return field;
}
}
});
}
//# sourceMappingURL=index.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../../src/schema/types/index.js"],"names":["allTypes","datetime","link","number","select","text","listTypes","Object","keys","newField","name","type","field","required","fieldsToSchema","fields","filter","f","map","properties","reduce","sch","toSchema","schemaToFields","modelSchema","key","schema","isType","fromSchema","includes"],"mappings":"0SAAA;AACA;AACA;AACA;AACA;AACA;;AAEA,IAAMA,QAAQ,GAAG;AACf,iCADe;AAEfC,EAAAA,QAAQ,EAARA,oBAFe;AAGfC,EAAAA,IAAI,EAAJA,gBAHe;AAIfC,EAAAA,MAAM,EAANA,kBAJe;AAKfC,EAAAA,MAAM,EAANA,kBALe;AAMfC,EAAAA,IAAI,EAAJA,gBANe,EAAjB;;;AASO,SAASC,SAAT,GAAqB;AAC1B,SAAOC,MAAM,CAACC,IAAP,CAAYR,QAAZ,CAAP;AACD;;AAEM,SAASS,QAAT,CAAkBC,IAAlB,EAAwBC,IAAxB,EAA8B;AACnC,MAAMC,KAAK,GAAGZ,QAAQ,CAACW,IAAD,CAAR,aAAd;AACAC,EAAAA,KAAK,CAACF,IAAN,GAAaA,IAAb;AACAE,EAAAA,KAAK,CAACC,QAAN,GAAiB,KAAjB;AACA,SAAOD,KAAP;AACD;;AAEM,SAASE,cAAT,CAAwBC,MAAxB,EAAgC;AACrC,MAAMF,QAAQ,GAAGE,MAAM,CAACC,MAAP,CAAc,UAAAC,CAAC,UAAIA,CAAC,CAACJ,QAAN,EAAf,EAA+BK,GAA/B,CAAmC,UAAAD,CAAC,UAAIA,CAAC,CAACP,IAAN,EAApC,CAAjB;;AAEA,SAAO;AACLC,IAAAA,IAAI,EAAE,QADD;AAELE,IAAAA,QAAQ,EAARA,QAFK;AAGLM,IAAAA,UAAU,EAAEJ,MAAM,CAACK,MAAP,CAAc,UAACC,GAAD,EAAMT,KAAN,EAAgB;AACxCS,MAAAA,GAAG,CAACT,KAAK,CAACF,IAAP,CAAH,GAAkBV,QAAQ,CAACY,KAAK,CAACD,IAAP,CAAR,CAAqBW,QAArB,CAA8BV,KAA9B,CAAlB;AACA,aAAOS,GAAP;AACD,KAHW,EAGT,EAHS,CAHP,EAAP;;AAQD;;AAEM,SAASE,cAAT,CAAwBC,WAAxB,EAAqC;AAC1C,SAAOjB,MAAM,CAACC,IAAP,CAAYgB,WAAW,CAACL,UAAxB,EAAoCD,GAApC,CAAwC,UAAAO,GAAG,EAAI;AACpD,QAAMC,MAAM,GAAGF,WAAW,CAACL,UAAZ,CAAuBM,GAAvB,CAAf;AACA,SAAK,IAAId,IAAT,IAAiBX,QAAjB,EAA2B;AACzB,UAAIA,QAAQ,CAACW,IAAD,CAAR,CAAegB,MAAf,CAAsBD,MAAtB,CAAJ,EAAmC;AACjC,YAAMd,KAAK,GAAGZ,QAAQ,CAACW,IAAD,CAAR,CAAeiB,UAAf,CAA0BF,MAA1B,CAAd;AACAd,QAAAA,KAAK,CAACC,QAAN,GAAiBW,WAAW,CAACX,QAAZ,CAAqBgB,QAArB,CAA8BJ,GAA9B,CAAjB;AACAb,QAAAA,KAAK,CAACF,IAAN,GAAae,GAAb;AACA,eAAOb,KAAP;AACD;AACF;AACF,GAVM,CAAP;AAWD","sourcesContent":["import boolean from \"./boolean\"\nimport datetime from \"./datetime\"\nimport link from \"./link\"\nimport number from \"./number\"\nimport select from \"./select\"\nimport text from \"./text\"\n\nconst allTypes = {\n boolean,\n datetime,\n link,\n number,\n select,\n text,\n}\n\nexport function listTypes() {\n return Object.keys(allTypes)\n}\n\nexport function newField(name, type) {\n const field = allTypes[type].default()\n field.name = name\n field.required = false\n return field\n}\n\nexport function fieldsToSchema(fields) {\n const required = fields.filter(f => f.required).map(f => f.name)\n\n return {\n type: \"object\",\n required,\n properties: fields.reduce((sch, field) => {\n sch[field.name] = allTypes[field.type].toSchema(field)\n return sch\n }, {}),\n }\n}\n\nexport function schemaToFields(modelSchema) {\n return Object.keys(modelSchema.properties).map(key => {\n const schema = modelSchema.properties[key]\n for (let type in allTypes) {\n if (allTypes[type].isType(schema)) {\n const field = allTypes[type].fromSchema(schema)\n field.required = modelSchema.required.includes(key)\n field.name = key\n return field\n }\n }\n })\n}\n"],"file":"index.js"}

View file

@ -1,26 +0,0 @@
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _default2 = {
isType: function isType(schema) {return schema.type === "object" && schema.properties.modelId;},
fromSchema: function fromSchema(schema) {return {
type: "link",
modelId: schema.properties.modelId["const"],
viewId: schema.properties.viewId["const"],
"default": schema["default"] };},
toSchema: function toSchema(field) {return {
type: "object",
properties: {
_id: { type: "string" },
viewId: field.viewId ? { "const": field.viewId } : undefined,
modelId: field.modelId ? { "const": field.modelId } : undefined },
required: ["_id"],
"default": { _id: "" } };},
"default": function _default() {return {
type: "link",
modelId: null,
viewId: null };} };exports["default"] = _default2;
//# sourceMappingURL=link.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../../src/schema/types/link.js"],"names":["isType","schema","type","properties","modelId","fromSchema","viewId","toSchema","field","_id","undefined","required"],"mappings":"uHAAe;AACbA,EAAAA,MAAM,EAAE,gBAAAC,MAAM,UAAIA,MAAM,CAACC,IAAP,KAAgB,QAAhB,IAA4BD,MAAM,CAACE,UAAP,CAAkBC,OAAlD,EADD;;AAGbC,EAAAA,UAAU,EAAE,oBAAAJ,MAAM,UAAK;AACrBC,MAAAA,IAAI,EAAE,MADe;AAErBE,MAAAA,OAAO,EAAEH,MAAM,CAACE,UAAP,CAAkBC,OAAlB,SAFY;AAGrBE,MAAAA,MAAM,EAAEL,MAAM,CAACE,UAAP,CAAkBG,MAAlB,SAHa;AAIrB,iBAASL,MAAM,WAJM,EAAL,EAHL;;;AAUbM,EAAAA,QAAQ,EAAE,kBAAAC,KAAK,UAAK;AAClBN,MAAAA,IAAI,EAAE,QADY;AAElBC,MAAAA,UAAU,EAAE;AACVM,QAAAA,GAAG,EAAE,EAAEP,IAAI,EAAE,QAAR,EADK;AAEVI,QAAAA,MAAM,EAAEE,KAAK,CAACF,MAAN,GAAe,EAAE,SAAOE,KAAK,CAACF,MAAf,EAAf,GAAyCI,SAFvC;AAGVN,QAAAA,OAAO,EAAEI,KAAK,CAACJ,OAAN,GAAgB,EAAE,SAAOI,KAAK,CAACJ,OAAf,EAAhB,GAA2CM,SAH1C,EAFM;;AAOlBC,MAAAA,QAAQ,EAAE,CAAC,KAAD,CAPQ;AAQlB,iBAAS,EAAEF,GAAG,EAAE,EAAP,EARS,EAAL,EAVF;;;AAqBb,aAAS,4BAAO;AACdP,MAAAA,IAAI,EAAE,MADQ;AAEdE,MAAAA,OAAO,EAAE,IAFK;AAGdE,MAAAA,MAAM,EAAE,IAHM,EAAP,EArBI,E","sourcesContent":["export default {\n isType: schema => schema.type === \"object\" && schema.properties.modelId,\n\n fromSchema: schema => ({\n type: \"link\",\n modelId: schema.properties.modelId.const,\n viewId: schema.properties.viewId.const,\n default: schema.default,\n }),\n\n toSchema: field => ({\n type: \"object\",\n properties: {\n _id: { type: \"string\" },\n viewId: field.viewId ? { const: field.viewId } : undefined,\n modelId: field.modelId ? { const: field.modelId } : undefined,\n },\n required: [\"_id\"],\n default: { _id: \"\" },\n }),\n\n default: () => ({\n type: \"link\",\n modelId: null,\n viewId: null,\n }),\n}\n"],"file":"link.js"}

View file

@ -1,14 +0,0 @@
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _default2 = {
isType: function isType(schema) {return schema.type === "number";},
fromSchema: function fromSchema(schema) {return schema;},
toSchema: function toSchema(field) {return {
type: "number",
maximum: field.maximum,
minimum: field.minimum,
"default": undefined };},
"default": function _default() {return {
type: "number",
maximum: null,
minimum: null };} };exports["default"] = _default2;
//# sourceMappingURL=number.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../../src/schema/types/number.js"],"names":["isType","schema","type","fromSchema","toSchema","field","maximum","minimum","undefined"],"mappings":"uHAAe;AACbA,EAAAA,MAAM,EAAE,gBAAAC,MAAM,UAAIA,MAAM,CAACC,IAAP,KAAgB,QAApB,EADD;AAEbC,EAAAA,UAAU,EAAE,oBAAAF,MAAM,UAAIA,MAAJ,EAFL;AAGbG,EAAAA,QAAQ,EAAE,kBAAAC,KAAK,UAAK;AAClBH,MAAAA,IAAI,EAAE,QADY;AAElBI,MAAAA,OAAO,EAAED,KAAK,CAACC,OAFG;AAGlBC,MAAAA,OAAO,EAAEF,KAAK,CAACE,OAHG;AAIlB,iBAASC,SAJS,EAAL,EAHF;;AASb,aAAS,4BAAO;AACdN,MAAAA,IAAI,EAAE,QADQ;AAEdI,MAAAA,OAAO,EAAE,IAFK;AAGdC,MAAAA,OAAO,EAAE,IAHK,EAAP,EATI,E","sourcesContent":["export default {\n isType: schema => schema.type === \"number\",\n fromSchema: schema => schema,\n toSchema: field => ({\n type: \"number\",\n maximum: field.maximum,\n minimum: field.minimum,\n default: undefined,\n }),\n default: () => ({\n type: \"number\",\n maximum: null,\n minimum: null,\n }),\n}\n"],"file":"number.js"}

View file

@ -1,7 +0,0 @@
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.newView = void 0;var _shortid = require("shortid");
var newView = function newView() {var modelId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;return {
id: (0, _shortid.generate)(),
name: "",
modelId: modelId };};exports.newView = newView;
//# sourceMappingURL=views.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../src/schema/views.js"],"names":["newView","modelId","id","name"],"mappings":"oGAAA;;AAEO,IAAMA,OAAO,GAAG,SAAVA,OAAU,QAACC,OAAD,uEAAW,IAAX,QAAqB;AAC1CC,IAAAA,EAAE,EAAE,wBADsC;AAE1CC,IAAAA,IAAI,EAAE,EAFoC;AAG1CF,IAAAA,OAAO,EAAPA,OAH0C,EAArB,EAAhB,C","sourcesContent":["import { generate } from \"shortid\"\n\nexport const newView = (modelId = null) => ({\n id: generate(),\n name: \"\",\n modelId,\n})\n"],"file":"views.js"}

View file

@ -1,6 +0,0 @@
"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports, "__esModule", { value: true });exports["default"] = void 0;var _ajv = _interopRequireDefault(require("ajv"));
var ajv = new _ajv["default"]();var _default =
ajv;exports["default"] = _default;
//# sourceMappingURL=index.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["../../src/schemaValidation/index.js"],"names":["ajv","Ajv"],"mappings":"4LAAA;;AAEA,IAAMA,GAAG,GAAG,IAAIC,eAAJ,EAAZ,C;;AAEeD,G","sourcesContent":["import Ajv from \"ajv\";\n\nconst ajv = new Ajv();\n\nexport default ajv;"],"file":"index.js"}

View file

@ -1,68 +0,0 @@
{
"name": "@budibase/common",
"version": "0.0.32",
"description": "core javascript library for budibase",
"main": "lib/index.js",
"files": [
"dist/**",
"!dist/node_modules"
],
"directories": {
"test": "test"
},
"scripts": {
"test": "jest",
"build": "npx babel src --out-dir lib --source-maps"
},
"keywords": [
"budibase"
],
"author": "Budibase",
"license": "MPL-2.0",
"jest": {
"testURL": "http://jest-breaks-if-this-does-not-exist",
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/internals/mocks/fileMock.js",
"\\.(css|less|sass|scss)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"js",
"mjs"
],
"moduleDirectories": [
"node_modules"
],
"transform": {
"^.+\\.mjs$": "babel-jest",
"^.+\\.js$": "babel-jest"
}
},
"devDependencies": {
"@babel/cli": "^7.4.4",
"@babel/core": "^7.4.5",
"@babel/plugin-transform-runtime": "^7.4.4",
"@babel/preset-env": "^7.4.5",
"@babel/runtime": "^7.4.5",
"babel-jest": "^25.3.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"cross-env": "^5.1.4",
"jest": "^24.8.0",
"readable-stream": "^3.1.1",
"regenerator-runtime": "^0.11.1",
"rimraf": "^2.6.2"
},
"dependencies": {
"@nx-js/compiler-util": "^2.0.0",
"ajv": "^6.12.0",
"bcryptjs": "^2.4.3",
"date-fns": "^1.29.0",
"lodash": "^4.17.13",
"shortid": "^2.2.8"
},
"devEngines": {
"node": ">=7.x",
"npm": ">=4.x",
"yarn": ">=0.21.3"
},
"gitHead": "b1f4f90927d9e494e513220ef060af28d2d42455"
}

View file

@ -1,21 +0,0 @@
## Getting Started
Install packages:
`npm install`
Next, run the tests. Install jest, globally:
`npm install -g jest`
And finally, run
`jest`
## Documentation
A work in progress, lives here: https://github.com/Budibase/docs/blob/master/budibase-core.md

View file

@ -1,128 +0,0 @@
import { cloneDeep, isUndefined } from "lodash/fp"
import { generate } from "shortid"
import { UnauthorisedError } from "./errors"
export const apiWrapper = async (
app,
eventNamespace,
isAuthorized,
eventContext,
func,
...params
) => {
pushCallStack(app, eventNamespace)
if (!isAuthorized(app)) {
handleNotAuthorized(app, eventContext, eventNamespace)
return
}
const startDate = Date.now()
const elapsed = () => Date.now() - startDate
try {
await app.publish(eventNamespace.onBegin, eventContext)
const result = await func(...params)
await publishComplete(app, eventContext, eventNamespace, elapsed, result)
return result
} catch (error) {
await publishError(app, eventContext, eventNamespace, elapsed, error)
throw error
}
}
export const apiWrapperSync = (
app,
eventNamespace,
isAuthorized,
eventContext,
func,
...params
) => {
pushCallStack(app, eventNamespace)
if (!isAuthorized(app)) {
handleNotAuthorized(app, eventContext, eventNamespace)
return
}
const startDate = Date.now()
const elapsed = () => Date.now() - startDate
try {
app.publish(eventNamespace.onBegin, eventContext)
const result = func(...params)
publishComplete(app, eventContext, eventNamespace, elapsed, result)
return result
} catch (error) {
publishError(app, eventContext, eventNamespace, elapsed, error)
throw error
}
}
const handleNotAuthorized = (app, eventContext, eventNamespace) => {
const err = new UnauthorisedError(`Unauthorized: ${eventNamespace}`)
publishError(app, eventContext, eventNamespace, () => 0, err)
throw err
}
const pushCallStack = (app, eventNamespace, seedCallId) => {
const callId = generate()
const createCallStack = () => ({
seedCallId: !isUndefined(seedCallId) ? seedCallId : callId,
threadCallId: callId,
stack: [],
})
if (isUndefined(app.calls)) {
app.calls = createCallStack()
}
app.calls.stack.push({
namespace: eventNamespace,
callId,
})
}
const popCallStack = app => {
app.calls.stack.pop()
if (app.calls.stack.length === 0) {
delete app.calls
}
}
const publishError = async (
app,
eventContext,
eventNamespace,
elapsed,
err
) => {
const ctx = cloneDeep(eventContext)
ctx.error = err
ctx.elapsed = elapsed()
await app.publish(eventNamespace.onError, ctx)
popCallStack(app)
}
const publishComplete = async (
app,
eventContext,
eventNamespace,
elapsed,
result
) => {
const endcontext = cloneDeep(eventContext)
endcontext.result = result
endcontext.elapsed = elapsed()
await app.publish(eventNamespace.onComplete, endcontext)
popCallStack(app)
return result
}
export default apiWrapper

View file

@ -1,26 +0,0 @@
import { compileCode as cCode } from "@nx-js/compiler-util"
import { includes } from "lodash/fp"
export const compileCode = code => {
let func
let safeCode
if (includes("return ")(code)) {
safeCode = code
} else {
let trimmed = code.trim()
trimmed = trimmed.endsWith(";")
? trimmed.substring(0, trimmed.length - 1)
: trimmed
safeCode = `return (${trimmed})`
}
try {
func = cCode(safeCode)
} catch (e) {
e.message = `Error compiling code : ${code} : ${e.message}`
throw e
}
return func
}

View file

@ -1,34 +0,0 @@
export class BadRequestError extends Error {
constructor(message) {
super(message)
this.httpStatusCode = 400
}
}
export class UnauthorisedError extends Error {
constructor(message) {
super(message)
this.httpStatusCode = 401
}
}
export class ForbiddenError extends Error {
constructor(message) {
super(message)
this.httpStatusCode = 403
}
}
export class NotFoundError extends Error {
constructor(message) {
super(message)
this.httpStatusCode = 404
}
}
export class ConflictError extends Error {
constructor(message) {
super(message)
this.httpStatusCode = 409
}
}

View file

@ -1,27 +0,0 @@
import { has } from "lodash/fp"
const publish = handlers => async (eventName, context = {}) => {
if (!has(eventName)(handlers)) return
for (const handler of handlers[eventName]) {
await handler(eventName, context)
}
}
const subscribe = handlers => (eventName, handler) => {
if (!has(eventName)(handlers)) {
handlers[eventName] = []
}
handlers[eventName].push(handler)
}
export const createEventAggregator = () => {
const handlers = {}
const eventAggregator = {
publish: publish(handlers),
subscribe: subscribe(handlers),
}
return eventAggregator
}
export default createEventAggregator

View file

@ -1,85 +0,0 @@
import { union, reduce } from "lodash/fp"
const commonPlus = extra => union(["onBegin", "onComplete", "onError"])(extra)
const common = () => commonPlus([])
const _events = {
recordApi: {
save: commonPlus(["onInvalid", "onRecordUpdated", "onRecordCreated"]),
delete: common(),
getContext: common(),
getNew: common(),
load: common(),
validate: common(),
uploadFile: common(),
downloadFile: common(),
},
indexApi: {
buildIndex: common(),
listItems: common(),
delete: common(),
aggregates: common(),
},
collectionApi: {
getAllowedRecordTypes: common(),
initialise: common(),
delete: common(),
},
authApi: {
authenticate: common(),
authenticateTemporaryAccess: common(),
createTemporaryAccess: common(),
createUser: common(),
enableUser: common(),
disableUser: common(),
loadAccessLevels: common(),
getNewAccessLevel: common(),
getNewUser: common(),
getNewUserAuth: common(),
getUsers: common(),
saveAccessLevels: common(),
isAuthorized: common(),
changeMyPassword: common(),
setPasswordFromTemporaryCode: common(),
scorePassword: common(),
isValidPassword: common(),
validateUser: common(),
validateAccessLevels: common(),
setUserAccessLevels: common(),
},
templateApi: {
saveApplicationHierarchy: common(),
saveActionsAndTriggers: common(),
},
actionsApi: {
execute: common(),
},
}
const _eventsList = []
const makeEvent = (area, method, name) => `${area}:${method}:${name}`
for (const areaKey in _events) {
for (const methodKey in _events[areaKey]) {
_events[areaKey][methodKey] = reduce((obj, s) => {
obj[s] = makeEvent(areaKey, methodKey, s)
return obj
}, {})(_events[areaKey][methodKey])
}
}
for (const areaKey in _events) {
for (const methodKey in _events[areaKey]) {
for (const name in _events[areaKey][methodKey]) {
_eventsList.push(_events[areaKey][methodKey][name])
}
}
}
export const events = _events
export const eventsList = _eventsList
export default { events: _events, eventsList: _eventsList }

View file

@ -1,307 +0,0 @@
import {
head,
tail,
findIndex,
startsWith,
dropRight,
flow,
takeRight,
trim,
replace,
} from "lodash"
import {
some,
reduce,
isEmpty,
isArray,
join,
isString,
isInteger,
isDate,
toNumber,
isUndefined,
isNaN,
isNull,
constant,
split,
includes,
filter,
} from "lodash/fp"
import { events, eventsList } from "./events.js"
// this is the combinator function
export const $$ = (...funcs) => arg => flow(funcs)(arg)
// this is the pipe function
export const $ = (arg, funcs) => $$(...funcs)(arg)
export const keySep = "/"
const trimKeySep = str => trim(str, keySep)
const splitByKeySep = str => split(keySep)(str)
export const safeKey = key =>
replace(`${keySep}${trimKeySep(key)}`, `${keySep}${keySep}`, keySep)
export const joinKey = (...strs) => {
const paramsOrArray = (strs.length === 1) & isArray(strs[0]) ? strs[0] : strs
return $(paramsOrArray, [
filter(s => !isUndefined(s) && !isNull(s) && s.toString().length > 0),
join(keySep),
safeKey,
])
}
export const splitKey = $$(trimKeySep, splitByKeySep)
export const getDirFomKey = $$(splitKey, dropRight, p => joinKey(...p))
export const getFileFromKey = $$(splitKey, takeRight, head)
export const configFolder = `${keySep}.config`
export const fieldDefinitions = joinKey(configFolder, "fields.json")
export const templateDefinitions = joinKey(configFolder, "templates.json")
export const appDefinitionFile = joinKey(configFolder, "appDefinition.json")
export const dirIndex = folderPath =>
joinKey(configFolder, "dir", ...splitKey(folderPath), "dir.idx")
export const getIndexKeyFromFileKey = $$(getDirFomKey, dirIndex)
export const ifExists = (val, exists, notExists) =>
isUndefined(val)
? isUndefined(notExists)
? (() => {})()
: notExists()
: exists()
export const getOrDefault = (val, defaultVal) =>
ifExists(
val,
() => val,
() => defaultVal
)
export const not = func => val => !func(val)
export const isDefined = not(isUndefined)
export const isNonNull = not(isNull)
export const isNotNaN = not(isNaN)
export const allTrue = (...funcArgs) => val =>
reduce(
(result, conditionFunc) =>
(isNull(result) || result == true) && conditionFunc(val),
null
)(funcArgs)
export const anyTrue = (...funcArgs) => val =>
reduce(
(result, conditionFunc) => result == true || conditionFunc(val),
null
)(funcArgs)
export const insensitiveEquals = (str1, str2) =>
str1.trim().toLowerCase() === str2.trim().toLowerCase()
export const isSomething = allTrue(isDefined, isNonNull, isNotNaN)
export const isNothing = not(isSomething)
export const isNothingOrEmpty = v => isNothing(v) || isEmpty(v)
export const somethingOrGetDefault = getDefaultFunc => val =>
isSomething(val) ? val : getDefaultFunc()
export const somethingOrDefault = (val, defaultVal) =>
somethingOrGetDefault(constant(defaultVal))(val)
export const mapIfSomethingOrDefault = (mapFunc, defaultVal) => val =>
isSomething(val) ? mapFunc(val) : defaultVal
export const mapIfSomethingOrBlank = mapFunc =>
mapIfSomethingOrDefault(mapFunc, "")
export const none = predicate => collection => !some(predicate)(collection)
export const all = predicate => collection =>
none(v => !predicate(v))(collection)
export const isNotEmpty = ob => !isEmpty(ob)
export const isAsync = fn => fn.constructor.name === "AsyncFunction"
export const isNonEmptyArray = allTrue(isArray, isNotEmpty)
export const isNonEmptyString = allTrue(isString, isNotEmpty)
export const tryOr = failFunc => (func, ...args) => {
try {
return func.apply(null, ...args)
} catch (_) {
return failFunc()
}
}
export const tryAwaitOr = failFunc => async (func, ...args) => {
try {
return await func.apply(null, ...args)
} catch (_) {
return await failFunc()
}
}
export const defineError = (func, errorPrefix) => {
try {
return func()
} catch (err) {
err.message = `${errorPrefix} : ${err.message}`
throw err
}
}
export const tryOrIgnore = tryOr(() => {})
export const tryAwaitOrIgnore = tryAwaitOr(async () => {})
export const causesException = func => {
try {
func()
return false
} catch (e) {
return true
}
}
export const executesWithoutException = func => !causesException(func)
export const handleErrorWith = returnValInError =>
tryOr(constant(returnValInError))
export const handleErrorWithUndefined = handleErrorWith(undefined)
export const switchCase = (...cases) => value => {
const nextCase = () => head(cases)[0](value)
const nextResult = () => head(cases)[1](value)
if (isEmpty(cases)) return // undefined
if (nextCase() === true) return nextResult()
return switchCase(...tail(cases))(value)
}
export const isValue = val1 => val2 => val1 === val2
export const isOneOf = (...vals) => val => includes(val)(vals)
export const defaultCase = constant(true)
export const memberMatches = (member, match) => obj => match(obj[member])
export const StartsWith = searchFor => searchIn =>
startsWith(searchIn, searchFor)
export const contains = val => array => findIndex(array, v => v === val) > -1
export const getHashCode = s => {
let hash = 0
let i
let char
let l
if (s.length == 0) return hash
for (i = 0, l = s.length; i < l; i++) {
char = s.charCodeAt(i)
hash = (hash << 5) - hash + char
hash |= 0 // Convert to 32bit integer
}
// converting to string, but dont want a "-" prefixed
if (hash < 0) {
return `n${(hash * -1).toString()}`
}
return hash.toString()
}
// thanks to https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/
export const awEx = async promise => {
try {
const result = await promise
return [undefined, result]
} catch (error) {
return [error, undefined]
}
}
export const isSafeInteger = n =>
isInteger(n) &&
n <= Number.MAX_SAFE_INTEGER &&
n >= 0 - Number.MAX_SAFE_INTEGER
export const toDateOrNull = s =>
isNull(s) ? null : isDate(s) ? s : new Date(s)
export const toBoolOrNull = s => (isNull(s) ? null : s === "true" || s === true)
export const toNumberOrNull = s => (isNull(s) ? null : toNumber(s))
export const isArrayOfString = opts => isArray(opts) && all(isString)(opts)
export const pushAll = (target, items) => {
for (let i of items) target.push(i)
}
export const pause = async duration =>
new Promise(res => setTimeout(res, duration))
export const retry = async (fn, retries, delay, ...args) => {
try {
return await fn(...args)
} catch (err) {
if (retries > 1) {
return await pause(delay).then(
async () => await retry(fn, retries - 1, delay, ...args)
)
}
throw err
}
}
export { events } from "./events.js"
export default {
ifExists,
getOrDefault,
isDefined,
isNonNull,
isNotNaN,
allTrue,
isSomething,
mapIfSomethingOrDefault,
mapIfSomethingOrBlank,
configFolder,
fieldDefinitions,
isNothing,
not,
switchCase,
defaultCase,
StartsWith,
contains,
templateDefinitions,
handleErrorWith,
handleErrorWithUndefined,
tryOr,
tryOrIgnore,
tryAwaitOr,
tryAwaitOrIgnore,
dirIndex,
keySep,
$,
$$,
getDirFomKey,
getFileFromKey,
splitKey,
somethingOrDefault,
getIndexKeyFromFileKey,
joinKey,
somethingOrGetDefault,
appDefinitionFile,
isValue,
all,
isOneOf,
memberMatches,
defineError,
anyTrue,
isNonEmptyArray,
causesException,
executesWithoutException,
none,
getHashCode,
awEx,
events,
eventsList,
isNothingOrEmpty,
isSafeInteger,
toNumber,
toDate: toDateOrNull,
toBool: toBoolOrNull,
isArrayOfString,
insensitiveEquals,
pause,
retry,
pushAll,
}

View file

@ -1,14 +0,0 @@
import { filter, map } from "lodash/fp"
import { $, isSomething } from "./index"
export const stringNotEmpty = s => isSomething(s) && s.trim().length > 0
export const makerule = (field, error, isValid) => ({ field, error, isValid })
export const validationError = (rule, item) => ({ ...rule, item })
export const applyRuleSet = ruleSet => itemToValidate =>
$(ruleSet, [map(applyRule(itemToValidate)), filter(isSomething)])
export const applyRule = itemTovalidate => rule =>
rule.isValid(itemTovalidate) ? null : validationError(rule, itemTovalidate)

View file

@ -1,3 +0,0 @@
export { events } from "./common/events";
export { safeParseField } from "./schema/types";
export { default as schemaValidator } from "./schemaValidation";

View file

@ -1,22 +0,0 @@
export const createTrigger = () => ({
actionName: "",
eventName: "",
// function, has access to event context,
// returns object that is used as parameter to action
// only used if triggered by event
optionsCreator: "",
// action runs if true,
// has access to event context
condition: "",
})
export const createAction = () => ({
name: "",
behaviourSource: "",
// name of function in actionSource
behaviourName: "",
// parameter passed into behaviour.
// any other parms passed at runtime e.g.
// by trigger, or manually, will be merged into this
initialOptions: {},
})

View file

@ -1,96 +0,0 @@
import { some, map, filter, keys, includes, countBy, flatten } from "lodash/fp"
import {
isSomething,
$,
isNonEmptyString,
isNothingOrEmpty,
isNothing,
} from "../common"
import { all, getDefaultOptions } from "./types/index.js"
import { applyRuleSet, makerule } from "../common/validationCommon"
import { BadRequestError } from "../common/errors"
import { generate } from "shortid"
export const fieldErrors = {
AddFieldValidationFailed: "Add field validation: ",
}
export const allowedTypes = () => keys(all)
export const getNewField = type => ({
id: generate(),
name: "", // how field is referenced internally
type,
typeOptions: getDefaultOptions(type),
label: "", // how field is displayed
getInitialValue: "default", // function that gets value when initially created
getUndefinedValue: "default", // function that gets value when field undefined on record
})
const fieldRules = allFields => [
makerule("name", "field name is not set", f => isNonEmptyString(f.name)),
makerule("type", "field type is not set", f => isNonEmptyString(f.type)),
makerule("label", "field label is not set", f => isNonEmptyString(f.label)),
makerule("getInitialValue", "getInitialValue function is not set", f =>
isNonEmptyString(f.getInitialValue)
),
makerule("getUndefinedValue", "getUndefinedValue function is not set", f =>
isNonEmptyString(f.getUndefinedValue)
),
makerule(
"name",
"field name is duplicated",
f => isNothingOrEmpty(f.name) || countBy("name")(allFields)[f.name] === 1
),
makerule(
"type",
"type is unknown",
f => isNothingOrEmpty(f.type) || some(t => f.type === t)(allowedTypes())
),
]
const typeOptionsRules = field => {
const type = all[field.type]
if (isNothing(type)) return []
const def = optName => type.optionDefinitions[optName]
return $(field.typeOptions, [
keys,
filter(o => isSomething(def(o)) && isSomething(def(o).isValid)),
map(o =>
makerule(`typeOptions.${o}`, `${def(o).requirementDescription}`, field =>
def(o).isValid(field.typeOptions[o])
)
),
])
}
export const validateField = allFields => field => {
const everySingleField = includes(field)(allFields)
? allFields
: [...allFields, field]
return applyRuleSet([
...fieldRules(everySingleField),
...typeOptionsRules(field),
])(field)
}
export const validateAllFields = recordNode =>
$(recordNode.fields, [map(validateField(recordNode.fields)), flatten])
export const addField = (recordTemplate, field) => {
if (isNothingOrEmpty(field.label)) {
field.label = field.name
}
const validationMessages = validateField([...recordTemplate.fields, field])(
field
)
if (validationMessages.length > 0) {
const errors = map(m => m.error)(validationMessages)
throw new BadRequestError(
`${fieldErrors.AddFieldValidationFailed} ${errors.join(", ")}`
)
}
recordTemplate.fields.push(field)
}

View file

@ -1,33 +0,0 @@
export const fullSchema = (models, views) => {
const findModel = idOrName =>
models.find(
m => m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase()
)
const findView = idOrName =>
views.find(
m => m.id === idOrName || m.name.toLowerCase() === idOrName.toLowerCase()
)
const findField = (modelIdOrName, fieldName) => {
const model = models.find(
m =>
m.id === modelIdOrName ||
m.name.toLowerCase() === modelIdOrName.toLowerCase()
)
return model.fields.find(
f => f.name.toLowerCase() === fieldName.toLowerCase()
)
}
const viewsForModel = modelId => views.filter(v => v.modelId === modelId)
return {
models,
views,
findModel,
findField,
findView,
viewsForModel,
}
}

View file

@ -1,42 +0,0 @@
import { generate } from "shortid"
export const newModel = () => ({
_id: generate(),
name: "",
type: "model",
key: "name",
schema: {
type: "object",
properties: {
name: { type: "string" },
},
required: ["name"],
},
})
/**
*
* @param {Array} models
* @param {string} modelId
* @returns {}
*/
export const canDeleteModel = (models, modelId) => {
const errors = []
for (let model of models) {
const links = model.fields.filter(
f => f.type === "link" && f.typeOptions.modelId === modelId
)
for (let link of links) {
errors.push(
`The "${model.name}" model links to this model, via field "${link.name}"`
)
}
}
return {
errors,
canDelete: errors.length > 0,
}
}

View file

@ -1,12 +0,0 @@
export default {
isType: schema => schema.type === "boolean",
fromSchema: schema => schema,
toSchema: field => ({
type: "boolean",
default: field.default,
}),
default: () => ({
type: "boolean",
default: false,
}),
}

View file

@ -1,19 +0,0 @@
export default {
isType: schema =>
schema.anyOf &&
schema.anyOf.filter(s => s.type === "string" && s.format === "date-time")
.length > 0,
fromSchema: schema => ({
type: "datetime",
default: schema.default,
}),
toSchema: () => ({
anyOf: [{ type: "string", format: "date-time" }, { const: "" }],
default: "",
}),
default: () => ({
type: "datetime",
default: "",
}),
}

View file

@ -1,53 +0,0 @@
import boolean from "./boolean"
import datetime from "./datetime"
import link from "./link"
import number from "./number"
import select from "./select"
import text from "./text"
const allTypes = {
boolean,
datetime,
link,
number,
select,
text,
}
export function listTypes() {
return Object.keys(allTypes)
}
export function newField(name, type) {
const field = allTypes[type].default()
field.name = name
field.required = false
return field
}
export function fieldsToSchema(fields) {
const required = fields.filter(f => f.required).map(f => f.name)
return {
type: "object",
required,
properties: fields.reduce((sch, field) => {
sch[field.name] = allTypes[field.type].toSchema(field)
return sch
}, {}),
}
}
export function schemaToFields(modelSchema) {
return Object.keys(modelSchema.properties).map(key => {
const schema = modelSchema.properties[key]
for (let type in allTypes) {
if (allTypes[type].isType(schema)) {
const field = allTypes[type].fromSchema(schema)
field.required = modelSchema.required.includes(key)
field.name = key
return field
}
}
})
}

View file

@ -1,27 +0,0 @@
export default {
isType: schema => schema.type === "object" && schema.properties.modelId,
fromSchema: schema => ({
type: "link",
modelId: schema.properties.modelId.const,
viewId: schema.properties.viewId.const,
default: schema.default,
}),
toSchema: field => ({
type: "object",
properties: {
_id: { type: "string" },
viewId: field.viewId ? { const: field.viewId } : undefined,
modelId: field.modelId ? { const: field.modelId } : undefined,
},
required: ["_id"],
default: { _id: "" },
}),
default: () => ({
type: "link",
modelId: null,
viewId: null,
}),
}

View file

@ -1,15 +0,0 @@
export default {
isType: schema => schema.type === "number",
fromSchema: schema => schema,
toSchema: field => ({
type: "number",
maximum: field.maximum,
minimum: field.minimum,
default: undefined,
}),
default: () => ({
type: "number",
maximum: null,
minimum: null,
}),
}

View file

@ -1,21 +0,0 @@
export default {
isType: schema => schema.type === "string" && schema.enum,
fromSchema: schema => ({
type: "select",
enum: schema.enum,
default: schema.default,
}),
toSchema: field => ({
type: "string",
enum: field.enum,
default: field.default,
}),
default: () => ({
type: "select",
enum: [],
default: "",
}),
}

View file

@ -1,24 +0,0 @@
export default {
isType: schema => schema.type === "string" && !schema.format,
fromSchema: schema => ({
type: "text",
maxLength: schema.maxLength,
minLength: schema.minLength,
default: schema.default,
}),
toSchema: field => ({
type: "string",
maxLength: field.maxLength,
minLength: field.minLength,
default: "",
}),
default: () => ({
type: "text",
maxLength: null,
minLength: 0,
default: "",
}),
}

View file

@ -1,7 +0,0 @@
import { generate } from "shortid"
export const newView = (modelId = null) => ({
id: generate(),
name: "",
modelId,
})

View file

@ -1,5 +0,0 @@
import Ajv from "ajv";
const ajv = new Ajv();
export default ajv;

View file

@ -1,38 +0,0 @@
import { newModel } from "../schema/models"
import { newView } from "../schema/views"
import { fullSchema } from "../schema/fullSchema"
import { newField, schemaToFields, fieldsToSchema } from "../schema/types"
export function testSchema() {
const addFieldToModel = (model, field) => {
const defaultField = newField(field.name, field.type || "text")
Object.assign(defaultField, field)
const currentFields = schemaToFields(model.schema)
model.schema = fieldsToSchema([...currentFields, field])
}
const contactModel = newModel()
contactModel.name = "Contact"
addFieldToModel(contactModel, { name: "Is Active", type: "boolean" })
addFieldToModel(contactModel, { name: "Created", type: "datetime" })
addFieldToModel(contactModel, {
name: "Status",
type: "select",
enum: ["new", "complete"],
})
const activeContactsView = newView(contactModel.id)
activeContactsView.name = "Active Contacts"
activeContactsView.map = "if (doc['Is Active']) emit(doc.Name, doc)"
const dealModel = newModel()
dealModel.name = "Deal"
addFieldToModel(dealModel, { name: "Estimated Value", type: "number" })
addFieldToModel(dealModel, {
name: "Contact",
type: "link",
modelId: contactModel.id,
})
return fullSchema([contactModel, dealModel], [activeContactsView])
}

View file

@ -1,216 +0,0 @@
import common, { isOneOf } from "../src/common"
import _ from "lodash"
const lessThan = than => compare => compare < than
describe("common > switchCase", () => {
test("should return on first matching case", () => {
const result = common.switchCase(
[lessThan(1), _.constant("first")],
[lessThan(2), _.constant("second")],
[lessThan(3), _.constant("third")]
)(1)
expect(result).toBe("second")
})
test("should return undefined if case not matched", () => {
const result = common.switchCase(
[lessThan(1), _.constant("first")],
[lessThan(2), _.constant("second")],
[lessThan(3), _.constant("third")]
)(10)
expect(_.isUndefined(result)).toBeTruthy()
})
})
describe("common > allTrue", () => {
test("should only return true when all conditions are met", () => {
const result1 = common.allTrue(lessThan(3), lessThan(5), lessThan(10))(1)
expect(result1).toBeTruthy()
const result2 = common.allTrue(lessThan(3), lessThan(5), lessThan(10))(7)
expect(result2).toBeFalsy()
})
})
describe("common > anyTrue", () => {
test("should return true when one or more condition is met", () => {
const result1 = common.anyTrue(lessThan(3), lessThan(5), lessThan(10))(5)
expect(result1).toBeTruthy()
const result2 = common.anyTrue(lessThan(3), lessThan(5), lessThan(10))(4)
expect(result2).toBeTruthy()
})
test("should return false when no conditions are met", () => {
const result1 = common.anyTrue(lessThan(3), lessThan(5), lessThan(10))(15)
expect(result1).toBeFalsy()
})
})
const s = common.keySep
describe("common > getDirFromKey", () => {
test("should drop the final part of the path", () => {
const key = `${s}one${s}two${s}three${s}last`
const expectedDIr = `${s}one${s}two${s}three`
const result = common.getDirFomKey(key)
expect(result).toBe(expectedDIr)
})
test("should add leading /", () => {
const key = `one${s}two${s}three${s}last`
const expectedDIr = `${s}one${s}two${s}three`
const result = common.getDirFomKey(key)
expect(result).toBe(expectedDIr)
})
})
describe("common > getFileFromKey", () => {
test("should get the final part of the path", () => {
const key = `one${s}two${s}three${s}last`
const expectedFile = "last"
const result = common.getFileFromKey(key)
expect(result).toBe(expectedFile)
})
})
describe("common > getIndexKeyFromFileKey", () => {
test("should get the index key of the file's directory", () => {
const key = `one${s}two${s}three${s}file`
const expectedFile = common.dirIndex(`one${s}two${s}three`)
const result = common.getIndexKeyFromFileKey(key)
expect(result).toBe(expectedFile)
})
})
describe("common > somethingOrDefault", () => {
test("should use value if value is something", () => {
const result = common.somethingOrDefault("something", "default")
expect(result).toBe("something")
})
test("should use value if value is empty sting", () => {
const result = common.somethingOrDefault("", "default")
expect(result).toBe("")
})
test("should use value if value is empty array", () => {
const result = common.somethingOrDefault([], ["default"])
expect(result.length).toBe(0)
})
test("should use default if value is null", () => {
const result = common.somethingOrDefault(null, "default")
expect(result).toBe("default")
})
test("should use default if value is undefined", () => {
const result = common.somethingOrDefault({}.notDefined, "default")
expect(result).toBe("default")
})
})
describe("common > dirIndex", () => {
it("should match /config/dir/<path>/dir.idx to path", () => {
var result = common.dirIndex("some/path")
expect(result).toBe(`${s}.config${s}dir${s}some${s}path${s}dir.idx`)
})
})
describe("common > joinKey", () => {
it("should join an array with the key separator and leading separator", () => {
var result = common.joinKey("this", "is", "a", "path")
expect(result).toBe(`${s}this${s}is${s}a${s}path`)
})
})
describe("common > combinator ($$)", () => {
it("combines single params functions and returns a func", () => {
const f1 = str => str + " hello"
const f2 = str => str + " there"
const combined = common.$$(f1, f2)
const result = combined("mike says")
expect(result).toBe("mike says hello there")
})
})
describe("common > pipe ($)", () => {
it("combines single params functions and executes with given param", () => {
const f1 = str => str + " hello"
const f2 = str => str + " there"
const result = common.$("mike says", [f1, f2])
expect(result).toBe("mike says hello there")
})
})
describe("common > IsOneOf", () => {
it("should return true when supplied value is in list of given vals", () => {
expect(common.isOneOf("odo", "make")("odo")).toBe(true)
expect(common.isOneOf(1, 33, 9)(9)).toBe(true)
expect(common.isOneOf(true, false, "")(true)).toBe(true)
})
it("should return false when supplied value is not in list of given vals", () => {
expect(common.isOneOf("odo", "make")("bob")).toBe(false)
expect(common.isOneOf(1, 33, 9)(999)).toBe(false)
expect(common.isOneOf(1, false, "")(true)).toBe(false)
})
})
describe("defineError", () => {
it("should prefix and exception with message, and rethrow", () => {
expect(() =>
common.defineError(() => {
throw new Error("there")
}, "hello")
).toThrowError("hello : there")
})
it("should return function value when no exception", () => {
const result = common.defineError(() => 1, "no error")
expect(result).toBe(1)
})
})
describe("retry", () => {
let counter = 0
it("should retry once", async () => {
var result = await common.retry(async () => 1, 3, 50)
expect(result).toBe(1)
})
it("should retry twice", async () => {
var result = await common.retry(
async () => {
counter++
if (counter < 2) throw "error"
return counter
},
3,
50
)
expect(result).toBe(2)
})
it("throws error after 3 retries", async () => {
expect(
common.retry(
async () => {
counter++
throw counter
},
3,
50
)
).rejects.toThrowError(4)
})
})

View file

@ -1,32 +0,0 @@
import { testSchema } from "./testSchema.mjs"
import { isNonEmptyString } from "../src/common"
import { getNewRecord } from "../src/records/getNewRecord.mjs"
describe("getNewRecord", () => {
it("should get object with generated id and key (full path)", async () => {
const schema = testSchema()
const record = getNewRecord(schema, "Contact")
expect(record._id).toBeDefined()
expect(isNonEmptyString(record._id)).toBeTruthy()
expect(record._rev).not.toBeDefined()
expect(record._modelId).toBe(schema.findModel("Contact").id)
})
it("should create object with all declared fields, using default values", async () => {
const schema = testSchema()
const contact = getNewRecord(schema, "Contact")
expect(contact.Name).toBe(null)
expect(contact.Created).toBe(null)
expect(contact["Is Active"]).toBe(null)
})
it("should create object with all declared fields, and use inital values", async () => {
const schema = testSchema()
schema.findField("Contact", "Name").getInitialValue = "Default Name"
const contact = getNewRecord(schema, "Contact")
expect(contact.Name).toBe("Default Name")
})
})

View file

@ -1,11 +0,0 @@
{
"spec_dir": "test",
"spec_files": [
"**/*[sS]pec.js"
],
"helpers": [
"helpers/**/*.js"
],
"stopSpecOnExpectationFailure": false,
"random": false
}

View file

@ -1,110 +0,0 @@
import { validateActions, validateTrigger } from "../src/templateApi/validate"
import { createValidActionsAndTriggers } from "./specHelpers"
describe("templateApi actions validation", () => {
it("should return no errors when all actions are valid", () => {
const { allActions } = createValidActionsAndTriggers()
const result = validateActions(allActions)
expect(result).toEqual([])
})
it("should return error for empty behaviourName", () => {
const { allActions, logMessage } = createValidActionsAndTriggers()
logMessage.behaviourName = ""
const result = validateActions(allActions)
expect(result.length).toBe(1)
expect(result[0].field).toEqual("behaviourName")
})
it("should return error for empty behaviourSource", () => {
const { allActions, logMessage } = createValidActionsAndTriggers()
logMessage.behaviourSource = ""
const result = validateActions(allActions)
expect(result.length).toBe(1)
expect(result[0].field).toEqual("behaviourSource")
})
it("should return error for empty name", () => {
const { allActions, logMessage } = createValidActionsAndTriggers()
logMessage.name = ""
const result = validateActions(allActions)
expect(result.length).toBe(1)
expect(result[0].field).toEqual("name")
})
it("should return error for duplicate name", () => {
const {
allActions,
logMessage,
measureCallTime,
} = createValidActionsAndTriggers()
logMessage.name = measureCallTime.name
const result = validateActions(allActions)
expect(result.length).toBe(1)
expect(result[0].field).toEqual("")
})
})
describe("tempalteApi triggers validation", () => {
it("should return error when actionName is empty", () => {
const { allActions, logOnErrorTrigger } = createValidActionsAndTriggers()
logOnErrorTrigger.actionName = ""
const result = validateTrigger(logOnErrorTrigger, allActions)
expect(result.length).toBe(1)
expect(result[0].field).toEqual("actionName")
})
it("should return error when eventName is empty", () => {
const { allActions, logOnErrorTrigger } = createValidActionsAndTriggers()
logOnErrorTrigger.eventName = ""
const result = validateTrigger(logOnErrorTrigger, allActions)
expect(result.length).toBe(1)
expect(result[0].field).toEqual("eventName")
})
it("should return error when eventName does not exist in allowed events", () => {
const { allActions, logOnErrorTrigger } = createValidActionsAndTriggers()
logOnErrorTrigger.eventName = "non existant event name"
const result = validateTrigger(logOnErrorTrigger, allActions)
expect(result.length).toBe(1)
expect(result[0].field).toEqual("eventName")
})
it("should return error when actionName does not exist in supplied actions", () => {
const { allActions, logOnErrorTrigger } = createValidActionsAndTriggers()
logOnErrorTrigger.actionName = "non existent action name"
const result = validateTrigger(logOnErrorTrigger, allActions)
expect(result.length).toBe(1)
expect(result[0].field).toEqual("actionName")
})
it("should return error when optionsCreator is invalid javascript", () => {
const { allActions, logOnErrorTrigger } = createValidActionsAndTriggers()
logOnErrorTrigger.optionsCreator = "this is nonsense"
const result = validateTrigger(logOnErrorTrigger, allActions)
expect(result.length).toBe(1)
expect(result[0].field).toEqual("optionsCreator")
})
it("should return error when condition is invalid javascript", () => {
const { allActions, logOnErrorTrigger } = createValidActionsAndTriggers()
logOnErrorTrigger.condition = "this is nonsense"
const result = validateTrigger(logOnErrorTrigger, allActions)
expect(result.length).toBe(1)
expect(result[0].field).toEqual("condition")
})
it("should not return error when condition is empty", () => {
const { allActions, logOnErrorTrigger } = createValidActionsAndTriggers()
logOnErrorTrigger.condition = ""
const result = validateTrigger(logOnErrorTrigger, allActions)
expect(result.length).toBe(0)
})
it("should not return error when optionsCreator is empty", () => {
const { allActions, logOnErrorTrigger } = createValidActionsAndTriggers()
logOnErrorTrigger.optionsCreator = ""
const result = validateTrigger(logOnErrorTrigger, allActions)
expect(result.length).toBe(0)
})
})

View file

@ -1,86 +0,0 @@
import {
setupApphierarchy,
basicAppHierarchyCreator_WithFields,
stubEventHandler,
basicAppHierarchyCreator_WithFields_AndIndexes,
} from "./specHelpers"
import { canDeleteIndex } from "../src/templateApi/canDeleteIndex"
import { canDeleteRecord } from "../src/templateApi/canDeleteRecord"
describe("canDeleteIndex", () => {
it("should return no errors if deltion is valid", async () => {
const { appHierarchy } = await setupApphierarchy(
basicAppHierarchyCreator_WithFields
)
const partnerIndex = appHierarchy.root.indexes.find(i => i.name === "partner_index")
const result = canDeleteIndex(partnerIndex)
expect(result.canDelete).toBe(true)
expect(result.errors).toEqual([])
})
it("should return errors if index is a lookup for a reference field", async () => {
const { appHierarchy } = await setupApphierarchy(
basicAppHierarchyCreator_WithFields
)
const customerIndex = appHierarchy.root.indexes.find(i => i.name === "customer_index")
const result = canDeleteIndex(customerIndex)
expect(result.canDelete).toBe(false)
expect(result.errors.length).toBe(1)
})
it("should return errors if index is a manyToOne index for a reference field", async () => {
const { appHierarchy } = await setupApphierarchy(
basicAppHierarchyCreator_WithFields
)
const referredToCustomersIndex = appHierarchy.customerRecord.indexes.find(i => i.name === "referredToCustomers")
const result = canDeleteIndex(referredToCustomersIndex)
expect(result.canDelete).toBe(false)
expect(result.errors.length).toBe(1)
})
})
describe("canDeleteRecord", () => {
it("should return no errors when deletion is valid", async () => {
const { appHierarchy } = await setupApphierarchy(
basicAppHierarchyCreator_WithFields
)
appHierarchy.root.indexes = appHierarchy.root.indexes.filter(i => !i.allowedRecordNodeIds.includes(appHierarchy.customerRecord.nodeId))
const result = canDeleteRecord(appHierarchy.customerRecord)
expect(result.canDelete).toBe(true)
expect(result.errors).toEqual([])
})
it("should return errors when record is referenced by hierarchal index", async () => {
const { appHierarchy } = await setupApphierarchy(
basicAppHierarchyCreator_WithFields
)
const result = canDeleteRecord(appHierarchy.customerRecord)
expect(result.canDelete).toBe(false)
expect(result.errors.some(e => e.includes("customer_index"))).toBe(true)
})
it("should return errors when record has a child which cannot be deleted", async () => {
const { appHierarchy } = await setupApphierarchy(
basicAppHierarchyCreator_WithFields_AndIndexes
)
const result = canDeleteRecord(appHierarchy.customerRecord)
expect(result.canDelete).toBe(false)
expect(result.errors.some(e => e.includes("Outstanding Invoices"))).toBe(true)
})
})

View file

@ -1,124 +0,0 @@
import { isDefined, join, fieldDefinitions, $ } from "../src/common"
import { getMemoryTemplateApi } from "./specHelpers"
import { fieldErrors } from "../src/templateApi/fields"
const getRecordTemplate = templateApi =>
$(templateApi.getNewRootLevel(), [templateApi.getNewRecordTemplate])
const getValidField = templateApi => {
const field = templateApi.getNewField("string")
field.name = "forename"
field.label = "forename"
return field
}
const testMemberIsNotSet = membername => async () => {
const { templateApi } = await getMemoryTemplateApi()
const field = getValidField(templateApi)
field[membername] = ""
const errorsNotSet = templateApi.validateField([field])(field)
expect(errorsNotSet.length).toBe(1)
expect(errorsNotSet[0].error.includes("is not set")).toBeTruthy()
}
const testMemberIsNotDefined = membername => async () => {
const { templateApi } = await getMemoryTemplateApi()
const field = getValidField(templateApi)
delete field[membername]
const errorsNotSet = templateApi.validateField([field])(field)
expect(errorsNotSet.length).toBe(1)
expect(errorsNotSet[0].error.includes("is not set")).toBeTruthy()
}
describe("validateField", () => {
it("should return error when name is not set", testMemberIsNotSet("name"))
it(
"should return error when name is not defined",
testMemberIsNotDefined("name")
)
it("should return error when type is not set", testMemberIsNotSet("type"))
it(
"should return error when type is not defined",
testMemberIsNotDefined("type")
)
it(
"should return error when label is not defined",
testMemberIsNotDefined("label")
)
it(
"should return error when getInitialValue is not defined",
testMemberIsNotDefined("getInitialValue")
)
it(
"should return error when getInitialValue is not set",
testMemberIsNotSet("getInitialValue")
)
it(
"should return error when getUndefinedValue is not defined",
testMemberIsNotDefined("getUndefinedValue")
)
it(
"should return error when getUndefinedValue is not set",
testMemberIsNotSet("getUndefinedValue")
)
it("should return no errors when valid field is supplied", async () => {
const { templateApi } = await getMemoryTemplateApi()
const field = getValidField(templateApi)
const errors = templateApi.validateField([field])(field)
expect(errors.length).toBe(0)
})
it("should return error when field with same name exists already", async () => {
const { templateApi } = await getMemoryTemplateApi()
const field1 = getValidField(templateApi)
field1.name = "surname"
const field2 = getValidField(templateApi)
field2.name = "surname"
const errors = templateApi.validateField([field1, field2])(field2)
expect(errors.length).toBe(1)
expect(errors[0].error).toBe("field name is duplicated")
expect(errors[0].field).toBe("name")
})
it("should return error when field is not one of allowed types", async () => {
const { templateApi } = await getMemoryTemplateApi()
const field = getValidField(templateApi)
field.type = "sometype"
const errors = templateApi.validateField([field])(field)
expect(errors.length).toBe(1)
expect(errors[0].error).toBe("type is unknown")
expect(errors[0].field).toBe("type")
})
})
describe("addField", () => {
it("should throw exception when field is invalid", async () => {
const { templateApi } = await getMemoryTemplateApi()
const record = getRecordTemplate(templateApi)
const field = getValidField(templateApi)
field.name = ""
expect(() => templateApi.addField(record, field)).toThrow(
new RegExp("^" + fieldErrors.AddFieldValidationFailed, "i")
)
})
it("should add field when field is valid", async () => {
const { templateApi } = await getMemoryTemplateApi()
const record = getRecordTemplate(templateApi)
const field = getValidField(templateApi)
field.name = "some_new_field"
templateApi.addField(record, field)
expect(record.fields.length).toBe(1)
expect(record.fields[0]).toBe(field)
})
})

View file

@ -1,240 +0,0 @@
import { newField, fieldsToSchema, schemaToFields } from "../src/schema/types"
describe("fields to JSON schema", () => {
it("should convert text field to string", () => {
const field = newField("surname", "text")
const schema = fieldsToSchema([field])
expect(schema.properties.surname.type).toBe("string")
expect(schema.properties.surname.format).toBeUndefined()
expect(schema.properties.surname.default).toBe("")
})
it("should add required field", () => {
const field = newField("surname", "text")
let schema = fieldsToSchema([field])
expect(schema.required).toEqual([])
field.required = true
schema = fieldsToSchema([field])
expect(schema.required).toEqual(["surname"])
})
it("should convert boolean field to boolean", () => {
const field = newField("active", "boolean")
const schema = fieldsToSchema([field])
expect(schema.properties.active.type).toBe("boolean")
expect(schema.properties.active.default).toBe(false)
})
it("should convert datetime field to formatted string", () => {
const field = newField("surname", "datetime")
const schema = fieldsToSchema([field])
const datetimeCondition = schema.properties.surname.anyOf.find(s => s.type === "string" && s.format === "date-time")
expect(datetimeCondition).toBeDefined()
const blankCondition = schema.properties.surname.anyOf.find(s => s.const === "")
expect(blankCondition).toBeDefined()
expect(schema.properties.surname.default).toBe("")
})
it("should convert link field to object", () => {
const field = newField("contact", "link")
field.modelId = "1234"
field.viewId = "5678"
const schema = fieldsToSchema([field])
expect(schema.properties.contact.type).toBe("object")
expect(schema.properties.contact.required).toEqual(["_id"])
expect(schema.properties.contact.default).toEqual({ _id: "" })
expect(schema.properties.contact.properties).toEqual({
_id: { type: "string" },
modelId: { const: "1234" },
viewId: { const: "5678" },
})
})
it("should convert number field to number", () => {
const field = newField("age", "number")
field.maximum = 1234
field.minimum = -5678
const schema = fieldsToSchema([field])
expect(schema.properties).toEqual({
age: { type: "number", maximum: 1234, minimum: -5678}
})
})
it("should convert select to text with enum", () => {
const field = newField("status", "select")
field.enum = ["new", "complete"]
const schema = fieldsToSchema([field])
expect(schema.properties).toEqual({
status: {
type: "string",
enum: ["new", "complete"],
default: "",
}
})
})
})
describe("JSON Schema to fields", () => {
it("should convert unformatted string to text", () => {
const schema = schemaWithProperty("name",
{
type: "string",
maxLength: 100,
minLength: 4,
})
const fields = schemaToFields(schema)
expect(fields).toEqual([
{
name: "name",
type: "text",
maxLength: 100,
minLength: 4,
required: false,
}
])
})
it("should convert date-time formatted string to datetime", () => {
const schema = schemaWithProperty("createdDate",
{
anyOf: [
{
type: "string",
format: "date-time",
},
{ const: "" },
]
})
const fields = schemaToFields(schema)
expect(fields).toEqual([
{
name: "createdDate",
type: "datetime",
required: false,
}
])
})
it("should convert number to number", () => {
const schema = schemaWithProperty("age",
{
type: "number",
maximum: 100,
minimum: 3,
})
const fields = schemaToFields(schema)
expect(fields).toEqual([
{
name: "age",
type: "number",
required: false,
maximum: 100,
minimum: 3,
}
])
})
it("should convert string with enum to select", () => {
const schema = schemaWithProperty("status",
{
type: "string",
enum: ["new", "complete"]
})
const fields = schemaToFields(schema)
expect(fields).toEqual([
{
name: "status",
type: "select",
required: false,
enum: ["new", "complete"],
}
])
})
it("should convert boolean to boolean", () => {
const schema = schemaWithProperty("active",
{
type: "boolean",
})
const fields = schemaToFields(schema)
expect(fields).toEqual([
{
name: "active",
type: "boolean",
required: false,
}
])
})
it("should convert object with modelId & viewId to link", () => {
const schema = schemaWithProperty("contact",
{
type: "object",
properties: {
_id: { type: "string" },
modelId: { const: "1234" },
viewId: { const: null },
}
})
const fields = schemaToFields(schema)
expect(fields).toEqual([
{
name: "contact",
type: "link",
required: false,
modelId: "1234",
viewId: null,
}
])
})
it("should flag required field", () => {
const schema = schemaWithProperty("name",
{
type: "string",
maxLength: 100,
minLength: 4,
})
schema.required = ["name"]
const fields = schemaToFields(schema)
expect(fields[0].required).toBe(true)
})
function schemaWithProperty(name, prop) {
const schema = {
type: "object",
properties: {},
required: [],
}
schema.properties[name] = prop
return schema
}
})

View file

@ -1,137 +0,0 @@
import { testSchema } from "./testSchema.mjs"
import { validateRecord } from "../src/records/validateRecord.js"
import { getNewRecord } from "../src/records/getNewRecord.mjs"
describe("validateRecord", () => {
it("should return errors when any fields do not parse", () => {
const schema = testSchema()
const record = getNewRecord(schema, "Contact")
record.Name = "Ledog"
record["Is Active"] = "hello"
record.Created = "not a date"
const validationResult = validateRecord(schema, record)
expect(validationResult.isValid).toBe(false)
expect(validationResult.errors.length).toBe(2)
})
it("should return errors when mandatory field is empty", () => {
const schema = testSchema()
const record = getNewRecord(schema, "Contact")
record.Name = ""
const validationResult = validateRecord(schema, record)
expect(validationResult.isValid).toBe(false)
expect(validationResult.errors.length).toBe(1)
})
it("should return error when string field is beyond maxLength", () => {
const schema = testSchema()
schema.findField("Contact", "Name").typeOptions.maxLength = 5
const record = getNewRecord(schema, "Contact")
record.Name = "more than 5 characters"
const validationResult = validateRecord(schema, record)
expect(validationResult.isValid).toBe(false)
expect(validationResult.errors.length).toBe(1)
})
it("should return error when number field is > maxValue", () => {
const schema = testSchema()
schema.findField("Deal", "Estimated Value").typeOptions.maxValue = 5
const record = getNewRecord(schema, "Deal")
record["Estimated Value"] = 10
const validationResult = validateRecord(schema, record)
expect(validationResult.isValid).toBe(false)
expect(validationResult.errors.length).toBe(1)
})
it("should return error when number field is < minValue", () => {
const schema = testSchema()
schema.findField("Deal", "Estimated Value").typeOptions.minValue = 5
const record = getNewRecord(schema, "Deal")
record["Estimated Value"] = 1
const result = validateRecord(schema, record)
expect(result.isValid).toBe(false)
expect(result.errors.length).toBe(1)
})
it("should return error when number has too many decimal places", () => {
const schema = testSchema()
schema.findField("Deal", "Estimated Value").typeOptions.decimalPlaces = 2
const record = getNewRecord(schema, "Deal")
record["Estimated Value"] = 1.123
const result = validateRecord(schema, record)
expect(result.isValid).toBe(false)
expect(result.errors.length).toBe(1)
})
it("should return error when datetime field is > maxValue", () => {
const schema = testSchema()
schema.findField("Contact", "Created").typeOptions.maxValue = new Date(2020, 1, 1)
const record = getNewRecord(schema, "Contact")
record.Name = "Bob"
record.Created = new Date(2020, 1, 2)
const result = validateRecord(schema, record)
expect(result.isValid).toBe(false)
expect(result.errors.length).toBe(1)
})
it("should return error when number field is < minValue", () => {
const schema = testSchema()
schema.findField("Contact", "Created").typeOptions.minValue = new Date(2020, 1, 2)
const record = getNewRecord(schema, "Contact")
record.Name = "Bob"
record.Created = new Date(2020, 1, 1)
const result = validateRecord(schema, record)
expect(result.isValid).toBe(false)
expect(result.errors.length).toBe(1)
})
it("should return error when string IS NOT one of declared values, and only declared values are allowed", () => {
const schema = testSchema()
schema.findField("Contact", "Status").typeOptions.allowDeclaredValuesOnly = true
schema.findField("Contact", "Status").typeOptions.values = ["thedog"]
const record = getNewRecord(schema, "Contact")
record.Status = "not allowed"
record.Name = "Bob"
const result = validateRecord(schema, record)
expect(result.isValid).toBe(false)
expect(result.errors.length).toBe(1)
})
it("should not return error when string IS one of declared values, and only declared values are allowed", () => {
const schema = testSchema()
schema.findField("Contact", "Status").typeOptions.allowDeclaredValuesOnly = true
schema.findField("Contact", "Status").typeOptions.values = ["thedog"]
const record = getNewRecord(schema, "Contact")
record.Status = "thedog"
record.Name = "Bob"
const result = validateRecord(schema, record)
expect(result.isValid).toBe(true)
expect(result.errors.length).toBe(0)
})
it("should not return error when string IS NOT one of declared values, but any values are allowed", () => {
const schema = testSchema()
schema.findField("Contact", "Status").typeOptions.allowDeclaredValuesOnly = false
schema.findField("Contact", "Status").typeOptions.values = ["thedog"]
const record = getNewRecord(schema, "Contact")
record.Status = "not one of the values"
record.Name = "Bob"
const result = validateRecord(schema, record)
expect(result.isValid).toBe(true)
expect(result.errors.length).toBe(0)
})
})

File diff suppressed because it is too large Load diff

View file

@ -1,34 +0,0 @@
import { isNothing } from "../common"
export const getDatabaseManager = databaseManager => ({
createEmptyMasterDb: createEmptyMasterDb(databaseManager),
createEmptyInstanceDb: createEmptyInstanceDb(databaseManager),
getInstanceDbRootConfig: databaseManager.getInstanceDbRootConfig,
masterDatastoreConfig: getMasterDatastoreConfig(databaseManager),
getInstanceDatastoreConfig: getInstanceDatastoreConfig(databaseManager),
})
const getMasterDatastoreConfig = databaseManager =>
databaseManager.getDatastoreConfig("master")
const getInstanceDatastoreConfig = databaseManager => (
applicationId,
instanceId
) => databaseManager.getDatastoreConfig(applicationId, instanceId)
const createEmptyMasterDb = databaseManager => async () =>
await databaseManager.createEmptyDb("master")
const createEmptyInstanceDb = databaseManager => async (
applicationId,
instanceId
) => {
if (isNothing(applicationId)) {
throw new Error("CreateDb: application id not supplied")
}
if (isNothing(instanceId)) {
throw new Error("CreateDb: instance id not supplied")
}
return await databaseManager.createEmptyDb(applicationId, instanceId)
}

View file

@ -105,7 +105,6 @@ export { getIndexApi } from "./indexApi"
export { setupDatastore } from "./appInitialise"
export { getActionsApi } from "./actionsApi"
export { initialiseData } from "./appInitialise/initialiseData"
export { getDatabaseManager } from "./appInitialise/databaseManager"
export { hierarchy }
export { common }
export { crypto }

View file

@ -2,14 +2,6 @@ const jwt = require("jsonwebtoken");
const CouchDB = require("../../db");
const bcrypt = require("../../utilities/bcrypt");
exports.forgotPassword = async ctx => {
};
exports.setPassword = async ctx => { };
exports.changePassword = async ctx => {
};
exports.authenticate = async ctx => {
const { username, password } = ctx.request.body;
@ -17,7 +9,7 @@ exports.authenticate = async ctx => {
if (!password) ctx.throw(400, "Password Required");
// query couch for their username
const db = new CouchDB(ctx.params.instanceId);
const db = new CouchDB(ctx.params.clientId);
const dbUser = await db.query("by_username", {
include_docs: true,
key: username

View file

@ -1,5 +1,7 @@
const CouchDB = require("../../db");
const { schemaValidator } = require("../../../common/lib");
const Ajv = require("ajv");
const ajv = new Ajv();
exports.save = async function(ctx) {
const db = new CouchDB(ctx.params.instanceId);
@ -7,7 +9,7 @@ exports.save = async function(ctx) {
// validation with ajv
const model = await db.get(record.modelId)
const validate = schemaValidator.compile({
const validate = ajv.compile({
properties: model.schema
});
const valid = validate(record)

View file

@ -20,9 +20,8 @@ exports.serveApp = async function(ctx) {
// TODO: Hook up to JWT auth in real app
// TODO: serve CSS and other assets
// resolve unauthenticated page if user not authenticated
// resolve main page if user authenticated
await send(ctx, "/index.html", { root: appPath })
await send(ctx, ctx.file, { root: appPath })
}
exports.serveComponentLibrary = async function(ctx) {

View file

@ -1,30 +1,23 @@
const Router = require("@koa/router")
const session = require("../middleware/session")
const authenticated = require("../middleware/authenticated");
const compress = require("koa-compress");
const zlib = require("zlib");
const { resolve } = require("path")
const { homedir } = require("os")
const send = require("koa-send")
const {
componentLibraryInfo,
} = require("../utilities/builder")
const {
// componentRoutes,
authRoutes,
pageRoutes,
userRoutes,
authenticatedRoutes
recordRoutes,
instanceRoutes,
clientRoutes,
applicationRoutes,
modelRoutes,
viewRoutes,
staticRoutes,
componentRoutes
} = require("./routes");
const recordRoutes = require("./routes/neo/record");
const instanceRoutes = require("./routes/neo/instance");
const neoUserRoutes = require("./routes/neo/user");
const clientRoutes = require("./routes/neo/client");
const applicationRoutes = require("./routes/neo/application");
const modelsRoutes = require("./routes/neo/model");
const viewsRoutes = require("./routes/neo/view");
const staticRoutes = require("./routes/neo/static");
const componentRoutes = require("./routes/neo/component");
module.exports = app => {
const router = new Router()
@ -38,107 +31,15 @@ module.exports = app => {
flush: zlib.Z_SYNC_FLUSH,
}
}))
// .use(session(app))
.use(authenticated)
.use(async (ctx, next) => {
// TODO: temp dev middleware
// ctx.sessionId = ctx.session._sessCtx.externalKey
// ctx.session.accessed = true
ctx.isAuthenticated = true;
ctx.config = { latestPackagesFolder: resolve(homedir(), ".budibase") }
await next();
});
// .use(async (ctx, next) => {
// ctx.sessionId = ctx.session._sessCtx.externalKey
// ctx.session.accessed = true
// ctx.config = config
// const pathParts = ctx.path.split("/")
// if (pathParts.length < 2) {
// ctx.throw(StatusCodes.NOT_FOUND, "App Name not declared")
// }
// const appname = pathParts[1]
// ctx.set("x-bbappname", appname)
// if (appname === "_builder") {
// if (!config.dev) {
// ctx.response.status = StatusCodes.FORBIDDEN
// ctx.body = "run in dev mode to access builder"
// return
// }
// // Builder URLs should have admin access to the API
// if (ctx.path.startsWith("/_builder/instance/_master")) {
// const {
// instance,
// publicPath,
// sharedPath,
// } = await ctx.master.getFullAccessApiForMaster()
// ctx.instance = instance
// ctx.publicPath = publicPath
// ctx.sharedPath = sharedPath
// ctx.isAuthenticated = !!ctx.instance
// } else if (ctx.path.startsWith("/_builder/instance")) {
// const builderAppName = pathParts[3]
// const instanceId = pathParts[4]
// const {
// bbInstance,
// publicPath,
// sharedPath,
// } = await ctx.master.getFullAccessApiForInstanceId(
// builderAppName,
// instanceId
// )
// ctx.instance = bbInstance
// ctx.publicPath = publicPath
// ctx.sharedPath = sharedPath
// ctx.isAuthenticated = !!ctx.instance
// }
// await next()
// } else {
// const instance = await ctx.master.getInstanceApiForSession(
// appname,
// ctx.sessionId
// )
// ctx.instance = instance.instance
// ctx.publicPath = instance.publicPath
// ctx.sharedPath = instance.sharedPath
// ctx.isAuthenticated = !!instance.instance
// await next()
// }
// })
router
// .get("/_builder", async ctx => {
// await send(ctx, "/index.html", { root: builderPath })
// })
// .get("/_builder/:appname/componentlibrary", async ctx => {
// const info = await componentLibraryInfo(
// ctx.config,
// ctx.params.appname,
// ctx.query.lib
// )
// await send(ctx, info.components._lib || "index.js", { root: info.libDir })
// })
// .get("/_builder/*", async (ctx, next) => {
// const path = ctx.path.replace("/_builder", "")
// const isFile = new RegExp(/(.+\..{1,5})/g).test(path)
// if (path.startsWith("/api/") || path.startsWith("/instance/")) {
// await next()
// } else if (isFile) {
// await send(ctx, path, { root: builderPath })
// } else {
// await send(ctx, "/index.html", { root: builderPath })
// }
// })
// Neo
// error handling middleware
router.use(async (ctx, next) => {
try {
@ -153,25 +54,17 @@ module.exports = app => {
}
});
// Legacy Routes
router.use(userRoutes.routes());
router.use(userRoutes.allowedMethods());
// router.use(appsRoutes.routes())
// router.use(appsRoutes.allowedMethods());
// router.use(componentRoutes.routes());
// router.use(componentRoutes.allowedMethods());
router.use(authRoutes.routes());
router.use(authRoutes.allowedMethods());
router.use(pageRoutes.routes());
router.use(pageRoutes.allowedMethods());
// Neo Routes
router.use(staticRoutes.routes());
router.use(staticRoutes.allowedMethods());
router.use(viewRoutes.routes());
router.use(viewRoutes.allowedMethods());
router.use(viewsRoutes.routes());
router.use(viewsRoutes.allowedMethods());
router.use(modelsRoutes.routes());
router.use(modelsRoutes.allowedMethods());
router.use(modelRoutes.routes());
router.use(modelRoutes.allowedMethods());
router.use(applicationRoutes.routes());
router.use(applicationRoutes.allowedMethods());
@ -182,26 +75,19 @@ module.exports = app => {
router.use(clientRoutes.routes());
router.use(clientRoutes.allowedMethods());
router.use(neoUserRoutes.routes());
router.use(neoUserRoutes.allowedMethods());
router.use(userRoutes.routes());
router.use(userRoutes.allowedMethods());
router.use(recordRoutes.routes());
router.use(recordRoutes.allowedMethods());
router.use(instanceRoutes.routes());
router.use(instanceRoutes.allowedMethods());
// end of Neo
// router
// .get("/:appname", async ctx => {
// await send(ctx, "/index.html", { root: ctx.publicPath })
// })
// .get("/:appname/*", routeHandlers.appDefault)
// .get("/_builder/instance/:appname/:instanceid/*", routeHandlers.appDefault)
router.use(staticRoutes.routes());
router.use(staticRoutes.allowedMethods());
// router.use(authenticatedRoutes.routes());
// router.use(authenticatedRoutes.allowedMethods());
router.redirect("/", "/_builder");
return router
}

View file

@ -1,5 +1,5 @@
const Router = require("@koa/router");
const controller = require("../../controllers/application");
const controller = require("../controllers/application");
const router = Router();

View file

@ -1,5 +1,5 @@
const Router = require("@koa/router");
const controller = require("../../controllers/auth");
const controller = require("../controllers/auth");
const router = Router();

View file

@ -1,132 +0,0 @@
const Router = require("@koa/router");
const StatusCodes = require("../../utilities/statusCodes")
const routeHandlers = require("../../middleware/routeHandlers")
const router = Router();
// async function isAuthenticated(ctx, next) {
// if (ctx.isAuthenticated) {
// await next()
// } else {
// ctx.response.status = StatusCodes.UNAUTHORIZED
// }
// }
// router.use(isAuthenticated)
// router.post(
// "/_builder/instance/:appname/:instanceid/api/upgradeData",
// routeHandlers.upgradeData
// )
// router.post("/:appname/api/changeMyPassword", routeHandlers.changeMyPassword)
// router.post(
// "/_builder/instance/:appname/:instanceid/api/changeMyPassword",
// routeHandlers.changeMyPassword
// )
// router.post(
// "/:appname/api/executeAction/:actionname",
// routeHandlers.executeAction
// )
// router.post(
// "/_builder/instance/:appname/:instanceid/api/executeAction/:actionname",
// routeHandlers.executeAction
// )
// router.post("/:appname/api/createUser", routeHandlers.createUser)
// router.post(
// "/_builder/instance/:appname/:instanceid/api/createUser",
// routeHandlers.createUser
// )
// router.post("/:appname/api/enableUser", routeHandlers.enableUser)
// router.post(
// "/_builder/instance/:appname/:instanceid/api/enableUser",
// routeHandlers.enableUser
// )
// router.post("/:appname/api/disableUser", routeHandlers.disableUser)
// router.post(
// "/_builder/instance/:appname/:instanceid/api/disableUser",
// routeHandlers.disableUser
// )
// router.get("/:appname/api/users", routeHandlers.getUsers)
// router.get(
// "/_builder/instance/:appname/:instanceid/api/users",
// routeHandlers.getUsers
// )
// router.get("/:appname/api/accessLevels", routeHandlers.getAccessLevels)
// router.get(
// "/_builder/instance/:appname/:instanceid/api/accessLevels",
// routeHandlers.getAccessLevels
// )
// router.get("/:appname/api/listRecords/*", routeHandlers.listRecordsGet)
// router.get(
// "/_builder/instance/:appname/:instanceid/api/listRecords/*",
// routeHandlers.listRecordsGet
// )
// router.post("/:appname/api/listRecords/*", routeHandlers.listRecordsPost)
// router.post(
// "/_builder/instance/:appname/:instanceid/api/listRecords/*",
// routeHandlers.listRecordsPost
// )
// router.post("/:appname/api/aggregates/*", routeHandlers.aggregatesPost)
// router.post(
// "/_builder/instance/:appname/:instanceid/api/aggregates/*",
// routeHandlers.aggregatesPost
// )
// router.post("/:appname/api/files/*", routeHandlers.postFiles)
// router.post(
// "/_builder/instance/:appname/:instanceid/api/files/*",
// routeHandlers.postFiles
// )
// router.post("/:appname/api/record/*", routeHandlers.saveRecord)
// router.post(
// "/_builder/instance/:appname/:instanceid/api/record/*",
// routeHandlers.saveRecord
// )
// router.get("/:appname/api/lookup_field/*", routeHandlers.lookupField)
// router.get(
// "/_builder/instance/:appname/:instanceid/api/lookup_field/*",
// routeHandlers.lookupField
// )
// router.get("/:appname/api/record/*", routeHandlers.getRecord)
// router.get(
// "/_builder/instance/:appname/:instanceid/api/record/*",
// routeHandlers.getRecord
// )
// router.del("/:appname/api/record/*", routeHandlers.deleteRecord)
// router.del(
// "/_builder/instance/:appname/:instanceid/api/record/*",
// routeHandlers.deleteRecord
// )
// router.post("/:appname/api/apphierarchy", routeHandlers.saveAppHierarchy)
module.exports = router

View file

@ -1,5 +1,5 @@
const Router = require("@koa/router");
const controller = require("../../controllers/client");
const controller = require("../controllers/client");
const router = Router();

View file

@ -1,5 +1,5 @@
const Router = require("@koa/router");
const controller = require("../../controllers/component");
const controller = require("../controllers/component");
const router = Router();

View file

@ -1,47 +0,0 @@
const Router = require("@koa/router");
const send = require("koa-send")
const StatusCodes = require("../../utilities/statusCodes")
const {
componentLibraryInfo,
} = require("../../utilities/builder")
const router = Router();
// router.get("/_builder/:appname/componentlibrary", async ctx => {
// const info = await componentLibraryInfo(
// ctx.config,
// ctx.params.appname,
// ctx.query.lib
// )
// await send(ctx, info.components._lib || "index.js", { root: info.libDir })
// })
// router.get("/_builder/api/:appname/components", async ctx => {
// try {
// ctx.body = getComponentDefinitions(
// ctx.config,
// ctx.params.appname,
// ctx.query.lib
// )
// ctx.response.status = StatusCodes.OK
// } catch (e) {
// if (e.status) {
// ctx.response.status = e.status
// } else {
// throw e
// }
// }
// })
// router.get("/_builder/api/:appname/componentlibrary", async ctx => {
// const info = await componentLibraryInfo(
// ctx.config,
// ctx.params.appname,
// ctx.query.lib ? decodeURI(ctx.query.lib) : ""
// )
// ctx.body = info.components
// ctx.response.status = StatusCodes.OK
// })
module.exports = router

View file

@ -1,11 +1,25 @@
const authRoutes = require("./auth");
const pageRoutes = require("./pages");
const componentRoutes = require("./components");
const userRoutes = require("./user");
const authenticatedRoutes = require("./authenticated");
const recordRoutes = require("./record");
const instanceRoutes = require("./instance");
const clientRoutes = require("./client");
const applicationRoutes = require("./application");
const modelRoutes = require("./model");
const viewRoutes = require("./view");
const staticRoutes = require("./static");
const componentRoutes = require("./component");
module.exports = {
authRoutes,
pageRoutes,
componentRoutes,
userRoutes,
authenticatedRoutes
recordRoutes,
instanceRoutes,
clientRoutes,
applicationRoutes,
modelRoutes,
viewRoutes,
staticRoutes,
componentRoutes
};

View file

@ -1,5 +1,5 @@
const Router = require("@koa/router");
const controller = require("../../controllers/instance");
const controller = require("../controllers/instance");
const router = Router();

View file

@ -1,5 +1,5 @@
const Router = require("@koa/router");
const controller = require("../../controllers/model");
const Router = require("@koa/router");
const controller = require("../controllers/model");
const router = Router();

Some files were not shown because too many files have changed in this diff Show more