2020-04-14 21:25:37 +12:00
{
"version": 3,
"file": "bundle.js",
"sources": [
"../node_modules/svelte/internal/index.mjs",
"../node_modules/svelte/store/index.mjs",
"../../client/src/core/createCoreApp.js",
"../node_modules/lodash/lodash.min.js",
"../node_modules/lodash/fp/_mapping.js",
"../node_modules/lodash/fp/placeholder.js",
"../node_modules/lodash/fp/_baseConvert.js",
"../node_modules/lodash/fp.js",
"../node_modules/shortid/lib/random/random-from-seed.js",
"../node_modules/shortid/lib/alphabet.js",
"../node_modules/shortid/lib/random/random-byte-browser.js",
"../node_modules/nanoid/format.js",
"../node_modules/shortid/lib/generate.js",
"../node_modules/shortid/lib/build.js",
"../node_modules/shortid/lib/is-valid.js",
"../node_modules/shortid/lib/index.js",
"../node_modules/shortid/index.js",
"../node_modules/lodash/lodash.js",
"../../core/src/common/events.js",
"../../core/src/common/errors.js",
"../../core/src/common/apiWrapper.js",
"../node_modules/bcryptjs/dist/bcrypt.js",
"../../core/src/common/index.js",
"../../core/src/common/validationCommon.js",
"../node_modules/@nx-js/compiler-util/dist/es.es5.js",
"../../core/src/indexing/evaluate.js",
"../../core/src/templateApi/indexes.js",
"../../core/src/templateApi/hierarchy.js",
"../../core/src/types/typeHelpers.js",
"../../core/src/types/string.js",
"../../core/src/types/bool.js",
"../../core/src/types/number.js",
"../../core/src/types/datetime.js",
"../../core/src/types/array.js",
"../../core/src/types/reference.js",
"../../core/src/types/file.js",
"../../core/src/types/index.js",
"../../core/src/authApi/authCommon.js",
"../../core/src/authApi/isAuthorized.js",
"../../core/src/authApi/permissions.js",
"../../core/src/recordApi/getNew.js",
"../../core/src/templateApi/createNodes.js",
"../../client/src/core/index.js",
"../../client/src/state/isState.js",
"../../client/src/state/getState.js",
"../../client/src/state/setState.js",
"../../client/src/common/trimSlash.js",
"../../client/src/state/standardState.js",
"../../client/src/api/loadRecord.js",
"../../client/src/api/listRecords.js",
"../../client/src/api/authenticate.js",
"../../client/src/api/saveRecord.js",
"../../client/src/api/index.js",
"../../client/src/state/coreHandlers.js",
"../../client/src/state/eventHandlers.js",
"../../client/src/state/stateBinding.js",
"../../client/src/render/renderComponent.js",
"../../client/src/render/builtinComponents.js",
"../../client/src/render/attachChildren.js",
"../../client/node_modules/regexparam/dist/regexparam.mjs",
"../../client/src/render/screenRouter.js",
"../../client/src/createApp.js",
"../src/Container.svelte",
"../src/buildStyle.js",
"../src/Text.svelte",
"../src/Heading.svelte",
"../src/Input.svelte",
"../src/Select.svelte",
"../src/Option.svelte",
"../src/cssVars.js",
"../src/Button.svelte",
"../src/Login.svelte",
"../src/Nav.svelte",
"../src/Table.svelte",
"../src/Test/testComponents.js",
"../src/Test/rootComponent.js",
"../src/Test/createApp.js",
"../src/Test/props.js",
"../src/Test/TestApp.svelte",
"../src/Test/testMain.js"
],
"sourcesContent": [
"function noop() { }\nconst identity = x => x;\nfunction assign(tar, src) {\n // @ts-ignore\n for (const k in src)\n tar[k] = src[k];\n return tar;\n}\nfunction is_promise(value) {\n return value && typeof value === 'object' && typeof value.then === 'function';\n}\nfunction add_location(element, file, line, column, char) {\n element.__svelte_meta = {\n loc: { file, line, column, char }\n };\n}\nfunction run(fn) {\n return fn();\n}\nfunction blank_object() {\n return Object.create(null);\n}\nfunction run_all(fns) {\n fns.forEach(run);\n}\nfunction is_function(thing) {\n return typeof thing === 'function';\n}\nfunction safe_not_equal(a, b) {\n return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');\n}\nfunction not_equal(a, b) {\n return a != a ? b == b : a !== b;\n}\nfunction validate_store(store, name) {\n if (!store || typeof store.subscribe !== 'function') {\n throw new Error(`'${name}' is not a store with a 'subscribe' method`);\n }\n}\nfunction subscribe(store, callback) {\n const unsub = store.subscribe(callback);\n return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;\n}\nfunction get_store_value(store) {\n let value;\n subscribe(store, _ => value = _)();\n return value;\n}\nfunction component_subscribe(component, store, callback) {\n component.$$.on_destroy.push(subscribe(store, callback));\n}\nfunction create_slot(definition, ctx, fn) {\n if (definition) {\n const slot_ctx = get_slot_context(definition, ctx, fn);\n return definition[0](slot_ctx);\n }\n}\nfunction get_slot_context(definition, ctx, fn) {\n return definition[1]\n ? assign({}, assign(ctx.$$scope.ctx, definition[1](fn ? fn(ctx) : {})))\n : ctx.$$scope.ctx;\n}\nfunction get_slot_changes(definition, ctx, changed, fn) {\n return definition[1]\n ? assign({}, assign(ctx.$$scope.changed || {}, definition[1](fn ? fn(changed) : {})))\n : ctx.$$scope.changed || {};\n}\nfunction exclude_internal_props(props) {\n const result = {};\n for (const k in props)\n if (k[0] !== '$')\n result[k] = props[k];\n return result;\n}\nfunction once(fn) {\n let ran = false;\n return function (...args) {\n if (ran)\n return;\n ran = true;\n fn.call(this, ...args);\n };\n}\nfunction null_to_empty(value) {\n return value == null ? '' : value;\n}\nfunction set_store_value(store, ret, value = ret) {\n store.set(value);\n return ret;\n}\n\nconst is_client = typeof window !== 'undefined';\nlet now = is_client\n ? () => window.performance.now()\n : () => Date.now();\nlet raf = is_client ? cb => requestAnimationFrame(cb) : noop;\n// used internally for testing\nfunction set_now(fn) {\n now = fn;\n}\nfunction set_raf(fn) {\n raf = fn;\n}\n\nconst tasks = new Set();\nlet running = false;\nfunction run_tasks() {\n tasks.forEach(task => {\n if (!task[0](now())) {\n tasks.delete(task);\n task[1]();\n }\n });\n running = tasks.size > 0;\n if (running)\n raf(run_tasks);\n}\nfunction clear_loops() {\n // for testing...\n tasks.forEach(task => tasks.delete(task));\n running = false;\n}\nfunction loop(fn) {\n let task;\n if (!running) {\n running = true;\n raf(run_tasks);\n }\n return {\n promise: new Promise(fulfil => {\n tasks.add(task = [fn, fulfil]);\n }),\n abort() {\n tasks.delete(task);\n }\n };\n}\n\nfunction append(target, node) {\n target.appendChild(node);\n}\nfunction insert(target, node, anchor) {\n target.insertBefore(node, anchor || null);\n}\nfunction detach(node) {\n node.parentNode.removeChild(node);\n}\nfunction destroy_each(iterations, detaching) {\n for (let i = 0; i < iterations.length; i += 1) {\n if (iterations[i])\n iterations[i].d(detaching);\n }\n}\nfunction element(name) {\n return document.createElement(name);\n}\nfunctio
"import { safe_not_equal, noop, run_all, is_function } from '../internal';\nexport { get_store_value as get } from '../internal';\n\nconst subscriber_queue = [];\n/**\n * Creates a `Readable` store that allows reading by subscription.\n * @param value initial value\n * @param {StartStopNotifier}start start and stop notifications for subscriptions\n */\nfunction readable(value, start) {\n return {\n subscribe: writable(value, start).subscribe,\n };\n}\n/**\n * Create a `Writable` store that allows both updating and reading by subscription.\n * @param {*=}value initial value\n * @param {StartStopNotifier=}start start and stop notifications for subscriptions\n */\nfunction writable(value, start = noop) {\n let stop;\n const subscribers = [];\n function set(new_value) {\n if (safe_not_equal(value, new_value)) {\n value = new_value;\n if (stop) { // store is ready\n const run_queue = !subscriber_queue.length;\n for (let i = 0; i < subscribers.length; i += 1) {\n const s = subscribers[i];\n s[1]();\n subscriber_queue.push(s, value);\n }\n if (run_queue) {\n for (let i = 0; i < subscriber_queue.length; i += 2) {\n subscriber_queue[i][0](subscriber_queue[i + 1]);\n }\n subscriber_queue.length = 0;\n }\n }\n }\n }\n function update(fn) {\n set(fn(value));\n }\n function subscribe(run, invalidate = noop) {\n const subscriber = [run, invalidate];\n subscribers.push(subscriber);\n if (subscribers.length === 1) {\n stop = start(set) || noop;\n }\n run(value);\n return () => {\n const index = subscribers.indexOf(subscriber);\n if (index !== -1) {\n subscribers.splice(index, 1);\n }\n if (subscribers.length === 0) {\n stop();\n stop = null;\n }\n };\n }\n return { set, update, subscribe };\n}\n/**\n * Derived value store by synchronizing one or more readable stores and\n * applying an aggregation function over its input values.\n * @param {Stores} stores input stores\n * @param {function(Stores=, function(*)=):*}fn function callback that aggregates the values\n * @param {*=}initial_value when used asynchronously\n */\nfunction derived(stores, fn, initial_value) {\n const single = !Array.isArray(stores);\n const stores_array = single\n ? [stores]\n : stores;\n const auto = fn.length < 2;\n return readable(initial_value, (set) => {\n let inited = false;\n const values = [];\n let pending = 0;\n let cleanup = noop;\n const sync = () => {\n if (pending) {\n return;\n }\n cleanup();\n const result = fn(single ? values[0] : values, set);\n if (auto) {\n set(result);\n }\n else {\n cleanup = is_function(result) ? result : noop;\n }\n };\n const unsubscribers = stores_array.map((store, i) => store.subscribe((value) => {\n values[i] = value;\n pending &= ~(1 << i);\n if (inited) {\n sync();\n }\n }, () => {\n pending |= (1 << i);\n }));\n inited = true;\n sync();\n return function stop() {\n run_all(unsubscribers);\n cleanup();\n };\n });\n}\n\nexport { derived, readable, writable };\n",
"export const createCoreApp = (backendDefinition, user) => {\r\n const app = {\r\n datastore: null,\r\n crypto: null,\r\n publish: () => {},\r\n hierarchy: backendDefinition.hierarchy,\r\n actions: backendDefinition.actions,\r\n user,\r\n }\r\n\r\n return app\r\n}\r\n",
"/**\n * @license\n * Lodash lodash.com/license | Underscore.js 1.8.3 underscorejs.org/LICENSE\n */\n;(function(){function n(n,t,r){switch(r.length){case 0:return n.call(t);case 1:return n.call(t,r[0]);case 2:return n.call(t,r[0],r[1]);case 3:return n.call(t,r[0],r[1],r[2])}return n.apply(t,r)}function t(n,t,r,e){for(var u=-1,i=null==n?0:n.length;++u<i;){var o=n[u];t(e,o,r(o),n)}return e}function r(n,t){for(var r=-1,e=null==n?0:n.length;++r<e&&false!==t(n[r],r,n););return n}function e(n,t){for(var r=null==n?0:n.length;r--&&false!==t(n[r],r,n););return n}function u(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(!t(n[r],r,n))return false;\nreturn true}function i(n,t){for(var r=-1,e=null==n?0:n.length,u=0,i=[];++r<e;){var o=n[r];t(o,r,n)&&(i[u++]=o)}return i}function o(n,t){return!(null==n||!n.length)&&-1<v(n,t,0)}function f(n,t,r){for(var e=-1,u=null==n?0:n.length;++e<u;)if(r(t,n[e]))return true;return false}function c(n,t){for(var r=-1,e=null==n?0:n.length,u=Array(e);++r<e;)u[r]=t(n[r],r,n);return u}function a(n,t){for(var r=-1,e=t.length,u=n.length;++r<e;)n[u+r]=t[r];return n}function l(n,t,r,e){var u=-1,i=null==n?0:n.length;for(e&&i&&(r=n[++u]);++u<i;)r=t(r,n[u],u,n);\nreturn r}function s(n,t,r,e){var u=null==n?0:n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);return r}function h(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(t(n[r],r,n))return true;return false}function p(n,t,r){var e;return r(n,function(n,r,u){if(t(n,r,u))return e=r,false}),e}function _(n,t,r,e){var u=n.length;for(r+=e?1:-1;e?r--:++r<u;)if(t(n[r],r,n))return r;return-1}function v(n,t,r){if(t===t)n:{--r;for(var e=n.length;++r<e;)if(n[r]===t){n=r;break n}n=-1}else n=_(n,d,r);return n}function g(n,t,r,e){\n--r;for(var u=n.length;++r<u;)if(e(n[r],t))return r;return-1}function d(n){return n!==n}function y(n,t){var r=null==n?0:n.length;return r?m(n,t)/r:F}function b(n){return function(t){return null==t?T:t[n]}}function x(n){return function(t){return null==n?T:n[t]}}function j(n,t,r,e,u){return u(n,function(n,u,i){r=e?(e=false,n):t(r,n,u,i)}),r}function w(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].c;return n}function m(n,t){for(var r,e=-1,u=n.length;++e<u;){var i=t(n[e]);i!==T&&(r=r===T?i:r+i)}return r;\n}function A(n,t){for(var r=-1,e=Array(n);++r<n;)e[r]=t(r);return e}function E(n,t){return c(t,function(t){return[t,n[t]]})}function k(n){return function(t){return n(t)}}function S(n,t){return c(t,function(t){return n[t]})}function O(n,t){return n.has(t)}function I(n,t){for(var r=-1,e=n.length;++r<e&&-1<v(t,n[r],0););return r}function R(n,t){for(var r=n.length;r--&&-1<v(t,n[r],0););return r}function z(n){return\"\\\\\"+Un[n]}function W(n){var t=-1,r=Array(n.size);return n.forEach(function(n,e){r[++t]=[e,n];\n}),r}function B(n,t){return function(r){return n(t(r))}}function L(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){var o=n[r];o!==t&&\"__lodash_placeholder__\"!==o||(n[r]=\"__lodash_placeholder__\",i[u++]=r)}return i}function U(n){var t=-1,r=Array(n.size);return n.forEach(function(n){r[++t]=n}),r}function C(n){var t=-1,r=Array(n.size);return n.forEach(function(n){r[++t]=[n,n]}),r}function D(n){if(Rn.test(n)){for(var t=On.lastIndex=0;On.test(n);)++t;n=t}else n=Qn(n);return n}function M(n){return Rn.test(n)?n.match(On)||[]:n.split(\"\");\n}var T,$=1/0,F=NaN,N=[[\"ary\",128],[\"bind\",1],[\"bindKey\",2],[\"curry\",8],[\"curryRight\",16],[\"flip\",512],[\"partial\",32],[\"partialRight\",64],[\"rearg\",256]],P=/\\b__p\\+='';/g,Z=/\\b(__p\\+=)''\\+/g,q=/(__e\\(.*?\\)|\\b__t\\))\\+'';/g,V=/&(?:amp|lt|gt|quot|#39);/g,K=/[&<>\"']/g,G=RegExp(V.source),H=RegExp(K.source),J=/<%-([\\s\\S]+?)%>/g,Y=/<%([\\s\\S]+?)%>/g,Q=/<%=([\\s\\S]+?)%>/g,X=/\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,nn=/^\\w*$/,tn=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g,rn=/[\\\\^$.*+?()[\\]{}|]/g,en=RegExp(rn.source),un=/^\\s+|\\s+$/g,on=/^\\s+/,fn=/\\s+$/,cn=/\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,an=/\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,ln=/,? & /,sn=/[^\\x00-\\x2f\\x3
"/** Used to map aliases to their real names. */\nexports.aliasToReal = {\n\n // Lodash aliases.\n 'each': 'forEach',\n 'eachRight': 'forEachRight',\n 'entries': 'toPairs',\n 'entriesIn': 'toPairsIn',\n 'extend': 'assignIn',\n 'extendAll': 'assignInAll',\n 'extendAllWith': 'assignInAllWith',\n 'extendWith': 'assignInWith',\n 'first': 'head',\n\n // Methods that are curried variants of others.\n 'conforms': 'conformsTo',\n 'matches': 'isMatch',\n 'property': 'get',\n\n // Ramda aliases.\n '__': 'placeholder',\n 'F': 'stubFalse',\n 'T': 'stubTrue',\n 'all': 'every',\n 'allPass': 'overEvery',\n 'always': 'constant',\n 'any': 'some',\n 'anyPass': 'overSome',\n 'apply': 'spread',\n 'assoc': 'set',\n 'assocPath': 'set',\n 'complement': 'negate',\n 'compose': 'flowRight',\n 'contains': 'includes',\n 'dissoc': 'unset',\n 'dissocPath': 'unset',\n 'dropLast': 'dropRight',\n 'dropLastWhile': 'dropRightWhile',\n 'equals': 'isEqual',\n 'identical': 'eq',\n 'indexBy': 'keyBy',\n 'init': 'initial',\n 'invertObj': 'invert',\n 'juxt': 'over',\n 'omitAll': 'omit',\n 'nAry': 'ary',\n 'path': 'get',\n 'pathEq': 'matchesProperty',\n 'pathOr': 'getOr',\n 'paths': 'at',\n 'pickAll': 'pick',\n 'pipe': 'flow',\n 'pluck': 'map',\n 'prop': 'get',\n 'propEq': 'matchesProperty',\n 'propOr': 'getOr',\n 'props': 'at',\n 'symmetricDifference': 'xor',\n 'symmetricDifferenceBy': 'xorBy',\n 'symmetricDifferenceWith': 'xorWith',\n 'takeLast': 'takeRight',\n 'takeLastWhile': 'takeRightWhile',\n 'unapply': 'rest',\n 'unnest': 'flatten',\n 'useWith': 'overArgs',\n 'where': 'conformsTo',\n 'whereEq': 'isMatch',\n 'zipObj': 'zipObject'\n};\n\n/** Used to map ary to method names. */\nexports.aryMethod = {\n '1': [\n 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',\n 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',\n 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',\n 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',\n 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',\n 'uniqueId', 'words', 'zipAll'\n ],\n '2': [\n 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',\n 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',\n 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',\n 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',\n 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',\n 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',\n 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',\n 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',\n 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',\n 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',\n 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',\n 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',\n 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',\n 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',\n 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',\n 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',\n 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',\n 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',\n 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',\n 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',\n 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',\n 'zipObjectDeep'\n ],\n '3': [\n 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',\n 'findFrom', 'findIndexFrom', 'findLastFrom',
"/**\n * The default argument placeholder value for methods.\n *\n * @type {Object}\n */\nmodule.exports = {};\n",
"var mapping = require('./_mapping'),\n fallbackHolder = require('./placeholder');\n\n/** Built-in value reference. */\nvar push = Array.prototype.push;\n\n/**\n * Creates a function, with an arity of `n`, that invokes `func` with the\n * arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} n The arity of the new function.\n * @returns {Function} Returns the new function.\n */\nfunction baseArity(func, n) {\n return n == 2\n ? function(a, b) { return func.apply(undefined, arguments); }\n : function(a) { return func.apply(undefined, arguments); };\n}\n\n/**\n * Creates a function that invokes `func`, with up to `n` arguments, ignoring\n * any additional arguments.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @param {number} n The arity cap.\n * @returns {Function} Returns the new function.\n */\nfunction baseAry(func, n) {\n return n == 2\n ? function(a, b) { return func(a, b); }\n : function(a) { return func(a); };\n}\n\n/**\n * Creates a clone of `array`.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the cloned array.\n */\nfunction cloneArray(array) {\n var length = array ? array.length : 0,\n result = Array(length);\n\n while (length--) {\n result[length] = array[length];\n }\n return result;\n}\n\n/**\n * Creates a function that clones a given object using the assignment `func`.\n *\n * @private\n * @param {Function} func The assignment function.\n * @returns {Function} Returns the new cloner function.\n */\nfunction createCloner(func) {\n return function(object) {\n return func({}, object);\n };\n}\n\n/**\n * A specialized version of `_.spread` which flattens the spread array into\n * the arguments of the invoked `func`.\n *\n * @private\n * @param {Function} func The function to spread arguments over.\n * @param {number} start The start position of the spread.\n * @returns {Function} Returns the new function.\n */\nfunction flatSpread(func, start) {\n return function() {\n var length = arguments.length,\n lastIndex = length - 1,\n args = Array(length);\n\n while (length--) {\n args[length] = arguments[length];\n }\n var array = args[start],\n otherArgs = args.slice(0, start);\n\n if (array) {\n push.apply(otherArgs, array);\n }\n if (start != lastIndex) {\n push.apply(otherArgs, args.slice(start + 1));\n }\n return func.apply(this, otherArgs);\n };\n}\n\n/**\n * Creates a function that wraps `func` and uses `cloner` to clone the first\n * argument it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} cloner The function to clone arguments.\n * @returns {Function} Returns the new immutable function.\n */\nfunction wrapImmutable(func, cloner) {\n return function() {\n var length = arguments.length;\n if (!length) {\n return;\n }\n var args = Array(length);\n while (length--) {\n args[length] = arguments[length];\n }\n var result = args[0] = cloner.apply(undefined, args);\n func.apply(undefined, args);\n return result;\n };\n}\n\n/**\n * The base implementation of `convert` which accepts a `util` object of methods\n * required to perform conversions.\n *\n * @param {Object} util The util object.\n * @param {string} name The name of the function to convert.\n * @param {Function} func The function to convert.\n * @param {Object} [options] The options object.\n * @param {boolean} [options.cap=true] Specify capping iteratee arguments.\n * @param {boolean} [options.curry=true] Specify currying.\n * @param {boolean} [options.fixed=true] Specify fixed arity.\n * @param {boolean} [options.immutable=true] Specify immutable operations.\n * @param {boolean} [options.rearg=true] Specify rearranging arguments.\n * @returns {Function|Object} Returns the converted function or object.\n */\nfunction baseConvert(util, name, func, options) {\n var isLib = typeof name == 'function',\n isObj = name === Object
"var _ = require('./lodash.min').runInContext();\nmodule.exports = require('./fp/_baseConvert')(_, _);\n",
"'use strict';\n\n// Found this seed-based random generator somewhere\n// Based on The Central Randomizer 1.3 (C) 1997 by Paul Houle (houle@msc.cornell.edu)\n\nvar seed = 1;\n\n/**\n * return a random number based on a seed\n * @param seed\n * @returns {number}\n */\nfunction getNextValue() {\n seed = (seed * 9301 + 49297) % 233280;\n return seed/(233280.0);\n}\n\nfunction setSeed(_seed_) {\n seed = _seed_;\n}\n\nmodule.exports = {\n nextValue: getNextValue,\n seed: setSeed\n};\n",
"'use strict';\n\nvar randomFromSeed = require('./random/random-from-seed');\n\nvar ORIGINAL = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-';\nvar alphabet;\nvar previousSeed;\n\nvar shuffled;\n\nfunction reset() {\n shuffled = false;\n}\n\nfunction setCharacters(_alphabet_) {\n if (!_alphabet_) {\n if (alphabet !== ORIGINAL) {\n alphabet = ORIGINAL;\n reset();\n }\n return;\n }\n\n if (_alphabet_ === alphabet) {\n return;\n }\n\n if (_alphabet_.length !== ORIGINAL.length) {\n throw new Error('Custom alphabet for shortid must be ' + ORIGINAL.length + ' unique characters. You submitted ' + _alphabet_.length + ' characters: ' + _alphabet_);\n }\n\n var unique = _alphabet_.split('').filter(function(item, ind, arr){\n return ind !== arr.lastIndexOf(item);\n });\n\n if (unique.length) {\n throw new Error('Custom alphabet for shortid must be ' + ORIGINAL.length + ' unique characters. These characters were not unique: ' + unique.join(', '));\n }\n\n alphabet = _alphabet_;\n reset();\n}\n\nfunction characters(_alphabet_) {\n setCharacters(_alphabet_);\n return alphabet;\n}\n\nfunction setSeed(seed) {\n randomFromSeed.seed(seed);\n if (previousSeed !== seed) {\n reset();\n previousSeed = seed;\n }\n}\n\nfunction shuffle() {\n if (!alphabet) {\n setCharacters(ORIGINAL);\n }\n\n var sourceArray = alphabet.split('');\n var targetArray = [];\n var r = randomFromSeed.nextValue();\n var characterIndex;\n\n while (sourceArray.length > 0) {\n r = randomFromSeed.nextValue();\n characterIndex = Math.floor(r * sourceArray.length);\n targetArray.push(sourceArray.splice(characterIndex, 1)[0]);\n }\n return targetArray.join('');\n}\n\nfunction getShuffled() {\n if (shuffled) {\n return shuffled;\n }\n shuffled = shuffle();\n return shuffled;\n}\n\n/**\n * lookup shuffled letter\n * @param index\n * @returns {string}\n */\nfunction lookup(index) {\n var alphabetShuffled = getShuffled();\n return alphabetShuffled[index];\n}\n\nfunction get () {\n return alphabet || ORIGINAL;\n}\n\nmodule.exports = {\n get: get,\n characters: characters,\n seed: setSeed,\n lookup: lookup,\n shuffled: getShuffled\n};\n",
"'use strict';\n\nvar crypto = typeof window === 'object' && (window.crypto || window.msCrypto); // IE 11 uses window.msCrypto\n\nvar randomByte;\n\nif (!crypto || !crypto.getRandomValues) {\n randomByte = function(size) {\n var bytes = [];\n for (var i = 0; i < size; i++) {\n bytes.push(Math.floor(Math.random() * 256));\n }\n return bytes;\n };\n} else {\n randomByte = function(size) {\n return crypto.getRandomValues(new Uint8Array(size));\n };\n}\n\nmodule.exports = randomByte;\n",
"/**\n * Secure random string generator with custom alphabet.\n *\n * Alphabet must contain 256 symbols or less. Otherwise, the generator\n * will not be secure.\n *\n * @param {generator} random The random bytes generator.\n * @param {string} alphabet Symbols to be used in new random string.\n * @param {size} size The number of symbols in new random string.\n *\n * @return {string} Random string.\n *\n * @example\n * const format = require('nanoid/format')\n *\n * function random (size) {\n * const result = []\n * for (let i = 0; i < size; i++) {\n * result.push(randomByte())\n * }\n * return result\n * }\n *\n * format(random, \"abcdef\", 5) //=> \"fbaef\"\n *\n * @name format\n * @function\n */\nmodule.exports = function (random, alphabet, size) {\n var mask = (2 << Math.log(alphabet.length - 1) / Math.LN2) - 1\n var step = Math.ceil(1.6 * mask * size / alphabet.length)\n size = +size\n\n var id = ''\n while (true) {\n var bytes = random(step)\n for (var i = 0; i < step; i++) {\n var byte = bytes[i] & mask\n if (alphabet[byte]) {\n id += alphabet[byte]\n if (id.length === size) return id\n }\n }\n }\n}\n\n/**\n * @callback generator\n * @param {number} bytes The number of bytes to generate.\n * @return {number[]} Random bytes.\n */\n",
"'use strict';\n\nvar alphabet = require('./alphabet');\nvar random = require('./random/random-byte');\nvar format = require('nanoid/format');\n\nfunction generate(number) {\n var loopCounter = 0;\n var done;\n\n var str = '';\n\n while (!done) {\n str = str + format(random, alphabet.get(), 1);\n done = number < (Math.pow(16, loopCounter + 1 ) );\n loopCounter++;\n }\n return str;\n}\n\nmodule.exports = generate;\n",
"'use strict';\n\nvar generate = require('./generate');\nvar alphabet = require('./alphabet');\n\n// Ignore all milliseconds before a certain time to reduce the size of the date entropy without sacrificing uniqueness.\n// This number should be updated every year or so to keep the generated id short.\n// To regenerate `new Date() - 0` and bump the version. Always bump the version!\nvar REDUCE_TIME = 1567752802062;\n\n// don't change unless we change the algos or REDUCE_TIME\n// must be an integer and less than 16\nvar version = 7;\n\n// Counter is used when shortid is called multiple times in one second.\nvar counter;\n\n// Remember the last time shortid was called in case counter is needed.\nvar previousSeconds;\n\n/**\n * Generate unique id\n * Returns string id\n */\nfunction build(clusterWorkerId) {\n var str = '';\n\n var seconds = Math.floor((Date.now() - REDUCE_TIME) * 0.001);\n\n if (seconds === previousSeconds) {\n counter++;\n } else {\n counter = 0;\n previousSeconds = seconds;\n }\n\n str = str + generate(version);\n str = str + generate(clusterWorkerId);\n if (counter > 0) {\n str = str + generate(counter);\n }\n str = str + generate(seconds);\n return str;\n}\n\nmodule.exports = build;\n",
"'use strict';\nvar alphabet = require('./alphabet');\n\nfunction isShortId(id) {\n if (!id || typeof id !== 'string' || id.length < 6 ) {\n return false;\n }\n\n var nonAlphabetic = new RegExp('[^' +\n alphabet.get().replace(/[|\\\\{}()[\\]^$+*?.-]/g, '\\\\$&') +\n ']');\n return !nonAlphabetic.test(id);\n}\n\nmodule.exports = isShortId;\n",
"'use strict';\n\nvar alphabet = require('./alphabet');\nvar build = require('./build');\nvar isValid = require('./is-valid');\n\n// if you are using cluster or multiple servers use this to make each instance\n// has a unique value for worker\n// Note: I don't know if this is automatically set when using third\n// party cluster solutions such as pm2.\nvar clusterWorkerId = require('./util/cluster-worker-id') || 0;\n\n/**\n * Set the seed.\n * Highly recommended if you don't want people to try to figure out your id schema.\n * exposed as shortid.seed(int)\n * @param seed Integer value to seed the random alphabet. ALWAYS USE THE SAME SEED or you might get overlaps.\n */\nfunction seed(seedValue) {\n alphabet.seed(seedValue);\n return module.exports;\n}\n\n/**\n * Set the cluster worker or machine id\n * exposed as shortid.worker(int)\n * @param workerId worker must be positive integer. Number less than 16 is recommended.\n * returns shortid module so it can be chained.\n */\nfunction worker(workerId) {\n clusterWorkerId = workerId;\n return module.exports;\n}\n\n/**\n *\n * sets new characters to use in the alphabet\n * returns the shuffled alphabet\n */\nfunction characters(newCharacters) {\n if (newCharacters !== undefined) {\n alphabet.characters(newCharacters);\n }\n\n return alphabet.shuffled();\n}\n\n/**\n * Generate unique id\n * Returns string id\n */\nfunction generate() {\n return build(clusterWorkerId);\n}\n\n// Export all other functions as properties of the generate function\nmodule.exports = generate;\nmodule.exports.generate = generate;\nmodule.exports.seed = seed;\nmodule.exports.worker = worker;\nmodule.exports.characters = characters;\nmodule.exports.isValid = isValid;\n",
"'use strict';\nmodule.exports = require('./lib/index');\n",
"/**\n * @license\n * Lodash <https://lodash.com/>\n * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n;(function() {\n\n /** Used as a safe reference for `undefined` in pre-ES5 environments. */\n var undefined;\n\n /** Used as the semantic version number. */\n var VERSION = '4.17.15';\n\n /** Used as the size to enable large array optimizations. */\n var LARGE_ARRAY_SIZE = 200;\n\n /** Error message constants. */\n var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',\n FUNC_ERROR_TEXT = 'Expected a function';\n\n /** Used to stand-in for `undefined` hash values. */\n var HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n /** Used as the maximum memoize cache size. */\n var MAX_MEMOIZE_SIZE = 500;\n\n /** Used as the internal argument placeholder. */\n var PLACEHOLDER = '__lodash_placeholder__';\n\n /** Used to compose bitmasks for cloning. */\n var CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n /** Used to compose bitmasks for value comparisons. */\n var COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n /** Used to compose bitmasks for function metadata. */\n var WRAP_BIND_FLAG = 1,\n WRAP_BIND_KEY_FLAG = 2,\n WRAP_CURRY_BOUND_FLAG = 4,\n WRAP_CURRY_FLAG = 8,\n WRAP_CURRY_RIGHT_FLAG = 16,\n WRAP_PARTIAL_FLAG = 32,\n WRAP_PARTIAL_RIGHT_FLAG = 64,\n WRAP_ARY_FLAG = 128,\n WRAP_REARG_FLAG = 256,\n WRAP_FLIP_FLAG = 512;\n\n /** Used as default options for `_.truncate`. */\n var DEFAULT_TRUNC_LENGTH = 30,\n DEFAULT_TRUNC_OMISSION = '...';\n\n /** Used to detect hot functions by number of calls within a span of milliseconds. */\n var HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n /** Used to indicate the type of lazy iteratees. */\n var LAZY_FILTER_FLAG = 1,\n LAZY_MAP_FLAG = 2,\n LAZY_WHILE_FLAG = 3;\n\n /** Used as references for various `Number` constants. */\n var INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n /** Used as references for the maximum length and index of an array. */\n var MAX_ARRAY_LENGTH = 4294967295,\n MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,\n HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;\n\n /** Used to associate wrap methods with their bit flags. */\n var wrapFlags = [\n ['ary', WRAP_ARY_FLAG],\n ['bind', WRAP_BIND_FLAG],\n ['bindKey', WRAP_BIND_KEY_FLAG],\n ['curry', WRAP_CURRY_FLAG],\n ['curryRight', WRAP_CURRY_RIGHT_FLAG],\n ['flip', WRAP_FLIP_FLAG],\n ['partial', WRAP_PARTIAL_FLAG],\n ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],\n ['rearg', WRAP_REARG_FLAG]\n ];\n\n /** `Object#toString` result references. */\n var argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n domExcTag = '[object DOMException]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]',\n weakSetTag = '[object WeakSet]';\n\n var arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n
"import { union, reduce } from \"lodash/fp\"\r\n\r\nconst commonPlus = extra => union([\"onBegin\", \"onComplete\", \"onError\"])(extra)\r\n\r\nconst common = () => commonPlus([])\r\n\r\nconst _events = {\r\n recordApi: {\r\n save: commonPlus([\"onInvalid\", \"onRecordUpdated\", \"onRecordCreated\"]),\r\n delete: common(),\r\n getContext: common(),\r\n getNew: common(),\r\n load: common(),\r\n validate: common(),\r\n uploadFile: common(),\r\n downloadFile: common(),\r\n },\r\n indexApi: {\r\n buildIndex: common(),\r\n listItems: common(),\r\n delete: common(),\r\n aggregates: common(),\r\n },\r\n collectionApi: {\r\n getAllowedRecordTypes: common(),\r\n initialise: common(),\r\n delete: common(),\r\n },\r\n authApi: {\r\n authenticate: common(),\r\n authenticateTemporaryAccess: common(),\r\n createTemporaryAccess: common(),\r\n createUser: common(),\r\n enableUser: common(),\r\n disableUser: common(),\r\n loadAccessLevels: common(),\r\n getNewAccessLevel: common(),\r\n getNewUser: common(),\r\n getNewUserAuth: common(),\r\n getUsers: common(),\r\n saveAccessLevels: common(),\r\n isAuthorized: common(),\r\n changeMyPassword: common(),\r\n setPasswordFromTemporaryCode: common(),\r\n scorePassword: common(),\r\n isValidPassword: common(),\r\n validateUser: common(),\r\n validateAccessLevels: common(),\r\n setUserAccessLevels: common(),\r\n },\r\n templateApi: {\r\n saveApplicationHierarchy: common(),\r\n saveActionsAndTriggers: common(),\r\n },\r\n actionsApi: {\r\n execute: common(),\r\n },\r\n}\r\n\r\nconst _eventsList = []\r\n\r\nconst makeEvent = (area, method, name) => `${area}:${method}:${name}`\r\n\r\nfor (const areaKey in _events) {\r\n for (const methodKey in _events[areaKey]) {\r\n _events[areaKey][methodKey] = reduce((obj, s) => {\r\n obj[s] = makeEvent(areaKey, methodKey, s)\r\n return obj\r\n }, {})(_events[areaKey][methodKey])\r\n }\r\n}\r\n\r\nfor (const areaKey in _events) {\r\n for (const methodKey in _events[areaKey]) {\r\n for (const name in _events[areaKey][methodKey]) {\r\n _eventsList.push(_events[areaKey][methodKey][name])\r\n }\r\n }\r\n}\r\n\r\nexport const events = _events\r\n\r\nexport const eventsList = _eventsList\r\n\r\nexport default { events: _events, eventsList: _eventsList }\r\n",
"export class BadRequestError extends Error {\r\n constructor(message) {\r\n super(message)\r\n this.httpStatusCode = 400\r\n }\r\n}\r\n\r\nexport class UnauthorisedError extends Error {\r\n constructor(message) {\r\n super(message)\r\n this.httpStatusCode = 401\r\n }\r\n}\r\n\r\nexport class ForbiddenError extends Error {\r\n constructor(message) {\r\n super(message)\r\n this.httpStatusCode = 403\r\n }\r\n}\r\n\r\nexport class NotFoundError extends Error {\r\n constructor(message) {\r\n super(message)\r\n this.httpStatusCode = 404\r\n }\r\n}\r\n\r\nexport class ConflictError extends Error {\r\n constructor(message) {\r\n super(message)\r\n this.httpStatusCode = 409\r\n }\r\n}\r\n",
"import { cloneDeep, isUndefined } from \"lodash/fp\"\r\nimport { generate } from \"shortid\"\r\nimport { UnauthorisedError } from \"./errors\"\r\n\r\nexport const apiWrapper = async (\r\n app,\r\n eventNamespace,\r\n isAuthorized,\r\n eventContext,\r\n func,\r\n ...params\r\n) => {\r\n pushCallStack(app, eventNamespace)\r\n\r\n if (!isAuthorized(app)) {\r\n handleNotAuthorized(app, eventContext, eventNamespace)\r\n return\r\n }\r\n\r\n const startDate = Date.now()\r\n const elapsed = () => Date.now() - startDate\r\n\r\n try {\r\n await app.publish(eventNamespace.onBegin, eventContext)\r\n\r\n const result = await func(...params)\r\n\r\n await publishComplete(app, eventContext, eventNamespace, elapsed, result)\r\n return result\r\n } catch (error) {\r\n await publishError(app, eventContext, eventNamespace, elapsed, error)\r\n throw error\r\n }\r\n}\r\n\r\nexport const apiWrapperSync = (\r\n app,\r\n eventNamespace,\r\n isAuthorized,\r\n eventContext,\r\n func,\r\n ...params\r\n) => {\r\n pushCallStack(app, eventNamespace)\r\n\r\n if (!isAuthorized(app)) {\r\n handleNotAuthorized(app, eventContext, eventNamespace)\r\n return\r\n }\r\n\r\n const startDate = Date.now()\r\n const elapsed = () => Date.now() - startDate\r\n\r\n try {\r\n app.publish(eventNamespace.onBegin, eventContext)\r\n\r\n const result = func(...params)\r\n\r\n publishComplete(app, eventContext, eventNamespace, elapsed, result)\r\n return result\r\n } catch (error) {\r\n publishError(app, eventContext, eventNamespace, elapsed, error)\r\n throw error\r\n }\r\n}\r\n\r\nconst handleNotAuthorized = (app, eventContext, eventNamespace) => {\r\n const err = new UnauthorisedError(`Unauthorized: ${eventNamespace}`)\r\n publishError(app, eventContext, eventNamespace, () => 0, err)\r\n throw err\r\n}\r\n\r\nconst pushCallStack = (app, eventNamespace, seedCallId) => {\r\n const callId = generate()\r\n\r\n const createCallStack = () => ({\r\n seedCallId: !isUndefined(seedCallId) ? seedCallId : callId,\r\n threadCallId: callId,\r\n stack: [],\r\n })\r\n\r\n if (isUndefined(app.calls)) {\r\n app.calls = createCallStack()\r\n }\r\n\r\n app.calls.stack.push({\r\n namespace: eventNamespace,\r\n callId,\r\n })\r\n}\r\n\r\nconst popCallStack = app => {\r\n app.calls.stack.pop()\r\n if (app.calls.stack.length === 0) {\r\n delete app.calls\r\n }\r\n}\r\n\r\nconst publishError = async (\r\n app,\r\n eventContext,\r\n eventNamespace,\r\n elapsed,\r\n err\r\n) => {\r\n const ctx = cloneDeep(eventContext)\r\n ctx.error = err\r\n ctx.elapsed = elapsed()\r\n await app.publish(eventNamespace.onError, ctx)\r\n popCallStack(app)\r\n}\r\n\r\nconst publishComplete = async (\r\n app,\r\n eventContext,\r\n eventNamespace,\r\n elapsed,\r\n result\r\n) => {\r\n const endcontext = cloneDeep(eventContext)\r\n endcontext.result = result\r\n endcontext.elapsed = elapsed()\r\n await app.publish(eventNamespace.onComplete, endcontext)\r\n popCallStack(app)\r\n return result\r\n}\r\n\r\nexport default apiWrapper\r\n",
"/*\r\n Copyright (c) 2012 Nevins Bartolomeo <nevins.bartolomeo@gmail.com>\r\n Copyright (c) 2012 Shane Girish <shaneGirish@gmail.com>\r\n Copyright (c) 2014 Daniel Wirtz <dcode@dcode.io>\r\n\r\n Redistribution and use in source and binary forms, with or without\r\n modification, are permitted provided that the following conditions\r\n are met:\r\n 1. Redistributions of source code must retain the above copyright\r\n notice, this list of conditions and the following disclaimer.\r\n 2. Redistributions in binary form must reproduce the above copyright\r\n notice, this list of conditions and the following disclaimer in the\r\n documentation and/or other materials provided with the distribution.\r\n 3. The name of the author may not be used to endorse or promote products\r\n derived from this software without specific prior written permission.\r\n\r\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\r\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\r\n OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\r\n IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\r\n INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\r\n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\r\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n/**\r\n * @license bcrypt.js (c) 2013 Daniel Wirtz <dcode@dcode.io>\r\n * Released under the Apache License, Version 2.0\r\n * see: https://github.com/dcodeIO/bcrypt.js for details\r\n */\r\n(function(global, factory) {\r\n\r\n /* AMD */ if (typeof define === 'function' && define[\"amd\"])\r\n define([], factory);\r\n /* CommonJS */ else if (typeof require === 'function' && typeof module === \"object\" && module && module[\"exports\"])\r\n module[\"exports\"] = factory();\r\n /* Global */ else\r\n (global[\"dcodeIO\"] = global[\"dcodeIO\"] || {})[\"bcrypt\"] = factory();\r\n\r\n}(this, function() {\r\n \"use strict\";\r\n\r\n /**\r\n * bcrypt namespace.\r\n * @type {Object.<string,*>}\r\n */\r\n var bcrypt = {};\r\n\r\n /**\r\n * The random implementation to use as a fallback.\r\n * @type {?function(number):!Array.<number>}\r\n * @inner\r\n */\r\n var randomFallback = null;\r\n\r\n /**\r\n * Generates cryptographically secure random bytes.\r\n * @function\r\n * @param {number} len Bytes length\r\n * @returns {!Array.<number>} Random bytes\r\n * @throws {Error} If no random implementation is available\r\n * @inner\r\n */\r\n function random(len) {\r\n /* node */ if (typeof module !== 'undefined' && module && module['exports'])\r\n try {\r\n return require(\"crypto\")['randomBytes'](len);\r\n } catch (e) {}\r\n /* WCA */ try {\r\n var a; (self['crypto']||self['msCrypto'])['getRandomValues'](a = new Uint32Array(len));\r\n return Array.prototype.slice.call(a);\r\n } catch (e) {}\r\n /* fallback */ if (!randomFallback)\r\n throw Error(\"Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative\");\r\n return randomFallback(len);\r\n }\r\n\r\n // Test if any secure randomness source is available\r\n var randomAvailable = false;\r\n try {\r\n random(1);\r\n randomAvailable = true;\r\n } catch (e) {}\r\n\r\n // Default fallback, if any\r\n randomFallback = null;\r\n /**\r\n * Sets the pseudo random number generator to use as a fallback if neither node's `crypto` module nor the Web Crypto\r\n * API is available. Please note: It is highly important that the PRNG used is cryptographically secure and that it\r\n * is seeded properly!\r\n
"import {\r\n head,\r\n tail,\r\n findIndex,\r\n startsWith,\r\n dropRight,\r\n flow,\r\n takeRight,\r\n trim,\r\n replace,\r\n} from \"lodash\"\r\nimport {\r\n some,\r\n reduce,\r\n isEmpty,\r\n isArray,\r\n join,\r\n isString,\r\n isInteger,\r\n isDate,\r\n toNumber,\r\n isUndefined,\r\n isNaN,\r\n isNull,\r\n constant,\r\n split,\r\n includes,\r\n filter,\r\n} from \"lodash/fp\"\r\nimport { events, eventsList } from \"./events\"\r\nimport { apiWrapper } from \"./apiWrapper\"\r\nimport { getLock, NO_LOCK, isNolock } from \"./lock\"\r\nimport crypto from \"./nodeCrypto\"\r\n\r\n// this is the combinator function\r\nexport const $$ = (...funcs) => arg => flow(funcs)(arg)\r\n\r\n// this is the pipe function\r\nexport const $ = (arg, funcs) => $$(...funcs)(arg)\r\n\r\nexport const keySep = \"/\"\r\nconst trimKeySep = str => trim(str, keySep)\r\nconst splitByKeySep = str => split(keySep)(str)\r\nexport const safeKey = key =>\r\n replace(`${keySep}${trimKeySep(key)}`, `${keySep}${keySep}`, keySep)\r\nexport const joinKey = (...strs) => {\r\n const paramsOrArray = (strs.length === 1) & isArray(strs[0]) ? strs[0] : strs\r\n return $(paramsOrArray, [\r\n filter(s => !isUndefined(s) && !isNull(s) && s.toString().length > 0),\r\n join(keySep),\r\n safeKey,\r\n ])\r\n}\r\nexport const splitKey = $$(trimKeySep, splitByKeySep)\r\nexport const getDirFomKey = $$(splitKey, dropRight, p => joinKey(...p))\r\nexport const getFileFromKey = $$(splitKey, takeRight, head)\r\n\r\nexport const configFolder = `${keySep}.config`\r\nexport const fieldDefinitions = joinKey(configFolder, \"fields.json\")\r\nexport const templateDefinitions = joinKey(configFolder, \"templates.json\")\r\nexport const appDefinitionFile = joinKey(configFolder, \"appDefinition.json\")\r\nexport const dirIndex = folderPath =>\r\n joinKey(configFolder, \"dir\", ...splitKey(folderPath), \"dir.idx\")\r\nexport const getIndexKeyFromFileKey = $$(getDirFomKey, dirIndex)\r\n\r\nexport const ifExists = (val, exists, notExists) =>\r\n isUndefined(val)\r\n ? isUndefined(notExists)\r\n ? (() => {})()\r\n : notExists()\r\n : exists()\r\n\r\nexport const getOrDefault = (val, defaultVal) =>\r\n ifExists(\r\n val,\r\n () => val,\r\n () => defaultVal\r\n )\r\n\r\nexport const not = func => val => !func(val)\r\nexport const isDefined = not(isUndefined)\r\nexport const isNonNull = not(isNull)\r\nexport const isNotNaN = not(isNaN)\r\n\r\nexport const allTrue = (...funcArgs) => val =>\r\n reduce(\r\n (result, conditionFunc) =>\r\n (isNull(result) || result == true) && conditionFunc(val),\r\n null\r\n )(funcArgs)\r\n\r\nexport const anyTrue = (...funcArgs) => val =>\r\n reduce(\r\n (result, conditionFunc) => result == true || conditionFunc(val),\r\n null\r\n )(funcArgs)\r\n\r\nexport const insensitiveEquals = (str1, str2) =>\r\n str1.trim().toLowerCase() === str2.trim().toLowerCase()\r\n\r\nexport const isSomething = allTrue(isDefined, isNonNull, isNotNaN)\r\nexport const isNothing = not(isSomething)\r\nexport const isNothingOrEmpty = v => isNothing(v) || isEmpty(v)\r\nexport const somethingOrGetDefault = getDefaultFunc => val =>\r\n isSomething(val) ? val : getDefaultFunc()\r\nexport const somethingOrDefault = (val, defaultVal) =>\r\n somethingOrGetDefault(constant(defaultVal))(val)\r\n\r\nexport const mapIfSomethingOrDefault = (mapFunc, defaultVal) => val =>\r\n isSomething(val) ? mapFunc(val) : defaultVal\r\n\r\nexport const mapIfSomethingOrBlank = mapFunc =>\r\n mapIfSomethingOrDefault(mapFunc, \"\")\r\n\r\nexport const none = predicate => collection => !some(predicate)(collection)\r\n\r\nexport const all = predicate => collection =>\r\n none(v => !predicate(v))(collection)\r\n\r\nexport const isNotEmpty = ob => !isEmpty(ob)\r\nexport const isAsync = fn => fn.constructor.name === \"AsyncFunction\"\r\nexport const isNonEmptyArray = allTrue(isArray, isNotEmpty)\r\nexport const isNonEmptyString = allTrue(isString, isNotEmpty)\r\nexport const tryOr = failFunc => (func, ...args) => {\r\n try {\r
"import { filter, map } from \"lodash/fp\"\r\nimport { $, isSomething } from \"./index\"\r\n\r\nexport const stringNotEmpty = s => isSomething(s) && s.trim().length > 0\r\n\r\nexport const makerule = (field, error, isValid) => ({ field, error, isValid })\r\n\r\nexport const validationError = (rule, item) => ({ ...rule, item })\r\n\r\nexport const applyRuleSet = ruleSet => itemToValidate =>\r\n $(ruleSet, [map(applyRule(itemToValidate)), filter(isSomething)])\r\n\r\nexport const applyRule = itemTovalidate => rule =>\r\n rule.isValid(itemTovalidate) ? null : validationError(rule, itemTovalidate)\r\n",
"var filters = new Map();\nvar limiters = new Map();\n\nfunction filter(name, handler) {\n if (typeof name !== 'string') {\n throw new TypeError('First argument must be a string.');\n }\n if (typeof handler !== 'function') {\n throw new TypeError('Second argument must be a function.');\n }\n if (filters.has(name)) {\n throw new Error((\"A filter named \" + name + \" is already registered.\"));\n }\n filters.set(name, handler);\n}\n\nfunction limiter(name, handler) {\n if (typeof name !== 'string') {\n throw new TypeError('First argument must be a string.');\n }\n if (typeof handler !== 'function') {\n throw new TypeError('Second argument must be a function.');\n }\n if (limiters.has(name)) {\n throw new Error((\"A limiter named \" + name + \" is already registered.\"));\n }\n limiters.set(name, handler);\n}\n\nfunction compileRawExpression(src) {\n return new Function('context', 'tempVars', // eslint-disable-line\n (\"const sandbox = $nxCompileToSandbox(context, tempVars)\\n try { with (sandbox) { return \" + src + \" } } catch (err) {\\n if (!(err instanceof TypeError)) throw err\\n }\\n $nxClearSandbox()\"));\n}\n\nfunction compileRawCode(src) {\n return new Function('context', 'tempVars', // eslint-disable-line\n (\"const sandbox = $nxCompileToSandbox(context, tempVars)\\n with (sandbox) { \" + src + \" }\\n $nxClearSandbox()\"));\n}\n\nvar filterRegex = /(?:[^\\|]|\\|\\|)+/g;\nvar limiterRegex = /(?:[^&]|&&)+/g;\nvar argsRegex = /\\S+/g;\n\nfunction parseExpression(src) {\n var tokens = src.match(filterRegex);\n if (tokens.length === 1) {\n return compileRawExpression(tokens[0]);\n }\n\n var expression = {\n exec: compileRawExpression(tokens[0]),\n filters: []\n };\n for (var i = 1; i < tokens.length; i++) {\n var filterTokens = tokens[i].match(argsRegex);\n var filterName = filterTokens.shift();\n var effect = filters.get(filterName);\n if (!effect) {\n throw new Error((\"There is no filter named: \" + filterName + \".\"));\n }\n expression.filters.push({ effect: effect, argExpressions: filterTokens.map(compileRawExpression) });\n }\n return expression;\n}\n\nfunction parseCode(src) {\n var tokens = src.match(limiterRegex);\n if (tokens.length === 1) {\n return compileRawCode(tokens[0]);\n }\n\n var code = {\n exec: compileRawCode(tokens[0]),\n limiters: []\n };\n for (var i = 1; i < tokens.length; i++) {\n var limiterTokens = tokens[i].match(argsRegex);\n var limiterName = limiterTokens.shift();\n var effect = limiters.get(limiterName);\n if (!effect) {\n throw new Error((\"There is no limiter named: \" + limiterName + \".\"));\n }\n code.limiters.push({ effect: effect, argExpressions: limiterTokens.map(compileRawExpression) });\n }\n return code;\n}\n\nvar expressionCache = new Map();\nvar codeCache = new Map();\n\nfunction compileExpression(src) {\n if (typeof src !== 'string') {\n throw new TypeError('First argument must be a string.');\n }\n var expression = expressionCache.get(src);\n if (!expression) {\n expression = parseExpression(src);\n expressionCache.set(src, expression);\n }\n\n if (typeof expression === 'function') {\n return expression;\n }\n\n return function evaluateExpression(context, tempVars) {\n var value = expression.exec(context, tempVars);\n for (var i = 0, list = expression.filters; i < list.length; i += 1) {\n var filter = list[i];\n\n var args = filter.argExpressions.map(evaluateArgExpression, context);\n value = filter.effect.apply(filter, [ value ].concat( args ));\n }\n return value;\n };\n}\n\nfunction compileCode(src) {\n if (typeof src !== 'string') {\n throw new TypeError('First argument must be a string.');\n }\n var code = codeCache.get(src);\n if (!code) {\n code = parseCode(src);\n codeCache.set(src, code);\n }\n\n if (typeof code === 'function') {\n return code;\n }\n\n var context = {};\n return function evaluateCode(state, tempVars) {\n var i = 0;\n function next
"import { compileExpression, compileCode } from \"@nx-js/compiler-util\"\r\nimport { isUndefined, keys, cloneDeep, isFunction } from \"lodash/fp\"\r\nimport { defineError } from \"../common\"\r\n\r\nexport const filterEval = \"FILTER_EVALUATE\"\r\nexport const filterCompile = \"FILTER_COMPILE\"\r\nexport const mapEval = \"MAP_EVALUATE\"\r\nexport const mapCompile = \"MAP_COMPILE\"\r\nexport const removeUndeclaredFields = \"REMOVE_UNDECLARED_FIELDS\"\r\nexport const addUnMappedFields = \"ADD_UNMAPPED_FIELDS\"\r\nexport const addTheKey = \"ADD_KEY\"\r\n\r\nconst getEvaluateResult = () => ({\r\n isError: false,\r\n passedFilter: true,\r\n result: null,\r\n})\r\n\r\nexport const compileFilter = index => compileExpression(index.filter)\r\n\r\nexport const compileMap = index => compileCode(index.map)\r\n\r\nexport const passesFilter = (record, index) => {\r\n const context = { record }\r\n if (!index.filter) return true\r\n\r\n const compiledFilter = defineError(() => compileFilter(index), filterCompile)\r\n\r\n return defineError(() => compiledFilter(context), filterEval)\r\n}\r\n\r\nexport const mapRecord = (record, index) => {\r\n const recordClone = cloneDeep(record)\r\n const context = { record: recordClone }\r\n\r\n const map = index.map ? index.map : \"return {...record};\"\r\n\r\n const compiledMap = defineError(() => compileCode(map), mapCompile)\r\n\r\n const mapped = defineError(() => compiledMap(context), mapEval)\r\n\r\n const mappedKeys = keys(mapped)\r\n for (let i = 0; i < mappedKeys.length; i++) {\r\n const key = mappedKeys[i]\r\n mapped[key] = isUndefined(mapped[key]) ? null : mapped[key]\r\n if (isFunction(mapped[key])) {\r\n delete mapped[key]\r\n }\r\n }\r\n\r\n mapped.key = record.key\r\n mapped.sortKey = index.getSortKey\r\n ? compileCode(index.getSortKey)(context)\r\n : record.id\r\n\r\n return mapped\r\n}\r\n\r\nexport const evaluate = record => index => {\r\n const result = getEvaluateResult()\r\n\r\n try {\r\n result.passedFilter = passesFilter(record, index)\r\n } catch (err) {\r\n result.isError = true\r\n result.passedFilter = false\r\n result.result = err.message\r\n }\r\n\r\n if (!result.passedFilter) return result\r\n\r\n try {\r\n result.result = mapRecord(record, index)\r\n } catch (err) {\r\n result.isError = true\r\n result.result = err.message\r\n }\r\n\r\n return result\r\n}\r\n\r\nexport default evaluate\r\n",
"import { map, isEmpty, countBy, flatten, includes, join, keys } from \"lodash/fp\"\r\nimport {} from \"lodash\"\r\nimport { applyRuleSet, makerule } from \"../common/validationCommon\"\r\nimport { compileFilter, compileMap } from \"../indexing/evaluate\"\r\nimport { isNonEmptyString, executesWithoutException, $ } from \"../common\"\r\nimport { isRecord } from \"./hierarchy\"\r\n\r\nexport const indexTypes = { reference: \"reference\", ancestor: \"ancestor\" }\r\n\r\nexport const indexRuleSet = [\r\n makerule(\"map\", \"index has no map function\", index =>\r\n isNonEmptyString(index.map)\r\n ),\r\n makerule(\r\n \"map\",\r\n \"index's map function does not compile\",\r\n index =>\r\n !isNonEmptyString(index.map) ||\r\n executesWithoutException(() => compileMap(index))\r\n ),\r\n makerule(\r\n \"filter\",\r\n \"index's filter function does not compile\",\r\n index =>\r\n !isNonEmptyString(index.filter) ||\r\n executesWithoutException(() => compileFilter(index))\r\n ),\r\n makerule(\"name\", \"must declare a name for index\", index =>\r\n isNonEmptyString(index.name)\r\n ),\r\n makerule(\r\n \"name\",\r\n \"there is a duplicate named index on this node\",\r\n index =>\r\n isEmpty(index.name) ||\r\n countBy(\"name\")(index.parent().indexes)[index.name] === 1\r\n ),\r\n makerule(\r\n \"indexType\",\r\n \"reference index may only exist on a record node\",\r\n index =>\r\n isRecord(index.parent()) || index.indexType !== indexTypes.reference\r\n ),\r\n makerule(\r\n \"indexType\",\r\n `index type must be one of: ${join(\", \")(keys(indexTypes))}`,\r\n index => includes(index.indexType)(keys(indexTypes))\r\n ),\r\n]\r\n\r\nexport const validateIndex = (index, allReferenceIndexesOnNode) =>\r\n applyRuleSet(indexRuleSet(allReferenceIndexesOnNode))(index)\r\n\r\nexport const validateAllIndexes = node =>\r\n $(node.indexes, [map(i => validateIndex(i, node.indexes)), flatten])\r\n",
"import {\r\n find,\r\n constant,\r\n map,\r\n last,\r\n first,\r\n split,\r\n intersection,\r\n take,\r\n union,\r\n includes,\r\n filter,\r\n some,\r\n} from \"lodash/fp\"\r\nimport {\r\n $,\r\n switchCase,\r\n isNothing,\r\n isSomething,\r\n defaultCase,\r\n splitKey,\r\n isNonEmptyString,\r\n joinKey,\r\n getHashCode,\r\n} from \"../common\"\r\nimport { indexTypes } from \"./indexes\"\r\n\r\nexport const getFlattenedHierarchy = (appHierarchy, useCached = true) => {\r\n if (isSomething(appHierarchy.getFlattenedHierarchy) && useCached) {\r\n return appHierarchy.getFlattenedHierarchy()\r\n }\r\n\r\n const flattenHierarchy = (currentNode, flattened) => {\r\n flattened.push(currentNode)\r\n if (\r\n (!currentNode.children || currentNode.children.length === 0) &&\r\n (!currentNode.indexes || currentNode.indexes.length === 0) &&\r\n (!currentNode.aggregateGroups || currentNode.aggregateGroups.length === 0)\r\n ) {\r\n return flattened\r\n }\r\n\r\n const unionIfAny = l2 => l1 => union(l1)(!l2 ? [] : l2)\r\n\r\n const children = $(\r\n [],\r\n [\r\n unionIfAny(currentNode.children),\r\n unionIfAny(currentNode.indexes),\r\n unionIfAny(currentNode.aggregateGroups),\r\n ]\r\n )\r\n\r\n for (const child of children) {\r\n flattenHierarchy(child, flattened)\r\n }\r\n return flattened\r\n }\r\n\r\n appHierarchy.getFlattenedHierarchy = () => flattenHierarchy(appHierarchy, [])\r\n return appHierarchy.getFlattenedHierarchy()\r\n}\r\n\r\nexport const getLastPartInKey = key => last(splitKey(key))\r\n\r\nexport const getNodesInPath = appHierarchy => key =>\r\n $(appHierarchy, [\r\n getFlattenedHierarchy,\r\n filter(n => new RegExp(`${n.pathRegx()}`).test(key)),\r\n ])\r\n\r\nexport const getExactNodeForKey = appHierarchy => key =>\r\n $(appHierarchy, [\r\n getFlattenedHierarchy,\r\n find(n => new RegExp(`${n.pathRegx()}$`).test(key)),\r\n ])\r\n\r\nexport const getNodeForCollectionPath = appHierarchy => collectionKey =>\r\n $(appHierarchy, [\r\n getFlattenedHierarchy,\r\n find(\r\n n =>\r\n isCollectionRecord(n) &&\r\n new RegExp(`${n.collectionPathRegx()}$`).test(collectionKey)\r\n ),\r\n ])\r\n\r\nexport const hasMatchingAncestor = ancestorPredicate => decendantNode =>\r\n switchCase(\r\n [node => isNothing(node.parent()), constant(false)],\r\n\r\n [node => ancestorPredicate(node.parent()), constant(true)],\r\n\r\n [defaultCase, node => hasMatchingAncestor(ancestorPredicate)(node.parent())]\r\n )(decendantNode)\r\n\r\nexport const getNode = (appHierarchy, nodeKey) =>\r\n $(appHierarchy, [\r\n getFlattenedHierarchy,\r\n find(\r\n n =>\r\n n.nodeKey() === nodeKey ||\r\n (isCollectionRecord(n) && n.collectionNodeKey() === nodeKey)\r\n ),\r\n ])\r\n\r\nexport const getCollectionNode = (appHierarchy, nodeKey) =>\r\n $(appHierarchy, [\r\n getFlattenedHierarchy,\r\n find(n => isCollectionRecord(n) && n.collectionNodeKey() === nodeKey),\r\n ])\r\n\r\nexport const getNodeByKeyOrNodeKey = (appHierarchy, keyOrNodeKey) => {\r\n const nodeByKey = getExactNodeForKey(appHierarchy)(keyOrNodeKey)\r\n return isNothing(nodeByKey) ? getNode(appHierarchy, keyOrNodeKey) : nodeByKey\r\n}\r\n\r\nexport const getCollectionNodeByKeyOrNodeKey = (appHierarchy, keyOrNodeKey) => {\r\n const nodeByKey = getNodeForCollectionPath(appHierarchy)(keyOrNodeKey)\r\n return isNothing(nodeByKey)\r\n ? getCollectionNode(appHierarchy, keyOrNodeKey)\r\n : nodeByKey\r\n}\r\n\r\nexport const isNode = (appHierarchy, key) =>\r\n isSomething(getExactNodeForKey(appHierarchy)(key))\r\n\r\nexport const getActualKeyOfParent = (parentNodeKey, actualChildKey) =>\r\n $(actualChildKey, [\r\n splitKey,\r\n take(splitKey(parentNodeKey).length),\r\n ks => joinKey(...ks),\r\n ])\r\n\r\nexport const getParentKey = key => {\r\n return $(key, [splitKey, take(splitKey(key).length - 1), joinKey])\r\n}\r\n\r\nexport const isKeyAncestorOf = ancestorKey => decen
"import { merge } from \"lodash\"\r\nimport { constant, isUndefined, has, mapValues, cloneDeep } from \"lodash/fp\"\r\nimport { isNotEmpty } from \"../common\"\r\n\r\nexport const getSafeFieldParser = (tryParse, defaultValueFunctions) => (\r\n field,\r\n record\r\n) => {\r\n if (has(field.name)(record)) {\r\n return getSafeValueParser(\r\n tryParse,\r\n defaultValueFunctions\r\n )(record[field.name])\r\n }\r\n return defaultValueFunctions[field.getUndefinedValue]()\r\n}\r\n\r\nexport const getSafeValueParser = (\r\n tryParse,\r\n defaultValueFunctions\r\n) => value => {\r\n const parsed = tryParse(value)\r\n if (parsed.success) {\r\n return parsed.value\r\n }\r\n return defaultValueFunctions.default()\r\n}\r\n\r\nexport const getNewValue = (tryParse, defaultValueFunctions) => field => {\r\n const getInitialValue =\r\n isUndefined(field) || isUndefined(field.getInitialValue)\r\n ? \"default\"\r\n : field.getInitialValue\r\n\r\n return has(getInitialValue)(defaultValueFunctions)\r\n ? defaultValueFunctions[getInitialValue]()\r\n : getSafeValueParser(tryParse, defaultValueFunctions)(getInitialValue)\r\n}\r\n\r\nexport const typeFunctions = specificFunctions =>\r\n merge(\r\n {\r\n value: constant,\r\n null: constant(null),\r\n },\r\n specificFunctions\r\n )\r\n\r\nexport const validateTypeConstraints = validationRules => async (\r\n field,\r\n record,\r\n context\r\n) => {\r\n const fieldValue = record[field.name]\r\n const validateRule = async r =>\r\n !(await r.isValid(fieldValue, field.typeOptions, context))\r\n ? r.getMessage(fieldValue, field.typeOptions)\r\n : \"\"\r\n\r\n const errors = []\r\n for (const r of validationRules) {\r\n const err = await validateRule(r)\r\n if (isNotEmpty(err)) errors.push(err)\r\n }\r\n\r\n return errors\r\n}\r\n\r\nconst getDefaultOptions = mapValues(v => v.defaultValue)\r\n\r\nexport const makerule = (isValid, getMessage) => ({ isValid, getMessage })\r\nexport const parsedFailed = val => ({ success: false, value: val })\r\nexport const parsedSuccess = val => ({ success: true, value: val })\r\nexport const getDefaultExport = (\r\n name,\r\n tryParse,\r\n functions,\r\n options,\r\n validationRules,\r\n sampleValue,\r\n stringify\r\n) => ({\r\n getNew: getNewValue(tryParse, functions),\r\n safeParseField: getSafeFieldParser(tryParse, functions),\r\n safeParseValue: getSafeValueParser(tryParse, functions),\r\n tryParse,\r\n name,\r\n getDefaultOptions: () => getDefaultOptions(cloneDeep(options)),\r\n optionDefinitions: options,\r\n validateTypeConstraints: validateTypeConstraints(validationRules),\r\n sampleValue,\r\n stringify: val => (val === null || val === undefined ? \"\" : stringify(val)),\r\n getDefaultValue: functions.default,\r\n})\r\n",
"import { constant, isString, isNull, includes, isBoolean } from \"lodash/fp\"\r\nimport {\r\n typeFunctions,\r\n makerule,\r\n parsedSuccess,\r\n getDefaultExport,\r\n} from \"./typeHelpers\"\r\nimport {\r\n switchCase,\r\n defaultCase,\r\n toBoolOrNull,\r\n toNumberOrNull,\r\n isSafeInteger,\r\n isArrayOfString,\r\n} from \"../common\"\r\n\r\nconst stringFunctions = typeFunctions({\r\n default: constant(null),\r\n})\r\n\r\nconst stringTryParse = switchCase(\r\n [isString, parsedSuccess],\r\n [isNull, parsedSuccess],\r\n [defaultCase, v => parsedSuccess(v.toString())]\r\n)\r\n\r\nconst options = {\r\n maxLength: {\r\n defaultValue: null,\r\n isValid: n => n === null || (isSafeInteger(n) && n > 0),\r\n requirementDescription:\r\n \"max length must be null (no limit) or a greater than zero integer\",\r\n parse: toNumberOrNull,\r\n },\r\n values: {\r\n defaultValue: null,\r\n isValid: v =>\r\n v === null || (isArrayOfString(v) && v.length > 0 && v.length < 10000),\r\n requirementDescription:\r\n \"'values' must be null (no values) or an arry of at least one string\",\r\n parse: s => s,\r\n },\r\n allowDeclaredValuesOnly: {\r\n defaultValue: false,\r\n isValid: isBoolean,\r\n requirementDescription: \"allowDeclaredValuesOnly must be true or false\",\r\n parse: toBoolOrNull,\r\n },\r\n}\r\n\r\nconst typeConstraints = [\r\n makerule(\r\n async (val, opts) =>\r\n val === null || opts.maxLength === null || val.length <= opts.maxLength,\r\n (val, opts) => `value exceeds maximum length of ${opts.maxLength}`\r\n ),\r\n makerule(\r\n async (val, opts) =>\r\n val === null ||\r\n opts.allowDeclaredValuesOnly === false ||\r\n includes(val)(opts.values),\r\n val => `\"${val}\" does not exist in the list of allowed values`\r\n ),\r\n]\r\n\r\nexport default getDefaultExport(\r\n \"string\",\r\n stringTryParse,\r\n stringFunctions,\r\n options,\r\n typeConstraints,\r\n \"abcde\",\r\n str => str\r\n)\r\n",
"import { constant, isBoolean, isNull } from \"lodash/fp\"\r\nimport {\r\n typeFunctions,\r\n makerule,\r\n parsedFailed,\r\n parsedSuccess,\r\n getDefaultExport,\r\n} from \"./typeHelpers\"\r\nimport { switchCase, defaultCase, isOneOf, toBoolOrNull } from \"../common\"\r\n\r\nconst boolFunctions = typeFunctions({\r\n default: constant(null),\r\n})\r\n\r\nconst boolTryParse = switchCase(\r\n [isBoolean, parsedSuccess],\r\n [isNull, parsedSuccess],\r\n [isOneOf(\"true\", \"1\", \"yes\", \"on\"), () => parsedSuccess(true)],\r\n [isOneOf(\"false\", \"0\", \"no\", \"off\"), () => parsedSuccess(false)],\r\n [defaultCase, parsedFailed]\r\n)\r\n\r\nconst options = {\r\n allowNulls: {\r\n defaultValue: true,\r\n isValid: isBoolean,\r\n requirementDescription: \"must be a true or false\",\r\n parse: toBoolOrNull,\r\n },\r\n}\r\n\r\nconst typeConstraints = [\r\n makerule(\r\n async (val, opts) => opts.allowNulls === true || val !== null,\r\n () => \"field cannot be null\"\r\n ),\r\n]\r\n\r\nexport default getDefaultExport(\r\n \"bool\",\r\n boolTryParse,\r\n boolFunctions,\r\n options,\r\n typeConstraints,\r\n true,\r\n JSON.stringify\r\n)\r\n",
"import { constant, isNumber, isString, isNull } from \"lodash/fp\"\r\nimport {\r\n makerule,\r\n typeFunctions,\r\n parsedFailed,\r\n parsedSuccess,\r\n getDefaultExport,\r\n} from \"./typeHelpers\"\r\nimport {\r\n switchCase,\r\n defaultCase,\r\n toNumberOrNull,\r\n isSafeInteger,\r\n} from \"../common\"\r\n\r\nconst numberFunctions = typeFunctions({\r\n default: constant(null),\r\n})\r\n\r\nconst parseStringtoNumberOrNull = s => {\r\n const num = Number(s)\r\n return isNaN(num) ? parsedFailed(s) : parsedSuccess(num)\r\n}\r\n\r\nconst numberTryParse = switchCase(\r\n [isNumber, parsedSuccess],\r\n [isString, parseStringtoNumberOrNull],\r\n [isNull, parsedSuccess],\r\n [defaultCase, parsedFailed]\r\n)\r\n\r\nconst options = {\r\n maxValue: {\r\n defaultValue: Number.MAX_SAFE_INTEGER,\r\n isValid: isSafeInteger,\r\n requirementDescription: \"must be a valid integer\",\r\n parse: toNumberOrNull,\r\n },\r\n minValue: {\r\n defaultValue: 0 - Number.MAX_SAFE_INTEGER,\r\n isValid: isSafeInteger,\r\n requirementDescription: \"must be a valid integer\",\r\n parse: toNumberOrNull,\r\n },\r\n decimalPlaces: {\r\n defaultValue: 0,\r\n isValid: n => isSafeInteger(n) && n >= 0,\r\n requirementDescription: \"must be a positive integer\",\r\n parse: toNumberOrNull,\r\n },\r\n}\r\n\r\nconst getDecimalPlaces = val => {\r\n const splitDecimal = val.toString().split(\".\")\r\n if (splitDecimal.length === 1) return 0\r\n return splitDecimal[1].length\r\n}\r\n\r\nconst typeConstraints = [\r\n makerule(\r\n async (val, opts) =>\r\n val === null || opts.minValue === null || val >= opts.minValue,\r\n (val, opts) =>\r\n `value (${val.toString()}) must be greater than or equal to ${\r\n opts.minValue\r\n }`\r\n ),\r\n makerule(\r\n async (val, opts) =>\r\n val === null || opts.maxValue === null || val <= opts.maxValue,\r\n (val, opts) =>\r\n `value (${val.toString()}) must be less than or equal to ${\r\n opts.minValue\r\n } options`\r\n ),\r\n makerule(\r\n async (val, opts) =>\r\n val === null || opts.decimalPlaces >= getDecimalPlaces(val),\r\n (val, opts) =>\r\n `value (${val.toString()}) must have ${\r\n opts.decimalPlaces\r\n } decimal places or less`\r\n ),\r\n]\r\n\r\nexport default getDefaultExport(\r\n \"number\",\r\n numberTryParse,\r\n numberFunctions,\r\n options,\r\n typeConstraints,\r\n 1,\r\n num => num.toString()\r\n)\r\n",
"import { constant, isDate, isString, isNull } from \"lodash/fp\"\r\nimport {\r\n makerule,\r\n typeFunctions,\r\n parsedFailed,\r\n parsedSuccess,\r\n getDefaultExport,\r\n} from \"./typeHelpers\"\r\nimport { switchCase, defaultCase, toDateOrNull } from \"../common\"\r\n\r\nconst dateFunctions = typeFunctions({\r\n default: constant(null),\r\n now: () => new Date(),\r\n})\r\n\r\nconst isValidDate = d => d instanceof Date && !isNaN(d)\r\n\r\nconst parseStringToDate = s =>\r\n switchCase(\r\n [isValidDate, parsedSuccess],\r\n [defaultCase, parsedFailed]\r\n )(new Date(s))\r\n\r\nconst dateTryParse = switchCase(\r\n [isDate, parsedSuccess],\r\n [isString, parseStringToDate],\r\n [isNull, parsedSuccess],\r\n [defaultCase, parsedFailed]\r\n)\r\n\r\nconst options = {\r\n maxValue: {\r\n defaultValue: new Date(32503680000000),\r\n isValid: isDate,\r\n requirementDescription: \"must be a valid date\",\r\n parse: toDateOrNull,\r\n },\r\n minValue: {\r\n defaultValue: new Date(-8520336000000),\r\n isValid: isDate,\r\n requirementDescription: \"must be a valid date\",\r\n parse: toDateOrNull,\r\n },\r\n}\r\n\r\nconst typeConstraints = [\r\n makerule(\r\n async (val, opts) =>\r\n val === null || opts.minValue === null || val >= opts.minValue,\r\n (val, opts) =>\r\n `value (${val.toString()}) must be greater than or equal to ${\r\n opts.minValue\r\n }`\r\n ),\r\n makerule(\r\n async (val, opts) =>\r\n val === null || opts.maxValue === null || val <= opts.maxValue,\r\n (val, opts) =>\r\n `value (${val.toString()}) must be less than or equal to ${\r\n opts.minValue\r\n } options`\r\n ),\r\n]\r\n\r\nexport default getDefaultExport(\r\n \"datetime\",\r\n dateTryParse,\r\n dateFunctions,\r\n options,\r\n typeConstraints,\r\n new Date(1984, 4, 1),\r\n date => JSON.stringify(date).replace(new RegExp('\"', \"g\"), \"\")\r\n)\r\n",
"import { map, constant, isArray } from \"lodash/fp\"\r\nimport {\r\n typeFunctions,\r\n makerule,\r\n parsedFailed,\r\n getDefaultExport,\r\n parsedSuccess,\r\n} from \"./typeHelpers\"\r\nimport {\r\n switchCase,\r\n defaultCase,\r\n toNumberOrNull,\r\n $$,\r\n isSafeInteger,\r\n} from \"../common\"\r\n\r\nconst arrayFunctions = () =>\r\n typeFunctions({\r\n default: constant([]),\r\n })\r\n\r\nconst mapToParsedArrary = type =>\r\n $$(\r\n map(i => type.safeParseValue(i)),\r\n parsedSuccess\r\n )\r\n\r\nconst arrayTryParse = type =>\r\n switchCase([isArray, mapToParsedArrary(type)], [defaultCase, parsedFailed])\r\n\r\nconst typeName = type => `array<${type}>`\r\n\r\nconst options = {\r\n maxLength: {\r\n defaultValue: 10000,\r\n isValid: isSafeInteger,\r\n requirementDescription: \"must be a positive integer\",\r\n parse: toNumberOrNull,\r\n },\r\n minLength: {\r\n defaultValue: 0,\r\n isValid: n => isSafeInteger(n) && n >= 0,\r\n requirementDescription: \"must be a positive integer\",\r\n parse: toNumberOrNull,\r\n },\r\n}\r\n\r\nconst typeConstraints = [\r\n makerule(\r\n async (val, opts) => val === null || val.length >= opts.minLength,\r\n (val, opts) => `must choose ${opts.minLength} or more options`\r\n ),\r\n makerule(\r\n async (val, opts) => val === null || val.length <= opts.maxLength,\r\n (val, opts) => `cannot choose more than ${opts.maxLength} options`\r\n ),\r\n]\r\n\r\nexport default type =>\r\n getDefaultExport(\r\n typeName(type.name),\r\n arrayTryParse(type),\r\n arrayFunctions(type),\r\n options,\r\n typeConstraints,\r\n [type.sampleValue],\r\n JSON.stringify\r\n )\r\n",
"import { isString, isObjectLike, isNull, has, isEmpty } from \"lodash/fp\"\r\nimport {\r\n typeFunctions,\r\n makerule,\r\n parsedSuccess,\r\n getDefaultExport,\r\n parsedFailed,\r\n} from \"./typeHelpers\"\r\nimport {\r\n switchCase,\r\n defaultCase,\r\n isNonEmptyString,\r\n isArrayOfString,\r\n} from \"../common\"\r\n\r\nconst referenceNothing = () => ({ key: \"\" })\r\n\r\nconst referenceFunctions = typeFunctions({\r\n default: referenceNothing,\r\n})\r\n\r\nconst hasStringValue = (ob, path) => has(path)(ob) && isString(ob[path])\r\n\r\nconst isObjectWithKey = v => isObjectLike(v) && hasStringValue(v, \"key\")\r\n\r\nconst tryParseFromString = s => {\r\n try {\r\n const asObj = JSON.parse(s)\r\n if (isObjectWithKey) {\r\n return parsedSuccess(asObj)\r\n }\r\n } catch (_) {\r\n // EMPTY\r\n }\r\n\r\n return parsedFailed(s)\r\n}\r\n\r\nconst referenceTryParse = v =>\r\n switchCase(\r\n [isObjectWithKey, parsedSuccess],\r\n [isString, tryParseFromString],\r\n [isNull, () => parsedSuccess(referenceNothing())],\r\n [defaultCase, parsedFailed]\r\n )(v)\r\n\r\nconst options = {\r\n indexNodeKey: {\r\n defaultValue: null,\r\n isValid: isNonEmptyString,\r\n requirementDescription: \"must be a non-empty string\",\r\n parse: s => s,\r\n },\r\n displayValue: {\r\n defaultValue: \"\",\r\n isValid: isNonEmptyString,\r\n requirementDescription: \"must be a non-empty string\",\r\n parse: s => s,\r\n },\r\n reverseIndexNodeKeys: {\r\n defaultValue: null,\r\n isValid: v => isArrayOfString(v) && v.length > 0,\r\n requirementDescription: \"must be a non-empty array of strings\",\r\n parse: s => s,\r\n },\r\n}\r\n\r\nconst isEmptyString = s => isString(s) && isEmpty(s)\r\n\r\nconst ensureReferenceExists = async (val, opts, context) =>\r\n isEmptyString(val.key) || (await context.referenceExists(opts, val.key))\r\n\r\nconst typeConstraints = [\r\n makerule(\r\n ensureReferenceExists,\r\n (val, opts) =>\r\n `\"${val[opts.displayValue]}\" does not exist in options list (key: ${\r\n val.key\r\n })`\r\n ),\r\n]\r\n\r\nexport default getDefaultExport(\r\n \"reference\",\r\n referenceTryParse,\r\n referenceFunctions,\r\n options,\r\n typeConstraints,\r\n { key: \"key\", value: \"value\" },\r\n JSON.stringify\r\n)\r\n",
"import { last, has, isString, intersection, isNull, isNumber } from \"lodash/fp\"\r\nimport {\r\n typeFunctions,\r\n parsedFailed,\r\n parsedSuccess,\r\n getDefaultExport,\r\n} from \"./typeHelpers\"\r\nimport { switchCase, defaultCase, none, $, splitKey } from \"../common\"\r\n\r\nconst illegalCharacters = \"*?\\\\/:<>|\\0\\b\\f\\v\"\r\n\r\nexport const isLegalFilename = filePath => {\r\n const fn = fileName(filePath)\r\n return (\r\n fn.length <= 255 &&\r\n intersection(fn.split(\"\"))(illegalCharacters.split(\"\")).length === 0 &&\r\n none(f => f === \"..\")(splitKey(filePath))\r\n )\r\n}\r\n\r\nconst fileNothing = () => ({ relativePath: \"\", size: 0 })\r\n\r\nconst fileFunctions = typeFunctions({\r\n default: fileNothing,\r\n})\r\n\r\nconst fileTryParse = v =>\r\n switchCase(\r\n [isValidFile, parsedSuccess],\r\n [isNull, () => parsedSuccess(fileNothing())],\r\n [defaultCase, parsedFailed]\r\n )(v)\r\n\r\nconst fileName = filePath => $(filePath, [splitKey, last])\r\n\r\nconst isValidFile = f =>\r\n !isNull(f) &&\r\n has(\"relativePath\")(f) &&\r\n has(\"size\")(f) &&\r\n isNumber(f.size) &&\r\n isString(f.relativePath) &&\r\n isLegalFilename(f.relativePath)\r\n\r\nconst options = {}\r\n\r\nconst typeConstraints = []\r\n\r\nexport default getDefaultExport(\r\n \"file\",\r\n fileTryParse,\r\n fileFunctions,\r\n options,\r\n typeConstraints,\r\n { relativePath: \"some_file.jpg\", size: 1000 },\r\n JSON.stringify\r\n)\r\n",
"import { assign, merge } from \"lodash\"\r\nimport {\r\n map,\r\n isString,\r\n isNumber,\r\n isBoolean,\r\n isDate,\r\n keys,\r\n isObject,\r\n isArray,\r\n has,\r\n} from \"lodash/fp\"\r\nimport { $ } from \"../common\"\r\nimport { parsedSuccess } from \"./typeHelpers\"\r\nimport string from \"./string\"\r\nimport bool from \"./bool\"\r\nimport number from \"./number\"\r\nimport datetime from \"./datetime\"\r\nimport array from \"./array\"\r\nimport reference from \"./reference\"\r\nimport file from \"./file\"\r\nimport { BadRequestError } from \"../common/errors\"\r\n\r\nconst allTypes = () => {\r\n const basicTypes = {\r\n string,\r\n number,\r\n datetime,\r\n bool,\r\n reference,\r\n file,\r\n }\r\n\r\n const arrays = $(basicTypes, [\r\n keys,\r\n map(k => {\r\n const kvType = {}\r\n const concreteArray = array(basicTypes[k])\r\n kvType[concreteArray.name] = concreteArray\r\n return kvType\r\n }),\r\n types => assign({}, ...types),\r\n ])\r\n\r\n return merge({}, basicTypes, arrays)\r\n}\r\n\r\nexport const all = allTypes()\r\n\r\nexport const getType = typeName => {\r\n if (!has(typeName)(all))\r\n throw new BadRequestError(`Do not recognise type ${typeName}`)\r\n return all[typeName]\r\n}\r\n\r\nexport const getSampleFieldValue = field => getType(field.type).sampleValue\r\n\r\nexport const getNewFieldValue = field => getType(field.type).getNew(field)\r\n\r\nexport const safeParseField = (field, record) =>\r\n getType(field.type).safeParseField(field, record)\r\n\r\nexport const validateFieldParse = (field, record) =>\r\n has(field.name)(record)\r\n ? getType(field.type).tryParse(record[field.name])\r\n : parsedSuccess(undefined) // fields may be undefined by default\r\n\r\nexport const getDefaultOptions = type => getType(type).getDefaultOptions()\r\n\r\nexport const validateTypeConstraints = async (field, record, context) =>\r\n await getType(field.type).validateTypeConstraints(field, record, context)\r\n\r\nexport const detectType = value => {\r\n if (isString(value)) return string\r\n if (isBoolean(value)) return bool\r\n if (isNumber(value)) return number\r\n if (isDate(value)) return datetime\r\n if (isArray(value)) return array(detectType(value[0]))\r\n if (isObject(value) && has(\"key\")(value) && has(\"value\")(value))\r\n return reference\r\n if (isObject(value) && has(\"relativePath\")(value) && has(\"size\")(value))\r\n return file\r\n\r\n throw new BadRequestError(`cannot determine type: ${JSON.stringify(value)}`)\r\n}\r\n",
"import { clone, find, split } from \"lodash/fp\"\r\nimport { joinKey, $ } from \"../common\"\r\n// 5 minutes\r\nexport const tempCodeExpiryLength = 5 * 60 * 1000\r\n\r\nexport const AUTH_FOLDER = \"/.auth\"\r\nexport const USERS_LIST_FILE = joinKey(AUTH_FOLDER, \"users.json\")\r\nexport const userAuthFile = username =>\r\n joinKey(AUTH_FOLDER, `auth_${username}.json`)\r\nexport const USERS_LOCK_FILE = joinKey(AUTH_FOLDER, \"users_lock\")\r\nexport const ACCESS_LEVELS_FILE = joinKey(AUTH_FOLDER, \"access_levels.json\")\r\nexport const ACCESS_LEVELS_LOCK_FILE = joinKey(\r\n AUTH_FOLDER,\r\n \"access_levels_lock\"\r\n)\r\n\r\nexport const permissionTypes = {\r\n CREATE_RECORD: \"create record\",\r\n UPDATE_RECORD: \"update record\",\r\n READ_RECORD: \"read record\",\r\n DELETE_RECORD: \"delete record\",\r\n READ_INDEX: \"read index\",\r\n MANAGE_INDEX: \"manage index\",\r\n MANAGE_COLLECTION: \"manage collection\",\r\n WRITE_TEMPLATES: \"write templates\",\r\n CREATE_USER: \"create user\",\r\n SET_PASSWORD: \"set password\",\r\n CREATE_TEMPORARY_ACCESS: \"create temporary access\",\r\n ENABLE_DISABLE_USER: \"enable or disable user\",\r\n WRITE_ACCESS_LEVELS: \"write access levels\",\r\n LIST_USERS: \"list users\",\r\n LIST_ACCESS_LEVELS: \"list access levels\",\r\n EXECUTE_ACTION: \"execute action\",\r\n SET_USER_ACCESS_LEVELS: \"set user access levels\",\r\n}\r\n\r\nexport const getUserByName = (users, name) =>\r\n $(users, [find(u => u.name.toLowerCase() === name.toLowerCase())])\r\n\r\nexport const stripUserOfSensitiveStuff = user => {\r\n const stripped = clone(user)\r\n delete stripped.tempCode\r\n return stripped\r\n}\r\n\r\nexport const parseTemporaryCode = fullCode =>\r\n $(fullCode, [\r\n split(\":\"),\r\n parts => ({\r\n id: parts[1],\r\n code: parts[2],\r\n }),\r\n ])\r\n",
"import { values, includes, some } from \"lodash/fp\"\r\nimport { permissionTypes } from \"./authCommon\"\r\nimport { $, isNothing, apiWrapperSync, events } from \"../common\"\r\nimport { getNodeByKeyOrNodeKey, isNode } from \"../templateApi/hierarchy\"\r\nimport { alwaysAuthorized } from \"./permissions\"\r\n\r\nexport const isAuthorized = app => (permissionType, resourceKey) =>\r\n apiWrapperSync(\r\n app,\r\n events.authApi.isAuthorized,\r\n alwaysAuthorized,\r\n { resourceKey, permissionType },\r\n _isAuthorized,\r\n app,\r\n permissionType,\r\n resourceKey\r\n )\r\n\r\nexport const _isAuthorized = (app, permissionType, resourceKey) => {\r\n if (!app.user) {\r\n return false\r\n }\r\n\r\n const validType = $(permissionTypes, [values, includes(permissionType)])\r\n\r\n if (!validType) {\r\n return false\r\n }\r\n\r\n const permMatchesResource = userperm => {\r\n const nodeKey = isNothing(resourceKey)\r\n ? null\r\n : isNode(app.hierarchy, resourceKey)\r\n ? getNodeByKeyOrNodeKey(app.hierarchy, resourceKey).nodeKey()\r\n : resourceKey\r\n\r\n return (\r\n userperm.type === permissionType &&\r\n (isNothing(resourceKey) || nodeKey === userperm.nodeKey)\r\n )\r\n }\r\n\r\n return $(app.user.permissions, [some(permMatchesResource)])\r\n}\r\n",
"import { permissionTypes } from \"./authCommon\"\r\nimport { isAuthorized } from \"./isAuthorized\"\r\n\r\nexport const temporaryAccessPermissions = () => [\r\n { type: permissionTypes.SET_PASSWORD },\r\n]\r\n\r\nconst nodePermission = type => ({\r\n add: (nodeKey, accessLevel) =>\r\n accessLevel.permissions.push({ type, nodeKey }),\r\n isAuthorized: resourceKey => app => isAuthorized(app)(type, resourceKey),\r\n isNode: true,\r\n get: nodeKey => ({ type, nodeKey }),\r\n})\r\n\r\nconst staticPermission = type => ({\r\n add: accessLevel => accessLevel.permissions.push({ type }),\r\n isAuthorized: app => isAuthorized(app)(type),\r\n isNode: false,\r\n get: () => ({ type }),\r\n})\r\n\r\nconst createRecord = nodePermission(permissionTypes.CREATE_RECORD)\r\n\r\nconst updateRecord = nodePermission(permissionTypes.UPDATE_RECORD)\r\n\r\nconst deleteRecord = nodePermission(permissionTypes.DELETE_RECORD)\r\n\r\nconst readRecord = nodePermission(permissionTypes.READ_RECORD)\r\n\r\nconst writeTemplates = staticPermission(permissionTypes.WRITE_TEMPLATES)\r\n\r\nconst createUser = staticPermission(permissionTypes.CREATE_USER)\r\n\r\nconst setPassword = staticPermission(permissionTypes.SET_PASSWORD)\r\n\r\nconst readIndex = nodePermission(permissionTypes.READ_INDEX)\r\n\r\nconst manageIndex = staticPermission(permissionTypes.MANAGE_INDEX)\r\n\r\nconst manageCollection = staticPermission(permissionTypes.MANAGE_COLLECTION)\r\n\r\nconst createTemporaryAccess = staticPermission(\r\n permissionTypes.CREATE_TEMPORARY_ACCESS\r\n)\r\n\r\nconst enableDisableUser = staticPermission(permissionTypes.ENABLE_DISABLE_USER)\r\n\r\nconst writeAccessLevels = staticPermission(permissionTypes.WRITE_ACCESS_LEVELS)\r\n\r\nconst listUsers = staticPermission(permissionTypes.LIST_USERS)\r\n\r\nconst listAccessLevels = staticPermission(permissionTypes.LIST_ACCESS_LEVELS)\r\n\r\nconst setUserAccessLevels = staticPermission(\r\n permissionTypes.SET_USER_ACCESS_LEVELS\r\n)\r\n\r\nconst executeAction = nodePermission(permissionTypes.EXECUTE_ACTION)\r\n\r\nexport const alwaysAuthorized = () => true\r\n\r\nexport const permission = {\r\n createRecord,\r\n updateRecord,\r\n deleteRecord,\r\n readRecord,\r\n writeTemplates,\r\n createUser,\r\n setPassword,\r\n readIndex,\r\n createTemporaryAccess,\r\n enableDisableUser,\r\n writeAccessLevels,\r\n listUsers,\r\n listAccessLevels,\r\n manageIndex,\r\n manageCollection,\r\n executeAction,\r\n setUserAccessLevels,\r\n}\r\n",
"import { keyBy, mapValues } from \"lodash/fp\"\r\nimport { generate } from \"shortid\"\r\nimport {\r\n getNodeForCollectionPath,\r\n isSingleRecord,\r\n} from \"../templateApi/hierarchy\"\r\nimport { getNewFieldValue } from \"../types\"\r\nimport { $, joinKey, safeKey, apiWrapperSync, events } from \"../common\"\r\nimport { permission } from \"../authApi/permissions\"\r\n\r\nexport const getNew = app => (collectionKey, recordTypeName) => {\r\n const recordNode = getRecordNode(app, collectionKey, recordTypeName)\r\n collectionKey = safeKey(collectionKey)\r\n return apiWrapperSync(\r\n app,\r\n events.recordApi.getNew,\r\n permission.createRecord.isAuthorized(recordNode.nodeKey()),\r\n { collectionKey, recordTypeName },\r\n _getNew,\r\n recordNode,\r\n collectionKey\r\n )\r\n}\r\n\r\nexport const _getNew = (recordNode, collectionKey) =>\r\n constructRecord(recordNode, getNewFieldValue, collectionKey)\r\n\r\nconst getRecordNode = (app, collectionKey) => {\r\n collectionKey = safeKey(collectionKey)\r\n return getNodeForCollectionPath(app.hierarchy)(collectionKey)\r\n}\r\n\r\nexport const getNewChild = app => (recordKey, collectionName, recordTypeName) =>\r\n getNew(app)(joinKey(recordKey, collectionName), recordTypeName)\r\n\r\nexport const constructRecord = (recordNode, getFieldValue, collectionKey) => {\r\n const record = $(recordNode.fields, [keyBy(\"name\"), mapValues(getFieldValue)])\r\n\r\n record.id = `${recordNode.nodeId}-${generate()}`\r\n record.key = isSingleRecord(recordNode)\r\n ? joinKey(collectionKey, recordNode.name)\r\n : joinKey(collectionKey, record.id)\r\n record.isNew = true\r\n record.type = recordNode.name\r\n return record\r\n}\r\n",
"import { each, find } from \"lodash\"\r\nimport { map, max, constant } from \"lodash/fp\"\r\nimport {\r\n switchCase,\r\n defaultCase,\r\n joinKey,\r\n $,\r\n isNothing,\r\n isSomething,\r\n} from \"../common\"\r\nimport {\r\n isIndex,\r\n isRoot,\r\n isSingleRecord,\r\n isCollectionRecord,\r\n isRecord,\r\n isaggregateGroup,\r\n getFlattenedHierarchy,\r\n} from \"./hierarchy\"\r\nimport { all } from \"../types\"\r\nimport { BadRequestError } from \"../common/errors\"\r\n\r\nexport const createNodeErrors = {\r\n indexCannotBeParent: \"Index template cannot be a parent\",\r\n allNonRootNodesMustHaveParent: \"Only the root node may have no parent\",\r\n indexParentMustBeRecordOrRoot:\r\n \"An index may only have a record or root as a parent\",\r\n aggregateParentMustBeAnIndex: \"aggregateGroup parent must be an index\",\r\n}\r\n\r\nconst pathRegxMaker = node => () =>\r\n node.nodeKey().replace(/{id}/g, \"[a-zA-Z0-9_-]+\")\r\n\r\nconst nodeKeyMaker = node => () =>\r\n switchCase(\r\n [\r\n n => isRecord(n) && !isSingleRecord(n),\r\n n =>\r\n joinKey(\r\n node.parent().nodeKey(),\r\n node.collectionName,\r\n `${n.nodeId}-{id}`\r\n ),\r\n ],\r\n\r\n [isRoot, constant(\"/\")],\r\n\r\n [defaultCase, n => joinKey(node.parent().nodeKey(), n.name)]\r\n )(node)\r\n\r\nconst validate = parent => node => {\r\n if (\r\n isIndex(node) &&\r\n isSomething(parent) &&\r\n !isRoot(parent) &&\r\n !isRecord(parent)\r\n ) {\r\n throw new BadRequestError(createNodeErrors.indexParentMustBeRecordOrRoot)\r\n }\r\n\r\n if (isaggregateGroup(node) && isSomething(parent) && !isIndex(parent)) {\r\n throw new BadRequestError(createNodeErrors.aggregateParentMustBeAnIndex)\r\n }\r\n\r\n if (isNothing(parent) && !isRoot(node)) {\r\n throw new BadRequestError(createNodeErrors.allNonRootNodesMustHaveParent)\r\n }\r\n\r\n return node\r\n}\r\n\r\nconst construct = parent => node => {\r\n node.nodeKey = nodeKeyMaker(node)\r\n node.pathRegx = pathRegxMaker(node)\r\n node.parent = constant(parent)\r\n node.isRoot = () =>\r\n isNothing(parent) && node.name === \"root\" && node.type === \"root\"\r\n if (isCollectionRecord(node)) {\r\n node.collectionNodeKey = () =>\r\n joinKey(parent.nodeKey(), node.collectionName)\r\n node.collectionPathRegx = () =>\r\n joinKey(parent.pathRegx(), node.collectionName)\r\n }\r\n return node\r\n}\r\n\r\nconst addToParent = obj => {\r\n const parent = obj.parent()\r\n if (isSomething(parent)) {\r\n if (isIndex(obj)) {\r\n // Q: why are indexes not children ?\r\n // A: because they cannot have children of their own.\r\n parent.indexes.push(obj)\r\n } else if (isaggregateGroup(obj)) {\r\n parent.aggregateGroups.push(obj)\r\n } else {\r\n parent.children.push(obj)\r\n }\r\n\r\n if (isRecord(obj)) {\r\n const defaultIndex = find(\r\n parent.indexes,\r\n i => i.name === `${parent.name}_index`\r\n )\r\n if (defaultIndex) {\r\n defaultIndex.allowedModelNodeIds.push(obj.nodeId)\r\n }\r\n }\r\n }\r\n return obj\r\n}\r\n\r\nexport const constructNode = (parent, obj) =>\r\n $(obj, [construct(parent), validate(parent), addToParent])\r\n\r\nconst getNodeId = parentNode => {\r\n // this case is handled better elsewhere\r\n if (!parentNode) return null\r\n const findRoot = n => (isRoot(n) ? n : findRoot(n.parent()))\r\n const root = findRoot(parentNode)\r\n\r\n return $(root, [getFlattenedHierarchy, map(n => n.nodeId), max]) + 1\r\n}\r\n\r\nexport const constructHierarchy = (node, parent) => {\r\n construct(parent)(node)\r\n if (node.indexes) {\r\n each(node.indexes, child => constructHierarchy(child, node))\r\n }\r\n if (node.aggregateGroups) {\r\n each(node.aggregateGroups, child => constructHierarchy(child, node))\r\n }\r\n if (node.children && node.children.length > 0) {\r\n each(node.children, child => constructHierarchy(child, node))\r\n }\r\n if (node.fields) {\r\n each(node.fields, f =
"import { createCoreApp } from \"./createCoreApp\"\r\nimport { getNew, getNewChild } from \"../../../core/src/recordApi/getNew\"\r\nimport { constructHierarchy } from \"../../../core/src/templateApi/createNodes\"\r\n\r\nexport const createCoreApi = (backendDefinition, user) => {\r\n const app = createCoreApp(backendDefinition, user)\r\n\r\n return {\r\n recordApi: {\r\n getNew: getNew(app),\r\n getNewChild: getNewChild(app),\r\n },\r\n\r\n templateApi: {\r\n constructHierarchy,\r\n },\r\n }\r\n}\r\n",
"export const BB_STATE_BINDINGPATH = \"##bbstate\"\r\nexport const BB_STATE_BINDINGSOURCE = \"##bbsource\"\r\nexport const BB_STATE_FALLBACK = \"##bbstatefallback\"\r\n\r\nexport const isBound = prop =>\r\n prop !== undefined && prop[BB_STATE_BINDINGPATH] !== undefined\r\n\r\nexport const takeStateFromStore = prop =>\r\n prop[BB_STATE_BINDINGSOURCE] === undefined ||\r\n prop[BB_STATE_BINDINGSOURCE] === \"store\"\r\n\r\nexport const takeStateFromContext = prop =>\r\n prop[BB_STATE_BINDINGSOURCE] === \"context\"\r\n\r\nexport const takeStateFromEventParameters = prop =>\r\n prop[BB_STATE_BINDINGSOURCE] === \"event\"\r\n",
"import { isUndefined, isObject } from \"lodash/fp\"\r\nimport {\r\n isBound,\r\n BB_STATE_BINDINGPATH,\r\n BB_STATE_FALLBACK,\r\n takeStateFromStore,\r\n} from \"./isState\"\r\n\r\nexport const getState = (s, path, fallback) => {\r\n if (!s) return fallback\r\n if (!path || path.length === 0) return fallback\r\n\r\n if (path === \"$\") return s\r\n\r\n const pathParts = path.split(\".\")\r\n const safeGetPath = (obj, currentPartIndex = 0) => {\r\n const currentKey = pathParts[currentPartIndex]\r\n\r\n if (pathParts.length - 1 == currentPartIndex) {\r\n const value = obj[currentKey]\r\n if (isUndefined(value)) return fallback\r\n else return value\r\n }\r\n\r\n if (\r\n obj[currentKey] === null ||\r\n obj[currentKey] === undefined ||\r\n !isObject(obj[currentKey])\r\n ) {\r\n return fallback\r\n }\r\n\r\n return safeGetPath(obj[currentKey], currentPartIndex + 1)\r\n }\r\n\r\n return safeGetPath(s)\r\n}\r\n\r\nexport const getStateOrValue = (globalState, prop, currentContext) => {\r\n if (!prop) return prop\r\n\r\n if (isBound(prop)) {\r\n const stateToUse = takeStateFromStore(prop) ? globalState : currentContext\r\n\r\n return getState(\r\n stateToUse,\r\n prop[BB_STATE_BINDINGPATH],\r\n prop[BB_STATE_FALLBACK]\r\n )\r\n }\r\n\r\n if (prop.path && prop.source) {\r\n const stateToUse = prop.source === \"store\" ? globalState : currentContext\r\n\r\n return getState(stateToUse, prop.path, prop.fallback)\r\n }\r\n\r\n return prop\r\n}\r\n",
"import { isObject } from \"lodash/fp\"\r\nimport { BB_STATE_BINDINGPATH } from \"./isState\"\r\n\r\nexport const setState = (store, path, value) => {\r\n if (!path || path.length === 0) return\r\n\r\n const pathParts = path.split(\".\")\r\n const safeSetPath = (obj, currentPartIndex = 0) => {\r\n const currentKey = pathParts[currentPartIndex]\r\n\r\n if (pathParts.length - 1 == currentPartIndex) {\r\n obj[currentKey] = value\r\n return\r\n }\r\n\r\n if (\r\n obj[currentKey] === null ||\r\n obj[currentKey] === undefined ||\r\n !isObject(obj[currentKey])\r\n ) {\r\n obj[currentKey] = {}\r\n }\r\n\r\n safeSetPath(obj[currentKey], currentPartIndex + 1)\r\n }\r\n\r\n store.update(s => {\r\n safeSetPath(s)\r\n return s\r\n })\r\n}\r\n\r\nexport const setStateFromBinding = (store, binding, value) =>\r\n setState(store, binding[BB_STATE_BINDINGPATH], value)\r\n",
"export const trimSlash = str => str.replace(/^\\/+|\\/+$/g, \"\")\r\n",
"export const ERROR = \"##error_message\"\r\n",
"import { trimSlash } from \"../common/trimSlash\"\r\n\r\nexport const loadRecord = api => async ({ recordKey, statePath }) => {\r\n if (!recordKey) {\r\n api.error(\"Load Record: record key not set\")\r\n return\r\n }\r\n\r\n if (!statePath) {\r\n api.error(\"Load Record: state path not set\")\r\n return\r\n }\r\n\r\n const record = await api.get({\r\n url: `/api/record/${trimSlash(recordKey)}`,\r\n })\r\n\r\n if (api.isSuccess(record)) api.setState(statePath, record)\r\n}\r\n",
"import { trimSlash } from \"../common/trimSlash\"\r\n\r\nexport const listRecords = api => async ({ indexKey, statePath }) => {\r\n if (!indexKey) {\r\n api.error(\"Load Record: record key not set\")\r\n return\r\n }\r\n\r\n if (!statePath) {\r\n api.error(\"Load Record: state path not set\")\r\n return\r\n }\r\n\r\n const records = await api.get({\r\n url: `/api/listRecords/${trimSlash(indexKey)}`,\r\n })\r\n\r\n if (api.isSuccess(records)) api.setState(statePath, records)\r\n}\r\n",
"export const USER_STATE_PATH = \"_bbuser\"\r\n\r\nexport const authenticate = api => async ({ username, password }) => {\r\n if (!username) {\r\n api.error(\"Authenticate: username not set\")\r\n return\r\n }\r\n\r\n if (!password) {\r\n api.error(\"Authenticate: password not set\")\r\n return\r\n }\r\n\r\n const user = await api.post({\r\n url: \"/api/authenticate\",\r\n body: { username, password },\r\n })\r\n\r\n // set user even if error - so it is defined at least\r\n api.setState(USER_STATE_PATH, user)\r\n localStorage.setItem(\"budibase:user\", JSON.stringify(user))\r\n}\r\n",
"import { trimSlash } from \"../common/trimSlash\"\r\n\r\nexport const saveRecord = api => async ({ statePath }) => {\r\n if (!statePath) {\r\n api.error(\"Load Record: state path not set\")\r\n return\r\n }\r\n\r\n const recordtoSave = api.getState(statePath)\r\n\r\n if (!recordtoSave) {\r\n api.error(`there is no record in state: ${statePath}`)\r\n return\r\n }\r\n\r\n if (!recordtoSave.key) {\r\n api.error(\r\n `item in state does not appear to be a record - it has no key (${statePath})`\r\n )\r\n return\r\n }\r\n\r\n const savedRecord = await api.post({\r\n url: `/api/record/${trimSlash(recordtoSave.key)}`,\r\n body: recordtoSave,\r\n })\r\n\r\n if (api.isSuccess(savedRecord)) api.setState(statePath, savedRecord)\r\n}\r\n",
"import { ERROR } from \"../state/standardState\"\r\nimport { loadRecord } from \"./loadRecord\"\r\nimport { listRecords } from \"./listRecords\"\r\nimport { authenticate } from \"./authenticate\"\r\nimport { saveRecord } from \"./saveRecord\"\r\n\r\nexport const createApi = ({ rootPath, setState, getState }) => {\r\n const apiCall = method => ({\r\n url,\r\n body,\r\n notFound,\r\n badRequest,\r\n forbidden,\r\n }) => {\r\n return fetch(`${rootPath}${url}`, {\r\n method: method,\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n body: body && JSON.stringify(body),\r\n credentials: \"same-origin\",\r\n }).then(r => {\r\n switch (r.status) {\r\n case 200:\r\n return r.json()\r\n case 404:\r\n return error(notFound || `${url} Not found`)\r\n case 400:\r\n return error(badRequest || `${url} Bad Request`)\r\n case 403:\r\n return error(forbidden || `${url} Forbidden`)\r\n default:\r\n if (\r\n r.status.toString().startsWith(\"2\") ||\r\n r.status.toString().startsWith(\"3\")\r\n )\r\n return r.json()\r\n else return error(`${url} - ${r.statusText}`)\r\n }\r\n })\r\n }\r\n\r\n const post = apiCall(\"POST\")\r\n const get = apiCall(\"GET\")\r\n const patch = apiCall(\"PATCH\")\r\n const del = apiCall(\"DELETE\")\r\n\r\n const ERROR_MEMBER = \"##error\"\r\n const error = message => {\r\n const e = {}\r\n e[ERROR_MEMBER] = message\r\n setState(ERROR, message)\r\n return e\r\n }\r\n\r\n const isSuccess = obj => !obj || !obj[ERROR_MEMBER]\r\n\r\n const apiOpts = {\r\n rootPath,\r\n setState,\r\n getState,\r\n isSuccess,\r\n error,\r\n post,\r\n get,\r\n patch,\r\n delete: del,\r\n }\r\n\r\n return {\r\n loadRecord: loadRecord(apiOpts),\r\n listRecords: listRecords(apiOpts),\r\n authenticate: authenticate(apiOpts),\r\n saveRecord: saveRecord(apiOpts),\r\n }\r\n}\r\n",
"import { ERROR } from \"./standardState\"\r\n\r\nexport const getNewChildRecordToState = (coreApi, setState) => ({\r\n recordKey,\r\n collectionName,\r\n childRecordType,\r\n statePath,\r\n}) => {\r\n const error = errorHandler(setState)\r\n try {\r\n if (!recordKey) {\r\n error(\"getNewChild > recordKey not set\")\r\n return\r\n }\r\n\r\n if (!collectionName) {\r\n error(\"getNewChild > collectionName not set\")\r\n return\r\n }\r\n\r\n if (!childRecordType) {\r\n error(\"getNewChild > childRecordType not set\")\r\n return\r\n }\r\n\r\n if (!statePath) {\r\n error(\"getNewChild > statePath not set\")\r\n return\r\n }\r\n\r\n const rec = coreApi.recordApi.getNewChild(\r\n recordKey,\r\n collectionName,\r\n childRecordType\r\n )\r\n setState(statePath, rec)\r\n } catch (e) {\r\n error(e.message)\r\n }\r\n}\r\n\r\nexport const getNewRecordToState = (coreApi, setState) => ({\r\n collectionKey,\r\n childRecordType,\r\n statePath,\r\n}) => {\r\n const error = errorHandler(setState)\r\n try {\r\n if (!collectionKey) {\r\n error(\"getNewChild > collectionKey not set\")\r\n return\r\n }\r\n\r\n if (!childRecordType) {\r\n error(\"getNewChild > childRecordType not set\")\r\n return\r\n }\r\n\r\n if (!statePath) {\r\n error(\"getNewChild > statePath not set\")\r\n return\r\n }\r\n\r\n const rec = coreApi.recordApi.getNew(collectionKey, childRecordType)\r\n setState(statePath, rec)\r\n } catch (e) {\r\n error(e.message)\r\n }\r\n}\r\n\r\nconst errorHandler = setState => message => setState(ERROR, message)\r\n",
"import { setState } from \"./setState\"\r\nimport { getState } from \"./getState\"\r\nimport { isArray, isUndefined } from \"lodash/fp\"\r\n\r\nimport { createApi } from \"../api\"\r\nimport { getNewChildRecordToState, getNewRecordToState } from \"./coreHandlers\"\r\n\r\nexport const EVENT_TYPE_MEMBER_NAME = \"##eventHandlerType\"\r\n\r\nexport const eventHandlers = (store, coreApi, rootPath) => {\r\n const handler = (parameters, execute) => ({\r\n execute,\r\n parameters,\r\n })\r\n\r\n const setStateWithStore = (path, value) => setState(store, path, value)\r\n\r\n let currentState\r\n store.subscribe(s => {\r\n currentState = s\r\n })\r\n\r\n const api = createApi({\r\n rootPath: rootPath,\r\n setState: setStateWithStore,\r\n getState: (path, fallback) => getState(currentState, path, fallback),\r\n })\r\n\r\n const setStateHandler = ({ path, value }) => setState(store, path, value)\r\n\r\n return {\r\n \"Set State\": handler([\"path\", \"value\"], setStateHandler),\r\n \"Load Record\": handler([\"recordKey\", \"statePath\"], api.loadRecord),\r\n \"List Records\": handler([\"indexKey\", \"statePath\"], api.listRecords),\r\n \"Save Record\": handler([\"statePath\"], api.saveRecord),\r\n\r\n \"Get New Child Record\": handler(\r\n [\"recordKey\", \"collectionName\", \"childRecordType\", \"statePath\"],\r\n getNewChildRecordToState(coreApi, setStateWithStore)\r\n ),\r\n\r\n \"Get New Record\": handler(\r\n [\"collectionKey\", \"childRecordType\", \"statePath\"],\r\n getNewRecordToState(coreApi, setStateWithStore)\r\n ),\r\n\r\n Authenticate: handler([\"username\", \"password\"], api.authenticate),\r\n }\r\n}\r\n\r\nexport const isEventType = prop =>\r\n isArray(prop) &&\r\n prop.length > 0 &&\r\n !isUndefined(prop[0][EVENT_TYPE_MEMBER_NAME])\r\n",
"import {\r\n isEventType,\r\n eventHandlers,\r\n EVENT_TYPE_MEMBER_NAME,\r\n} from \"./eventHandlers\"\r\n\r\nimport { getState } from \"./getState\"\r\n\r\nimport {\r\n isBound,\r\n takeStateFromStore,\r\n takeStateFromContext,\r\n takeStateFromEventParameters,\r\n BB_STATE_FALLBACK,\r\n BB_STATE_BINDINGPATH,\r\n BB_STATE_BINDINGSOURCE,\r\n} from \"./isState\"\r\n\r\nconst doNothing = () => {}\r\ndoNothing.isPlaceholder = true\r\n\r\nconst isMetaProp = propName =>\r\n propName === \"_component\" ||\r\n propName === \"_children\" ||\r\n propName === \"_id\" ||\r\n propName === \"_style\"\r\n\r\nexport const setupBinding = (store, rootProps, coreApi, context, rootPath) => {\r\n const rootInitialProps = { ...rootProps }\r\n\r\n const getBindings = (props, initialProps) => {\r\n const boundProps = []\r\n const contextBoundProps = []\r\n const componentEventHandlers = []\r\n\r\n for (let propName in props) {\r\n if (isMetaProp(propName)) continue\r\n\r\n const val = props[propName]\r\n\r\n if (isBound(val) && takeStateFromStore(val)) {\r\n const binding = BindingPath(val)\r\n const source = BindingSource(val)\r\n const fallback = BindingFallback(val)\r\n\r\n boundProps.push({\r\n path: binding,\r\n fallback,\r\n propName,\r\n source,\r\n })\r\n\r\n initialProps[propName] = fallback\r\n } else if (isBound(val) && takeStateFromContext(val)) {\r\n const binding = BindingPath(val)\r\n const fallback = BindingFallback(val)\r\n const source = BindingSource(val)\r\n\r\n contextBoundProps.push({\r\n path: binding,\r\n fallback,\r\n propName,\r\n source,\r\n })\r\n\r\n initialProps[propName] = !context\r\n ? val\r\n : getState(context, binding, fallback, source)\r\n } else if (isEventType(val)) {\r\n const handlers = { propName, handlers: [] }\r\n componentEventHandlers.push(handlers)\r\n\r\n for (let e of val) {\r\n handlers.handlers.push({\r\n handlerType: e[EVENT_TYPE_MEMBER_NAME],\r\n parameters: e.parameters,\r\n })\r\n }\r\n\r\n initialProps[propName] = doNothing\r\n }\r\n }\r\n\r\n return {\r\n contextBoundProps,\r\n boundProps,\r\n componentEventHandlers,\r\n initialProps,\r\n }\r\n }\r\n\r\n const bind = rootBindings => component => {\r\n if (\r\n rootBindings.boundProps.length === 0 &&\r\n rootBindings.componentEventHandlers.length === 0\r\n )\r\n return\r\n\r\n const handlerTypes = eventHandlers(store, coreApi, rootPath)\r\n\r\n const unsubscribe = store.subscribe(rootState => {\r\n const getPropsFromBindings = (s, bindings) => {\r\n const { boundProps, componentEventHandlers } = bindings\r\n const newProps = { ...bindings.initialProps }\r\n\r\n for (let boundProp of boundProps) {\r\n const val = getState(s, boundProp.path, boundProp.fallback)\r\n\r\n if (val === undefined && newProps[boundProp.propName] !== undefined) {\r\n delete newProps[boundProp.propName]\r\n }\r\n\r\n if (val !== undefined) {\r\n newProps[boundProp.propName] = val\r\n }\r\n }\r\n\r\n for (let boundHandler of componentEventHandlers) {\r\n const closuredHandlers = []\r\n for (let h of boundHandler.handlers) {\r\n const handlerType = handlerTypes[h.handlerType]\r\n closuredHandlers.push(eventContext => {\r\n const parameters = {}\r\n for (let pname in h.parameters) {\r\n const p = h.parameters[pname]\r\n parameters[pname] = !isBound(p)\r\n ? p\r\n : takeStateFromStore(p)\r\n ? getState(s, p[BB_STATE_BINDINGPATH], p[BB_STATE_FALLBACK])\r\n : takeStateFromEventParameters(p)\r\n ? getState(\r\n
"export const renderComponent = ({\r\n componentConstructor,\r\n uiFunctions,\r\n htmlElement,\r\n anchor,\r\n props,\r\n initialProps,\r\n bb,\r\n parentNode,\r\n}) => {\r\n const func = initialProps._id ? uiFunctions[initialProps._id] : undefined\r\n\r\n const parentContext = (parentNode && parentNode.context) || {}\r\n\r\n let renderedNodes = []\r\n const render = context => {\r\n let componentContext = parentContext\r\n if (context) {\r\n componentContext = { ...componentContext }\r\n componentContext.$parent = parentContext\r\n }\r\n\r\n const thisNode = createTreeNode()\r\n thisNode.context = componentContext\r\n thisNode.parentNode = parentNode\r\n thisNode.props = props\r\n\r\n parentNode.children.push(thisNode)\r\n renderedNodes.push(thisNode)\r\n\r\n initialProps._bb = bb(thisNode, props)\r\n\r\n thisNode.component = new componentConstructor({\r\n target: htmlElement,\r\n props: initialProps,\r\n hydrate: false,\r\n anchor,\r\n })\r\n\r\n thisNode.rootElement = htmlElement.children[htmlElement.children.length - 1]\r\n\r\n if (initialProps._id && thisNode.rootElement) {\r\n thisNode.rootElement.classList.add(`pos-${initialProps._id}`)\r\n }\r\n }\r\n\r\n if (func) {\r\n func(render, parentContext)\r\n } else {\r\n render()\r\n }\r\n\r\n return renderedNodes\r\n}\r\n\r\nexport const createTreeNode = () => ({\r\n context: {},\r\n props: {},\r\n rootElement: null,\r\n parentNode: null,\r\n children: [],\r\n component: null,\r\n unsubscribe: () => {},\r\n get destroy() {\r\n const node = this\r\n return () => {\r\n if (node.unsubscribe) node.unsubscribe()\r\n if (node.component && node.component.$destroy) node.component.$destroy()\r\n if (node.children) {\r\n for (let child of node.children) {\r\n child.destroy()\r\n }\r\n }\r\n }\r\n },\r\n})\r\n",
"import { screenSlotComponent } from \"./screenSlotComponent\"\r\n\r\nexport const builtinLibName = \"##builtin\"\r\n\r\nexport const isScreenSlot = componentName =>\r\n componentName === \"##builtin/screenslot\"\r\n\r\nexport const builtins = window => ({\r\n screenslot: screenSlotComponent(window),\r\n})\r\n",
"import { setupBinding } from \"../state/stateBinding\"\r\nimport { split, last } from \"lodash/fp\"\r\nimport { $ } from \"../core/common\"\r\nimport { renderComponent } from \"./renderComponent\"\r\nimport { isScreenSlot } from \"./builtinComponents\"\r\n\r\nexport const attachChildren = initialiseOpts => (htmlElement, options) => {\r\n const {\r\n uiFunctions,\r\n bb,\r\n coreApi,\r\n store,\r\n componentLibraries,\r\n treeNode,\r\n frontendDefinition,\r\n onScreenSlotRendered,\r\n } = initialiseOpts\r\n\r\n const anchor = options && options.anchor ? options.anchor : null\r\n const force = options ? options.force : false\r\n const hydrate = options ? options.hydrate : true\r\n\r\n if (!force && treeNode.children.length > 0) return treeNode.children\r\n\r\n for (let childNode of treeNode.children) {\r\n childNode.destroy()\r\n }\r\n\r\n if (hydrate) {\r\n while (htmlElement.firstChild) {\r\n htmlElement.removeChild(htmlElement.firstChild)\r\n }\r\n }\r\n\r\n htmlElement.classList.add(`lay-${treeNode.props._id}`)\r\n\r\n const renderedComponents = []\r\n for (let childProps of treeNode.props._children) {\r\n const { componentName, libName } = splitName(childProps._component)\r\n\r\n if (!componentName || !libName) return\r\n\r\n const { initialProps, bind } = setupBinding(\r\n store,\r\n childProps,\r\n coreApi,\r\n frontendDefinition.appRootPath\r\n )\r\n\r\n const componentConstructor = componentLibraries[libName][componentName]\r\n\r\n const renderedComponentsThisIteration = renderComponent({\r\n props: childProps,\r\n parentNode: treeNode,\r\n componentConstructor,\r\n uiFunctions,\r\n htmlElement,\r\n anchor,\r\n initialProps,\r\n bb,\r\n })\r\n\r\n if (\r\n onScreenSlotRendered &&\r\n isScreenSlot(childProps._component) &&\r\n renderedComponentsThisIteration.length > 0\r\n ) {\r\n // assuming there is only ever one screen slot\r\n onScreenSlotRendered(renderedComponentsThisIteration[0])\r\n }\r\n\r\n for (let comp of renderedComponentsThisIteration) {\r\n comp.unsubscribe = bind(comp.component)\r\n renderedComponents.push(comp)\r\n }\r\n }\r\n\r\n treeNode.children = renderedComponents\r\n\r\n return renderedComponents\r\n}\r\n\r\nconst splitName = fullname => {\r\n const componentName = $(fullname, [split(\"/\"), last])\r\n\r\n const libName = fullname.substring(\r\n 0,\r\n fullname.length - componentName.length - 1\r\n )\r\n\r\n return { libName, componentName }\r\n}\r\n",
"export default function (str, loose) {\n\tif (str instanceof RegExp) return { keys:false, pattern:str };\n\tvar c, o, tmp, ext, keys=[], pattern='', arr = str.split('/');\n\tarr[0] || arr.shift();\n\n\twhile (tmp = arr.shift()) {\n\t\tc = tmp[0];\n\t\tif (c === '*') {\n\t\t\tkeys.push('wild');\n\t\t\tpattern += '/(.*)';\n\t\t} else if (c === ':') {\n\t\t\to = tmp.indexOf('?', 1);\n\t\t\text = tmp.indexOf('.', 1);\n\t\t\tkeys.push( tmp.substring(1, !!~o ? o : !!~ext ? ext : tmp.length) );\n\t\t\tpattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';\n\t\t\tif (!!~ext) pattern += (!!~o ? '?' : '') + '\\\\' + tmp.substring(ext);\n\t\t} else {\n\t\t\tpattern += '/' + tmp;\n\t\t}\n\t}\n\n\treturn {\n\t\tkeys: keys,\n\t\tpattern: new RegExp('^' + pattern + (loose ? '(?=$|\\/)' : '\\/?$'), 'i')\n\t};\n}\n",
"import regexparam from \"regexparam\"\r\nimport { writable } from \"svelte/store\"\r\n\r\nexport const screenRouter = (screens, onScreenSelected) => {\r\n const routes = screens.map(s => s.route)\r\n let fallback = routes.findIndex(([p]) => p === \"*\")\r\n if (fallback < 0) fallback = 0\r\n\r\n let current\r\n\r\n function route(url) {\r\n const _url = url.state || url\r\n current = routes.findIndex(\r\n p => p !== \"*\" && new RegExp(\"^\" + p + \"$\").test(_url)\r\n )\r\n\r\n const params = {}\r\n\r\n if (current === -1) {\r\n routes.forEach(([p], i) => {\r\n const pm = regexparam(p)\r\n const matches = pm.pattern.exec(_url)\r\n\r\n if (!matches) return\r\n\r\n let j = 0\r\n while (j < pm.keys.length) {\r\n params[pm.keys[j]] = matches[++j] || null\r\n }\r\n\r\n current = i\r\n })\r\n }\r\n\r\n const storeInitial = {}\r\n storeInitial[\"##routeParams\"]\r\n const store = writable(storeInitial)\r\n\r\n if (current !== -1) {\r\n onScreenSelected(screens[current], store, _url)\r\n } else if (fallback) {\r\n onScreenSelected(screens[fallback], store, _url)\r\n }\r\n\r\n !url.state && history.pushState(_url, null, _url)\r\n }\r\n\r\n function click(e) {\r\n const x = e.target.closest(\"a\")\r\n const y = x && x.getAttribute(\"href\")\r\n\r\n if (\r\n e.ctrlKey ||\r\n e.metaKey ||\r\n e.altKey ||\r\n e.shiftKey ||\r\n e.button ||\r\n e.defaultPrevented\r\n )\r\n return\r\n\r\n if (!y || x.target || x.host !== location.host) return\r\n\r\n e.preventDefault()\r\n route(y)\r\n }\r\n\r\n addEventListener(\"popstate\", route)\r\n addEventListener(\"pushstate\", route)\r\n addEventListener(\"click\", click)\r\n\r\n return route\r\n}\r\n",
"import { writable } from \"svelte/store\"\r\nimport { createCoreApi } from \"./core\"\r\nimport { getStateOrValue } from \"./state/getState\"\r\nimport { setState, setStateFromBinding } from \"./state/setState\"\r\nimport { trimSlash } from \"./common/trimSlash\"\r\nimport { isBound } from \"./state/isState\"\r\nimport { attachChildren } from \"./render/attachChildren\"\r\nimport { createTreeNode } from \"./render/renderComponent\"\r\nimport { screenRouter } from \"./render/screenRouter\"\r\n\r\nexport const createApp = (\r\n document,\r\n componentLibraries,\r\n frontendDefinition,\r\n backendDefinition,\r\n user,\r\n uiFunctions\r\n) => {\r\n const coreApi = createCoreApi(backendDefinition, user)\r\n backendDefinition.hierarchy = coreApi.templateApi.constructHierarchy(\r\n backendDefinition.hierarchy\r\n )\r\n const pageStore = writable({\r\n _bbuser: user,\r\n })\r\n\r\n const relativeUrl = url =>\r\n frontendDefinition.appRootPath\r\n ? frontendDefinition.appRootPath + \"/\" + trimSlash(url)\r\n : url\r\n\r\n const apiCall = method => (url, body) =>\r\n fetch(relativeUrl(url), {\r\n method: method,\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n body: body && JSON.stringify(body),\r\n })\r\n\r\n const api = {\r\n post: apiCall(\"POST\"),\r\n get: apiCall(\"GET\"),\r\n patch: apiCall(\"PATCH\"),\r\n delete: apiCall(\"DELETE\"),\r\n }\r\n\r\n const safeCallEvent = (event, context) => {\r\n const isFunction = obj =>\r\n !!(obj && obj.constructor && obj.call && obj.apply)\r\n\r\n if (isFunction(event)) event(context)\r\n }\r\n\r\n let routeTo\r\n let currentScreenStore\r\n let currentScreenUbsubscribe\r\n let currentUrl\r\n\r\n const onScreenSlotRendered = screenSlotNode => {\r\n const onScreenSelected = (screen, store, url) => {\r\n const { getInitialiseParams, unsubscribe } = attachChildrenParams(store)\r\n screenSlotNode.props._children = [screen.props]\r\n const initialiseChildParams = getInitialiseParams(screenSlotNode)\r\n attachChildren(initialiseChildParams)(screenSlotNode.rootElement, {\r\n hydrate: true,\r\n force: true,\r\n })\r\n if (currentScreenUbsubscribe) currentScreenUbsubscribe()\r\n currentScreenUbsubscribe = unsubscribe\r\n currentScreenStore = store\r\n currentUrl = url\r\n }\r\n\r\n routeTo = screenRouter(frontendDefinition.screens, onScreenSelected)\r\n routeTo(currentUrl || window.location.pathname)\r\n }\r\n\r\n const attachChildrenParams = store => {\r\n let currentState = null\r\n const unsubscribe = store.subscribe(s => {\r\n currentState = s\r\n })\r\n\r\n const getInitialiseParams = treeNode => ({\r\n bb: getBbClientApi,\r\n coreApi,\r\n store,\r\n document,\r\n componentLibraries,\r\n frontendDefinition,\r\n uiFunctions,\r\n treeNode,\r\n onScreenSlotRendered,\r\n })\r\n\r\n const getBbClientApi = (treeNode, componentProps) => {\r\n return {\r\n attachChildren: attachChildren(getInitialiseParams(treeNode)),\r\n context: treeNode.context,\r\n props: componentProps,\r\n call: safeCallEvent,\r\n setStateFromBinding: (binding, value) =>\r\n setStateFromBinding(store, binding, value),\r\n setState: (path, value) => setState(store, path, value),\r\n getStateOrValue: (prop, currentContext) =>\r\n getStateOrValue(currentState, prop, currentContext),\r\n store,\r\n relativeUrl,\r\n api,\r\n isBound,\r\n parent,\r\n }\r\n }\r\n return { getInitialiseParams, unsubscribe }\r\n }\r\n\r\n let rootTreeNode\r\n\r\n const initialisePage = (page, target, urlPath) => {\r\n currentUrl = urlPath\r\n\r\n rootTreeNode = createTreeNode()\r\n rootTreeNode.props = {\r\n _children: [page.props],\r\n }\r\n rootTreeNode.rootElement = target\r\n const { getInitialiseParams } = attachChildrenParams(pageStore)\r\n co
"<script>\r\n export let className = \"\"\r\n export let onLoad\r\n export let type\r\n export let _bb\r\n\r\n let containerElement\r\n let hasLoaded;\r\n let currentChildren;\r\n\r\n $: {\r\n if(containerElement) {\r\n _bb.attachChildren(containerElement)\r\n if (!hasLoaded) {\r\n _bb.call(onLoad)\r\n hasLoaded = true\r\n }\r\n }\r\n }\r\n\r\n</script>\r\n\r\n{#if type === \"div\"}\r\n<div class={className} bind:this={containerElement} />\r\n{:else if type === \"header\"}\r\n<header class={className} bind:this={containerElement} />\r\n{:else if type === \"main\"}\r\n<main class={className} bind:this={containerElement} />\r\n{:else if type === \"footer\"}\r\n<footer class={className} bind:this={containerElement} />\r\n{:else if type === \"aside\"}\r\n<aside class={className} bind:this={containerElement} />\r\n{:else if type === \"summary\"}\r\n<summary class={className} bind:this={containerElement} />\r\n{:else if type === \"details\"}\r\n<details class={className} bind:this={containerElement} />\r\n{:else if type === \"article\"}\r\n<article class={className} bind:this={containerElement} />\r\n{:else if type === \"nav\"}\r\n<nav class={className} bind:this={containerElement} />\r\n{:else if type === \"mark\"}\r\n<mark class={className} bind:this={containerElement} />\r\n{:else if type === \"figure\"}\r\n<figure class={className} bind:this={containerElement} />\r\n{:else if type === \"figcaption\"}\r\n<figcaption class={className} bind:this={containerElement} />\r\n{:else if type === \"paragraph\"}\r\n<p class={className} bind:this={containerElement} />\r\n{/if}\r\n",
"export const buildStyle = styles => {\r\n let str = \"\"\r\n for (let s in styles) {\r\n if (styles[s]) {\r\n str += `${s}: ${styles[s]}; `\r\n }\r\n }\r\n return str\r\n}\r\n",
"<script>\r\n import { buildStyle } from \"./buildStyle\"\r\n\r\n export let text = \"\"\r\n export let className = \"\"\r\n\r\n export let formattingTag = \"\"\r\n\r\n export let font = \"\"\r\n export let textAlign = \"\"\r\n export let verticalAlign = \"\"\r\n export let color = \"\"\r\n\r\n export let _bb\r\n\r\n let style = \"\"\r\n\r\n const isTag = tag => (formattingTag || \"\").indexOf(tag) > -1\r\n\r\n $: {\r\n style = buildStyle({\r\n font,\r\n verticalAlign,\r\n color,\r\n \"text-align\": textAlign,\r\n \"vertical-align\": verticalAlign,\r\n })\r\n }\r\n</script>\r\n\r\n{#if isTag(\"none\")}\r\n{text}\r\n{:else if isTag(\"<b>\")}\r\n<b class={className} {style}>{text}</b>\r\n{:else if isTag(\"<strong>\")}\r\n<strong class={className} {style}>{text}</strong>\r\n{:else if isTag(\"<i>\")}\r\n<i class={className} {style}>{text}</i>\r\n{:else if isTag(\"<em>\")}\r\n<em class={className} {style}>{text}</em>\r\n{:else if isTag(\"<mark>\")}\r\n<mark class={className} {style}>{text}</mark>\r\n{:else if isTag(\"<small>\")}\r\n<small class={className} {style}>{text}</small>\r\n{:else if isTag(\"<del>\")}\r\n<del class={className} {style}>{text}</del>\r\n{:else if isTag(\"<ins>\")}\r\n<ins class={className} {style}>{text}</ins>\r\n{:else if isTag(\"<sub>\")}\r\n<sub class={className} {style}>{text}</sub>\r\n{:else if isTag(\"<sup>\")}\r\n<sup class={className} {style}>{text}</sup>\r\n{:else}\r\n{text}\r\n{/if}\r\n\r\n\r\n",
"<script>\r\n export let className = \"\"\r\n export let type\r\n export let _bb\r\n\r\n let containerElement\r\n\r\n $: containerElement && _bb.attachChildren(containerElement)\r\n\r\n</script>\r\n\r\n{#if type === \"h1\"}\r\n<h1 class={className} bind:this={containerElement}></h1>\r\n{:else if type === \"h2\"}\r\n<h2 class={className} bind:this={containerElement}></h2>\r\n{:else if type === \"h3\"}\r\n<h3 class={className} bind:this={containerElement}></h3>\r\n{:else if type === \"h4\"}\r\n<h4 class={className} bind:this={containerElement}></h4>\r\n{:else if type === \"h5\"}\r\n<h5 class={className} bind:this={containerElement}></h5>\r\n{:else if type === \"h6\"}\r\n<h6 class={className} bind:this={containerElement}></h6>\r\n{/if}\r\n",
"<script>\r\n export let value = \"\"\r\n export let className = \"\"\r\n export let type = \"text\"\r\n\r\n export let _bb\r\n\r\n let actualValue = \"\"\r\n\r\n const onchange = ev => {\r\n if (_bb) {\r\n _bb.setStateFromBinding(_bb.props.value, ev.target.value)\r\n }\r\n }\r\n</script>\r\n\r\n<input class={className} {type} {value} on:change={onchange} />\r\n",
"<script>\r\n export let value = \"\"\r\n export let className = \"\"\r\n\r\n export let _bb\r\n\r\n let actualValue = \"\"\r\n let selectElement;\r\n\r\n $: selectElement && _bb.attachChildren(selectElement)\r\n\r\n const onchange = ev => {\r\n if (_bb) {\r\n _bb.setStateFromBinding(_bb.props.value, ev.target.value)\r\n }\r\n }\r\n</script>\r\n\r\n<select class={className} {value} on:change={onchange} bind:this={selectElement}>\r\n\r\n</select>\r\n",
"<script>\r\n export let value = \"\"\r\n export let text = \"\"\r\n export let _bb\r\n\r\n let actualValue\r\n let actualText\r\n\r\n $: actualValue = value || text || \"\"\r\n $: actualText = text || value || \"\"\r\n\r\n</script>\r\n\r\n<option value={actualValue}>{actualText}</option>\r\n",
"// https://github.com/kaisermann/svelte-css-vars\r\n\r\nexport default (node, props) => {\r\n Object.entries(props).forEach(([key, value]) => {\r\n node.style.setProperty(`--${key}`, value)\r\n })\r\n\r\n return {\r\n update(new_props) {\r\n Object.entries(new_props).forEach(([key, value]) => {\r\n node.style.setProperty(`--${key}`, value)\r\n delete props[key]\r\n })\r\n\r\n Object.keys(props).forEach(name => node.style.removeProperty(`--${name}`))\r\n props = new_props\r\n },\r\n }\r\n}\r\n",
"<script>\r\n import cssVars from \"./cssVars\"\r\n import { buildStyle } from \"./buildStyle\"\r\n export let className = \"default\"\r\n export let disabled = false\r\n export let contentText\r\n export let onClick\r\n export let background\r\n export let color\r\n export let border\r\n export let padding\r\n export let hoverColor\r\n export let hoverBackground\r\n export let hoverBorder\r\n\r\n export let _bb\r\n let theButton\r\n let cssVariables\r\n let buttonStyles\r\n\r\n let customHoverColorClass\r\n let customHoverBorderClass\r\n let customHoverBackClass\r\n\r\n let customClasses = \"\"\r\n\r\n const createClasses = classes => {\r\n let all = \"\"\r\n for (let cls in classes) {\r\n if (classes[cls]) {\r\n all = all + \" \" + cls\r\n }\r\n }\r\n return all\r\n }\r\n\r\n $: if(_bb.props._children.length > 0) theButton && _bb.attachChildren(theButton)\r\n\r\n $: {\r\n cssVariables = {\r\n hoverColor,\r\n hoverBorder,\r\n hoverBackground,\r\n background,\r\n color,\r\n border,\r\n }\r\n\r\n buttonStyles = buildStyle({\r\n padding,\r\n })\r\n\r\n customClasses = createClasses({\r\n hoverColor,\r\n hoverBorder,\r\n hoverBackground,\r\n background,\r\n border,\r\n color,\r\n })\r\n }\r\n\r\n const clickHandler = () => {\r\n _bb.call(onClick)\r\n }\r\n</script>\r\n\r\n<button\r\n bind:this={theButton}\r\n use:cssVars={cssVariables}\r\n class=\"{className}\r\n {customClasses}\"\r\n disabled={disabled || false}\r\n on:click={clickHandler}\r\n style={buttonStyles}>\r\n {#if _bb.props_children.length === 0}{contentText}{/if}\r\n</button>\r\n\r\n<style>\r\n .default {\r\n font-family: inherit;\r\n font-size: inherit;\r\n padding: 0.4em;\r\n margin: 0 0 0.5em 0;\r\n box-sizing: border-box;\r\n border: 1px solid #ccc;\r\n border-radius: 2px;\r\n color: #333;\r\n background-color: #f4f4f4;\r\n outline: none;\r\n }\r\n\r\n .default:active {\r\n background-color: #ddd;\r\n }\r\n\r\n .default:focus {\r\n border-color: #666;\r\n }\r\n\r\n .border {\r\n border: var(--border);\r\n }\r\n\r\n .color {\r\n color: var(--color);\r\n }\r\n\r\n .background {\r\n background: var(--background);\r\n }\r\n\r\n .hoverBorder:hover {\r\n border: var(--hoverBorder);\r\n }\r\n\r\n .hoverColor:hover {\r\n color: var(--hoverColor);\r\n }\r\n\r\n .hoverBack:hover {\r\n background: var(--hoverBackground);\r\n }\r\n</style>\r\n",
"<script>\r\n import Button from \"./Button.svelte\"\r\n\r\n export let usernameLabel = \"Username\"\r\n export let passwordLabel = \"Password\"\r\n export let loginButtonLabel = \"Login\"\r\n export let loginRedirect = \"\"\r\n export let logo = \"\"\r\n export let buttonClass = \"\"\r\n export let inputClass = \"\"\r\n\r\n export let _bb\r\n\r\n let username = \"\"\r\n let password = \"\"\r\n let busy = false\r\n let incorrect = false\r\n let _logo = \"\"\r\n let _buttonClass = \"\"\r\n let _inputClass = \"\"\r\n\r\n $: {\r\n _logo = _bb.relativeUrl(logo)\r\n _buttonClass = buttonClass || \"default-button\"\r\n _inputClass = inputClass || \"default-input\"\r\n }\r\n\r\n const login = () => {\r\n busy = true\r\n _bb.api\r\n .post(\"/api/authenticate\", { username, password })\r\n .then(r => {\r\n busy = false\r\n if (r.status === 200) {\r\n return r.json()\r\n } else {\r\n incorrect = true\r\n return\r\n }\r\n })\r\n .then(user => {\r\n if (user) {\r\n localStorage.setItem(\"budibase:user\", JSON.stringify(user))\r\n location.reload()\r\n }\r\n })\r\n }\r\n</script>\r\n\r\n<div class=\"root\">\r\n\r\n <div class=\"content\">\r\n\r\n {#if _logo}\r\n <div class=\"logo-container\">\r\n <img src={_logo} alt=\"logo\" />\r\n </div>\r\n {/if}\r\n\r\n <div class=\"form-root\">\r\n <div class=\"label\">{usernameLabel}</div>\r\n <div class=\"control\">\r\n <input bind:value={username} type=\"text\" class={_inputClass} />\r\n </div>\r\n <div class=\"label\">{passwordLabel}</div>\r\n <div class=\"control\">\r\n <input bind:value={password} type=\"password\" class={_inputClass} />\r\n </div>\r\n </div>\r\n\r\n <div class=\"login-button-container\">\r\n <button disabled={busy} on:click={login} class={_buttonClass}>\r\n {loginButtonLabel}\r\n </button>\r\n </div>\r\n\r\n {#if incorrect}\r\n <div class=\"incorrect-details-panel\">Incorrect username or password</div>\r\n {/if}\r\n\r\n </div>\r\n\r\n</div>\r\n\r\n<style>\r\n .root {\r\n height: 100%;\r\n display: grid;\r\n grid-template-columns: [left] 1fr [middle] auto [right] 1fr;\r\n grid-template-rows: [top] 1fr [center] auto [bottom] 1fr;\r\n }\r\n\r\n .content {\r\n grid-column-start: middle;\r\n grid-row-start: center;\r\n width: 400px;\r\n }\r\n\r\n .logo-container {\r\n margin-bottom: 20px;\r\n }\r\n\r\n .logo-container > img {\r\n max-width: 100%;\r\n }\r\n\r\n .login-button-container {\r\n text-align: right;\r\n margin-top: 20px;\r\n }\r\n\r\n .incorrect-details-panel {\r\n margin-top: 30px;\r\n padding: 10px;\r\n border-style: solid;\r\n border-width: 1px;\r\n border-color: maroon;\r\n border-radius: 1px;\r\n text-align: center;\r\n color: maroon;\r\n background-color: mistyrose;\r\n }\r\n\r\n .form-root {\r\n display: grid;\r\n grid-template-columns: [label] auto [control] 1fr; /* [overflow] auto;*/\r\n }\r\n\r\n .label {\r\n grid-column-start: label;\r\n padding: 5px 10px;\r\n vertical-align: middle;\r\n }\r\n .control {\r\n grid-column-start: control;\r\n padding: 5px 10px;\r\n }\r\n\r\n .default-input {\r\n font-family: inherit;\r\n font-size: inherit;\r\n padding: 0.4em;\r\n margin: 0 0 0.5em 0;\r\n box-sizing: border-box;\r\n border: 1px solid #ccc;\r\n border-radius: 2px;\r\n width: 100%;\r\n }\r\n\r\n .default-button {\r\n font-family: inherit;\r\n font-size: inherit;\r\n padding: 0.4em;\r\n margin: 0 0 0.5em 0;\r\n box-sizing: border-box;\r\n border: 1px solid #ccc;\r\n border-radius: 2px;\r\n color: #333;\r\n background-color: #f4f4f4;\r\n outline: none;\r\n }\r\n\r\n .default-button:active {\r\n background-color: #ddd;\r\n }\r\n\r\n .default-button:focus {\r\n border-color: #666;\r\n }\r\n</style>\r\n",
"<script>\r\n import cssVars from \"./cssVars\"\r\n\r\n export let navBarBackground = \"\"\r\n export let navBarBorder = \"\"\r\n export let navBarColor = \"\"\r\n export let selectedItemBackground = \"\"\r\n export let selectedItemColor = \"\"\r\n export let selectedItemBorder = \"\"\r\n export let itemHoverBackground = \"\"\r\n export let itemHoverColor = \"\"\r\n export let hideNavBar = false\r\n export let selectedItem = \"\"\r\n\r\n export let _children\r\n export let _bb\r\n\r\n let selectedIndex = -1\r\n let styleVars = {}\r\n let components = {}\r\n let componentElements = {}\r\n\r\n const hasComponentElements = () =>\r\n Object.getOwnPropertyNames(componentElements).length > 0\r\n\r\n $: {\r\n styleVars = {\r\n navBarBackground,\r\n navBarBorder,\r\n navBarColor,\r\n selectedItemBackground,\r\n selectedItemColor,\r\n selectedItemBorder,\r\n itemHoverBackground,\r\n itemHoverColor,\r\n }\r\n\r\n if (_children && _children.length > 0 && hasComponentElements()) {\r\n const currentSelectedItem =\r\n selectedIndex > 0 ? _children[selectedIndex].title : \"\"\r\n if (selectedItem && currentSelectedItem !== selectedItem) {\r\n let i = 0\r\n for (let child of _children) {\r\n if (child.title === selectedItem) {\r\n onSelectItem(i)()\r\n }\r\n i++\r\n }\r\n } else if (!currentSelectedItem) {\r\n onSelectItem(0)\r\n }\r\n }\r\n }\r\n\r\n const onSelectItem = index => () => {\r\n selectedIndex = index\r\n if (!components[index]) {\r\n const comp = _bb.attachChildren(\r\n componentElements[index]\r\n )\r\n components[index] = comp\r\n }\r\n }\r\n</script>\r\n\r\n<div class=\"root\" use:cssVars={styleVars}>\r\n {#if !hideNavBar}\r\n <div class=\"navbar\">\r\n {#each _children as navItem, index}\r\n <div\r\n class=\"navitem\"\r\n on:click={onSelectItem(index)}\r\n class:selected={selectedIndex === index}>\r\n {navItem.title}\r\n </div>\r\n {/each}\r\n </div>\r\n {/if}\r\n {#each _children as navItem, index}\r\n <div class=\"content\" bind:this={componentElements[index]} />\r\n {/each}\r\n</div>\r\n\r\n<style>\r\n .root {\r\n height: 100%;\r\n width: 100%;\r\n grid-template-columns: [navbar] auto [content] 1fr;\r\n display: grid;\r\n }\r\n\r\n .navbar {\r\n grid-column: navbar;\r\n background: var(--navBarBackground);\r\n border: var(--navBarBorder);\r\n color: var(--navBarColor);\r\n }\r\n\r\n .navitem {\r\n padding: 10px 17px;\r\n cursor: pointer;\r\n }\r\n\r\n .navitem:hover {\r\n background: var(--itemHoverBackground);\r\n color: var(--itemHoverColor);\r\n }\r\n\r\n .navitem.selected {\r\n background: var(--selectedItemBackground);\r\n border: var(--selectedItemBorder);\r\n color: var(--selectedItemColor);\r\n }\r\n\r\n .content {\r\n grid-column: content;\r\n }\r\n</style>\r\n",
"<script>\r\n export let columns = []\r\n export let data = \"\"\r\n export let tableClass = \"\"\r\n export let theadClass = \"\"\r\n export let tbodyClass = \"\"\r\n export let trClass = \"\"\r\n export let thClass = \"\"\r\n export let onRowClick\r\n\r\n export let _bb\r\n\r\n const rowClickHandler = row => () => {\r\n _bb.call(onRowClick, row)\r\n }\r\n\r\n const cellValue = (colIndex, row) => {\r\n const val = _bb.getStateOrValue(_bb.props.columns[colIndex].value, row)\r\n return val\r\n }\r\n</script>\r\n\r\n<table class={tableClass}>\r\n <thead class={theadClass}>\r\n <tr class={trClass}>\r\n {#each columns as col}\r\n <th class={thClass}>{col.title}</th>\r\n {/each}\r\n </tr>\r\n </thead>\r\n <tbody class={tbodyClass}>\r\n {#if data}\r\n {#each data as row}\r\n <tr class={trClass} on:click={rowClickHandler(row)}>\r\n {#each columns as col, index}\r\n <th class={thClass}>{cellValue(index, row)}</th>\r\n {/each}\r\n </tr>\r\n {/each}\r\n {/if}\r\n </tbody>\r\n</table>\r\n\r\n<style>\r\n .table-default {\r\n width: 100%;\r\n margin-bottom: 1rem;\r\n color: #212529;\r\n border-collapse: collapse;\r\n }\r\n\r\n .table-default .thead-default .th-default {\r\n vertical-align: bottom;\r\n border-bottom: 2px solid #dee2e6;\r\n font-weight: bold;\r\n }\r\n\r\n .table-default .th-default {\r\n padding: 0.75rem;\r\n vertical-align: top;\r\n border-top: 1px solid #dee2e6;\r\n font-weight: normal;\r\n }\r\n\r\n .th-default {\r\n text-align: inherit;\r\n }\r\n\r\n .table-default .tbody-default .tr-default:hover {\r\n color: #212529;\r\n background-color: rgba(0, 0, 0, 0.075);\r\n cursor: pointer;\r\n }\r\n</style>\r\n",
"import { container, text, heading, input, select, option, button, login, nav, table } from \"../index\"\r\n\r\nexport default { container, text, heading, input, select, option, button, login, nav, table }\r\n",
"export const rootComponent = window => {\r\n return function(opts) {\r\n const node = window.document.createElement(\"DIV\")\r\n const $set = props => {\r\n props._bb.attachChildren(node)\r\n }\r\n const $destroy = () => {\r\n if (opts.target && node) opts.target.removeChild(node)\r\n }\r\n this.$set = $set\r\n this.$set(opts.props)\r\n this.$destroy = $destroy\r\n opts.target.appendChild(node)\r\n }\r\n}\r\n",
"import { createApp } from \"@budibase/client/src/createApp\"\r\nimport components from \"./testComponents\"\r\nimport packageJson from \"../../package.json\"\r\nimport { rootComponent } from \"./rootComponent\"\r\n\r\nexport default async () => {\r\n delete components._lib\r\n const componentLibraries = {}\r\n componentLibraries[packageJson.name] = components\r\n componentLibraries[\"testcomponents\"] = {\r\n rootComponent: rootComponent(window),\r\n }\r\n const appDef = { hierarchy: {}, actions: {} }\r\n const user = { name: \"yeo\", permissions: [] }\r\n const { initialisePage } = createApp(\r\n window.document,\r\n componentLibraries,\r\n { appRootPath: \"\" },\r\n appDef,\r\n user,\r\n {},\r\n []\r\n )\r\n return initialisePage\r\n}\r\n",
"export const form = {\r\n _id: \"1\",\r\n _component: \"@budibase/standard-components/container\",\r\n type: \"main\",\r\n _children: [\r\n {\r\n _component: \"@budibase/standard-components/heading\",\r\n type: \"h1\",\r\n _children: [\r\n {\r\n _component: \"@budibase/standard-components/text\",\r\n text: \"This is an H1 Heading\",\r\n },\r\n ],\r\n },\r\n {\r\n _component: \"@budibase/standard-components/text\",\r\n text: \"This just some text\",\r\n type: \"strong\",\r\n },\r\n {\r\n _component: \"@budibase/standard-components/container\",\r\n type: \"paragraph\",\r\n _children: [\r\n {\r\n _component: \"@budibase/standard-components/text\",\r\n formattingTag: \"<i>\",\r\n text: \"some iatlics in a paragraph\",\r\n },\r\n ],\r\n },\r\n {\r\n _component: \"@budibase/standard-components/heading\",\r\n type: \"h2\",\r\n _children: [\r\n {\r\n _component: \"@budibase/standard-components/text\",\r\n text: \"This is an H2 Heading\",\r\n },\r\n ],\r\n },\r\n {\r\n _component: \"@budibase/standard-components/select\",\r\n value: \"two\",\r\n _children: [\r\n {\r\n _component: \"@budibase/standard-components/option\",\r\n text: \"number 1\",\r\n value: \"one\",\r\n },\r\n {\r\n _component: \"@budibase/standard-components/option\",\r\n text: \"number 2\",\r\n value: \"two\",\r\n },\r\n ],\r\n },\r\n ],\r\n}\r\n",
"<script>\r\n import createApp from \"./createApp\"\r\n import { form } from \"./props\"\r\n let _bb\r\n let currentComponent\r\n let _appPromise\r\n\r\nconst autoAssignIds = (props, count = 0) => {\r\n if (!props._id) {\r\n props._id = `auto_id_${count}`\r\n }\r\n if (props._children) {\r\n for (let child of props._children) {\r\n count += 1\r\n autoAssignIds(child, count)\r\n }\r\n }\r\n}\r\n\r\n $: {\r\n if (currentComponent) {\r\n const _appPromise = createApp()\r\n const page = {\r\n props: form,\r\n }\r\n\r\n autoAssignIds(page.props)\r\n\r\n _appPromise.then(initialise => {\r\n initialise(page, currentComponent, \"\")\r\n })\r\n }\r\n }\r\n</script>\r\n\r\n{#await _appPromise}\r\n loading\r\n{:then _bb}\r\n <div id=\"current_component\" bind:this={currentComponent} />\r\n{/await}\r\n\r\n<style>\r\n #current_component {\r\n height: 100%;\r\n width: 100%;\r\n }\r\n</style>\r\n",
"import App from \"./TestApp.svelte\"\r\n\r\nconst app = new App({\r\n target: document.body,\r\n})\r\n\r\nexport default app\r\n"
],
"names": [
"global",
"this",
"fallbackHolder",
"mapping",
"require$$0",
"require$$1",
"setSeed",
"random",
"alphabet",
"generate",
"build",
"undefined",
"union",
"reduce",
"isUndefined",
"cloneDeep",
"require",
"flow",
"trim",
"split",
"replace",
"isArray",
"filter",
"isNull",
"join",
"isNaN",
"some",
"isEmpty",
"isString",
"constant",
"head",
"tail",
"includes",
"isInteger",
"isDate",
"toNumber",
"get",
"globals",
"countBy",
"keys",
"find",
"has",
"merge",
"mapValues",
"makerule",
"isBoolean",
"options",
"typeConstraints",
"isNumber",
"map",
"isObjectLike",
"intersection",
"last",
"assign",
"all",
"values",
"keyBy",
"each",
"isObject",
"actualValue",
"container",
"text",
"heading",
"input",
"select",
"option",
"button",
"login",
"nav",
"table",
"createApp",
"App"
],
"mappings": ";;;;;;;IAAA,SAAS,IAAI,GAAG,GAAG;AACnB,IACA,SAAS,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE;IAC1B;IACA,IAAI,KAAK,MAAM,CAAC,IAAI,GAAG;IACvB,QAAQ,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;IACxB,IAAI,OAAO,GAAG,CAAC;IACf,CAAC;IACD,SAAS,UAAU,CAAC,KAAK,EAAE;IAC3B,IAAI,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,UAAU,CAAC;IAClF,CAAC;IACD,SAAS,YAAY,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE;IACzD,IAAI,OAAO,CAAC,aAAa,GAAG;IAC5B,QAAQ,GAAG,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE;IACzC,KAAK,CAAC;IACN,CAAC;IACD,SAAS,GAAG,CAAC,EAAE,EAAE;IACjB,IAAI,OAAO,EAAE,EAAE,CAAC;IAChB,CAAC;IACD,SAAS,YAAY,GAAG;IACxB,IAAI,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IACD,SAAS,OAAO,CAAC,GAAG,EAAE;IACtB,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;IACD,SAAS,WAAW,CAAC,KAAK,EAAE;IAC5B,IAAI,OAAO,OAAO,KAAK,KAAK,UAAU,CAAC;IACvC,CAAC;IACD,SAAS,cAAc,CAAC,CAAC,EAAE,CAAC,EAAE;IAC9B,IAAI,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC,CAAC;IAClG,CAAC;AACD,IAoDA,SAAS,aAAa,CAAC,KAAK,EAAE;IAC9B,IAAI,OAAO,KAAK,IAAI,IAAI,GAAG,EAAE,GAAG,KAAK,CAAC;IACtC,CAAC;AACD,AAmDA;IACA,SAAS,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE;IAC9B,IAAI,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC;IACD,SAAS,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE;IACtC,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,IAAI,IAAI,CAAC,CAAC;IAC9C,CAAC;IACD,SAAS,MAAM,CAAC,IAAI,EAAE;IACtB,IAAI,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;IACtC,CAAC;IACD,SAAS,YAAY,CAAC,UAAU,EAAE,SAAS,EAAE;IAC7C,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;IACnD,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC;IACzB,YAAY,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;IACvC,KAAK;IACL,CAAC;IACD,SAAS,OAAO,CAAC,IAAI,EAAE;IACvB,IAAI,OAAO,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IACxC,CAAC;AACD,IAgBA,SAAS,WAAW,CAAC,IAAI,EAAE;IAC3B,IAAI,OAAO,QAAQ,CAAC,eAAe,CAAC,4BAA4B,EAAE,IAAI,CAAC,CAAC;IACxE,CAAC;IACD,SAAS,IAAI,CAAC,IAAI,EAAE;IACpB,IAAI,OAAO,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IACD,SAAS,KAAK,GAAG;IACjB,IAAI,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;IACD,SAAS,KAAK,GAAG;IACjB,IAAI,OAAO,IAAI,CAAC,EAAE,CAAC,CAAC;IACpB,CAAC;IACD,SAAS,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE;IAC/C,IAAI,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACnD,IAAI,OAAO,MAAM,IAAI,CAAC,mBAAmB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACnE,CAAC;AACD,IAqBA,SAAS,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;IACtC,IAAI,IAAI,KAAK,IAAI,IAAI;IACrB,QAAQ,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,CAAC;IACxC;IACA,QAAQ,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;AACD,IA+CA,SAAS,QAAQ,CAAC,OAAO,EAAE;IAC3B,IAAI,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAC1C,CAAC;IACD,SAAS,aAAa,CAAC,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE;IACrD,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;IAC9C,QAAQ,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9B,QAAQ,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI,EAAE;IACpC,YAAY,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;IAChE,gBAAgB,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACrD,gBAAgB,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,IAAI,CAAC;IAC/C,oBAAoB,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACzD,aAAa;IACb,YAAY,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACzC,SAAS;IACT,KAAK;IACL,IAAI,OAAO,GAAG,GAAG,WAAW,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnD,CAAC;IACD,SAAS,UAAU,CAAC,KAAK,EAAE,IAAI,EAAE;IACjC,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;IAC9C,QAAQ,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9B,QAAQ,IAAI,IAAI,CAAC,QAAQ,KAAK,CAAC,EAAE;IACjC,YAAY,IAAI,CAAC,IAAI,GAAG,EAAE,GAAG,IAAI,CAAC;IAClC,YAAY,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACzC,SAAS;IACT,KAAK;IACL,IAAI,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC;IACtB,CAAC;IACD,SAAS,WAAW,CAAC,KAAK,EAAE;IAC5B,IAAI,OAAO,UAAU,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IAClC,CAAC;AACD,IAKA,SAAS,eAAe,CAAC,KAAK,EAAE,KAAK,EAAE;IACvC,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,CAAC,KAAK,EAAE;IACtC,QAAQ,KAAK,CAAC,KAAK,GAAG,KAAK,
}