/*!

Squarespace node server.

- Cache conventions
- block-*.html
- query-*.json
- page-*.json
- page-*.html
- api-*.json
516315
function ( appRequest, appResponse ) {
    var data = {
        email: appRequest.body.email,
        password: appRequest.body.password
    };

    if ( !data.email || !data.password ) {
        appResponse.send( loginHTML );

        return;
    }

    appLogin( data, appResponse, function () {
        // End login post
        appResponse.json({
            success: true
        });
    });
}
872412
function browserSpecific() {
    var data = '';
    return through(
        function(buf) {
            data += buf;
        },
        function() {
            this.queue(data.replace(/\.\/node\//g, './browser/'));
            this.queue(null);
        }
    );
}
130165
function wxappEntry() {

  const regex = /src\/pages\/([^\/]+)\/[^\.]+.js/;
  
  return {
    entry: () => {

      let pages = {}
      let core = []

      glob.sync(`./src/pages/**/*.js`).forEach(x => {
        const name = x.match(regex)[1]
        const key = `pages/${name}/${name}`
        pages[key] = x
      })

      return Object.assign({}, pages, {
        app: [
          //'webpack-dev-server/client',
          //'webpack/hot/only-dev-server',
          './src/app.js'
        ]
      })
    }
  }
}
11763
function spaces(node) {
            const tokens = getTokens(node);
            const countSpace = countSpaces(tokens);

            if (rule.before) {

                // should be space(s) before arrow
                if (countSpace.before === 0) {
                    context.report({
                        node: tokens.before,
                        messageId: "expectedBefore",
                        fix(fixer) {
                            return fixer.insertTextBefore(tokens.arrow, " ");
                        }
                    });
                }
            } else {

                // should be no space before arrow
                if (countSpace.before > 0) {
                    context.report({
                        node: tokens.before,
                        messageId: "unexpectedBefore",
                        fix(fixer) {
                            return fixer.removeRange([tokens.before.range[1], tokens.arrow.range[0]]);
                        }
                    });
                }
            }

            if (rule.after) {

                // should be space(s) after arrow
                if (countSpace.after === 0) {
                    context.report({
                        node: tokens.after,
                        messageId: "expectedAfter",
                        fix(fixer) {
                            return fixer.insertTextAfter(tokens.arrow, " ");
                        }
                    });
                }
            } else {

                // should be no space after arrow
                if (countSpace.after > 0) {
                    context.report({
                        node: tokens.after,
                        messageId: "unexpectedAfter",
                        fix(fixer) {
                            return fixer.removeRange([tokens.arrow.range[1], tokens.after.range[0]]);
                        }
                    });
                }
            }
        }
132197
function _request_creator(mod_opts) {
	mod_opts = mod_opts || {};

	var _path = mod_opts.path || '';
	var _id = 0;
	var _cache = {};

	/** */
	function _cache_has_id(id) {
		return Object.prototype.hasOwnProperty.call(_cache, id) ? true : false;
	}

	/** */
	function _cache_cleanup(id) {
		if(_cache_has_id(id)) {
			delete _cache[id];
		}
	}
	
	/** HTTP request runner */
	function request_handler(req, res) {
		var server_start_time = get_time();
		var cache, url, id;
		
		url = require('url').parse(req.url, true);
		
		if(url.pathname === _path + '/time') {
			_id = Math.floor(Math.random()*100000000000000000);
			cache = {'id':_id, 'start': server_start_time, 'end':undefined};
			_cache[_id] = cache;
			
			req.on('close', _cache_cleanup.bind(undefined, _id) );
			
			req.on('end', function() {
				cache.status = true;
				cache.end = get_time();
			});
			
			setTimeout(_cache_cleanup.bind(undefined, _id), 1000*30);
		
			res.writeHead(200, {'Content-Type': 'application/json'});
			res.end(JSON.stringify(_id));
		} else if(url.pathname.substr(0, _path.length + 6) === _path + '/fetch') {
			id = parseInt(url.query.id, 10);
			if(_cache_has_id(id)) {
				res.writeHead(200, {'Content-Type': 'application/json'});
	
				res.end(JSON.stringify(_cache[id]));
				_cache_cleanup(id);
			} else {
				res.writeHead(404, {'Content-Type': 'application/json'});
				res.end(JSON.stringify("404 - Not Found"));
			}
		} else {
			res.writeHead(404, {'Content-Type': 'application/json'});
			res.end(JSON.stringify("404 - Not Found"));
		}
	}

	return request_handler;
}
489606
function precacheNode(inst, node) {
  var hostInst = getRenderedHostOrTextFromComponent(inst);
  hostInst._hostNode = node;
  node[internalInstanceKey] = hostInst;
}
991812
function plainHTMLBlocks() {

    const plainBlocks = ['code-example', 'code-tabs'];

    // Create matchers for each block
    const anyBlockMatcher = new RegExp('^' + createOpenMatcher(`(${plainBlocks.join('|')})`));

    const Parser = this.Parser;
    const blockTokenizers = Parser.prototype.blockTokenizers;
    const blockMethods = Parser.prototype.blockMethods;

    blockTokenizers.plainHTMLBlocks = tokenizePlainHTMLBlocks;
    blockMethods.splice(blockMethods.indexOf('html'), 0, 'plainHTMLBlocks');

    function tokenizePlainHTMLBlocks(eat, value, silent) {
      const openMatch = anyBlockMatcher.exec(value);
      if (openMatch) {
        const blockName = openMatch[1];
        try {
          const fullMatch = matchRecursiveRegExp(value, createOpenMatcher(blockName), createCloseMatcher(blockName))[0];
          if (silent || !fullMatch) {
            // either we are not eating (silent) or the match failed
            return !!fullMatch;
          }
          return eat(fullMatch[0])({
            type: 'html',
            value: fullMatch[0]
          });
        } catch(e) {
          this.file.fail('Unmatched plain HTML block tag ' + e.message);
        }
      }
    }
  }
1239164
function ( json ) {
    pageNotFoundJson = sqsUtil.copy( json );
    pageNotFoundJson.collection = {};
    pageNotFoundJson.error = true;
}
1308016
function lastNoneSpaceChild( block )
	{
		var lastIndex = block.children.length,
			last = block.children[ lastIndex - 1 ];
		while (  last && last.type == CKEDITOR.NODE_TEXT && !CKEDITOR.tools.trim( last.value ) )
			last = block.children[ --lastIndex ];
		return last;
	}
1062657
function () {
      var query = url.parse(page);
      var presenter = piccolo.build.router.parse(query.pathname);

      var state = {
        'resolved': presenter,
        'namespace': 'piccolo',
        'query': query
      };

      callback(state);
    }
94452
function (req, res) {
        if (!req.body.space || !server.spaces[req.body.space]) {
            log.error('Invalid Space', 'request:', JSON.stringify(req.body));
            Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid space' }));
            return;
        } else if (req.body.w === undefined || req.body.h === undefined || req.body.x === undefined || req.body.y === undefined) {
            // specifically testing for undefined since '0' is a valid input.
            log.error('Invalid Dimensions', 'request:', JSON.stringify(req.body));
            Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid dimensions' }));
            return;
        } else if (req.body.app && !req.body.app.url) {
            log.error('Invalid App Configuration', 'request:', JSON.stringify(req.body.app));
            Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid app configuration' }));
            return;
        }
        let section = { w: req.body.w, h: req.body.h, x: req.body.x, y: req.body.y, spaces: {} };
        section.spaces[req.body.space] = _calculateSectionLayout(req.body.space, {
            x: req.body.x, y: req.body.y, w: req.body.w, h: req.body.h
        });
        log.debug('Generated spaces configuration for new section');

        // Deploy an App into a section
        let sectionId = server.state.get('sections').length;
        if (req.body.app) {
            const url = req.body.app.url.replace(/\/$/, '');
            section.app = { 'url': url };
            log.debug('Got URL for app:', url);
            if (req.body.app.states) {
                /* istanbul ignore else */
                // DEBUG logging is turned on by default, and only turned off in production deployments.
                // The operation of the Constants.Logging.DEBUG flag has been tested elsewhere.
                if (Constants.Logging.DEBUG) {
                    log.debug('Got state configuration for app:', JSON.stringify(req.body.app.states));
                }
                // Cache or load states if they were provided as a part of the create request.
                if (req.body.app.states.cache) {
                    Object.keys(req.body.app.states.cache).forEach(function (name) {
                        log.debug('Caching new named state for future use:', name);
                        request.post(section.app.url + '/states/' + name, {
                            headers: { 'Content-Type': Constants.HTTP_CONTENT_TYPE_JSON },
                            json: req.body.app.states.cache[name]
                        }, _handleRequestError);
                    });
                }
                if (req.body.app.states.load) {
                    // Either a named state or an in-line state configuration can be loaded.
                    if (typeof req.body.app.states.load === 'string' || req.body.app.states.load instanceof String) {
                        section.app.state = req.body.app.states.load;
                        log.debug('Loading existing named state:', section.app.state);
                    } else {
                        log.debug('Loading state configuration');
                        request.post(section.app.url + '/instances/' + sectionId + '/state', {
                            headers: { 'Content-Type': Constants.HTTP_CONTENT_TYPE_JSON },
                            json: req.body.app.states.load
                        }, _handleRequestError);
                    }
                }
            }
            const opacity = req.body.app.opacity;
            if (opacity) {
                log.debug('Setting opacity for app:', opacity);
                section.app.opacity = opacity;
            }
        }
        server.state.set('sections[' + sectionId + ']', section);

        // Notify OVE viewers/controllers
        server.wss.clients.forEach(function (c) {
            if (c.readyState === Constants.WEBSOCKET_READY) {
                // Sections are created on the browser and then the application is deployed after a
                // short delay. This will ensure proper frame sizes.
                c.safeSend(JSON.stringify({ appId: Constants.APP_NAME,
                    message: { action: Constants.Action.CREATE, id: sectionId, spaces: section.spaces } }));
                if (section.app) {
                    setTimeout(function () {
                        c.safeSend(JSON.stringify({ appId: Constants.APP_NAME,
                            message: { action: Constants.Action.UPDATE, id: sectionId, app: section.app } }));
                    }, Constants.SECTION_UPDATE_DELAY);
                }
            }
        });
        log.info('Successfully created new section:', sectionId);
        log.debug('Existing sections (active/deleted):', server.state.get('sections').length);
        Utils.sendMessage(res, HttpStatus.OK, JSON.stringify({ id: sectionId }));
    }
579822
function blockChecksums(fs, path, size, callback) {
  var cache = {};

  fs.readFile(path, function (err, data) {
    if (!err) {
      // cache file
      cache[path] = data;
    } else if (err && err.code === 'ENOENT') {
      cache[path] = [];
    } else {
      return callback(err);
    }

    var length = cache[path].length;
    var incr = size;
    var start = 0;
    var end = incr > length ? length : incr;
    var blockIndex = 0;
    var result = [];
    var chunk;
    var weak;
    var strong;

    while (start < length) {
      chunk  = cache[path].slice(start, end);
      weak   = calcWeak32(chunk).sum;
      strong = md5sum(chunk);

      result.push({
        index: blockIndex,
        weak: weak,
        strong: strong
      });
      // update slice indices
      start += incr;
      end = (end + incr) > length ? length : end + incr;
      // update block index
      blockIndex++;
    }

    callback(null, result);
  });
}
883798
function nusoap_server($wsdl=false){
		parent::nusoap_base();
		// turn on debugging?
		global $debug;
		global $HTTP_SERVER_VARS;

		if (isset($_SERVER)) {
			$this->debug("_SERVER is defined:");
			$this->appendDebug($this->varDump($_SERVER));
		} elseif (isset($HTTP_SERVER_VARS)) {
			$this->debug("HTTP_SERVER_VARS is defined:");
			$this->appendDebug($this->varDump($HTTP_SERVER_VARS));
		} else {
			$this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined.");
		}

		if (isset($debug)) {
			$this->debug("In nusoap_server, set debug_flag=$debug based on global flag");
			$this->debug_flag = $debug;
		} elseif (isset($_SERVER['QUERY_STRING'])) {
			$qs = explode('&', $_SERVER['QUERY_STRING']);
			foreach ($qs as $v) {
				if (substr($v, 0, 6) == 'debug=') {
					$this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #1");
					$this->debug_flag = substr($v, 6);
				}
			}
		} elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
			$qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']);
			foreach ($qs as $v) {
				if (substr($v, 0, 6) == 'debug=') {
					$this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #2");
					$this->debug_flag = substr($v, 6);
				}
			}
		}

		// wsdl
		if($wsdl){
			$this->debug("In nusoap_server, WSDL is specified");
			if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) {
				$this->wsdl = $wsdl;
				$this->externalWSDLURL = $this->wsdl->wsdl;
				$this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL);
			} else {
				$this->debug('Create wsdl from ' . $wsdl);
				$this->wsdl = new wsdl($wsdl);
				$this->externalWSDLURL = $wsdl;
			}
			$this->appendDebug($this->wsdl->getDebug());
			$this->wsdl->clearDebug();
			if($err = $this->wsdl->getError()){
				die('WSDL ERROR: '.$err);
			}
		}
	}
1158157
function() {
    var query = new nodes.Query
      , expr
      , pred
      , id;

    // hash values support
    if ('ident' == this.peek().type
      && ('.' == this.lookahead(2).type
      || '[' == this.lookahead(2).type)) {
      this.cond = true;
      expr = this.expression();
      this.cond = false;
      query.push(new nodes.Feature(expr.nodes));
      return query;
    }

    if (pred = this.accept('ident') || this.accept('not')) {
      pred = new nodes.Literal(pred.val.string || pred.val);

      this.skipSpacesAndComments();
      if (id = this.accept('ident')) {
        query.type = id.val;
        query.predicate = pred;
      } else {
        query.type = pred;
      }
      this.skipSpacesAndComments();

      if (!this.accept('&&')) return query;
    }

    do {
      query.push(this.feature());
    } while (this.accept('&&'));

    return query;
  }
899791
function() {
    var queries = new nodes.QueryList
      , skip = ['comment', 'newline', 'space'];

    do {
      this.skip(skip);
      queries.push(this.query());
      this.skip(skip);
    } while (this.accept(','));
    return queries;
  }
606127
function jsonSections(sections, block) {

  return sections.map(function(section) {
    // Temporary inserting of partial
    var partial = section;
    if (partial.markup() && partial.markup().toString().match(/^[^\n]+\.(html|hbs|pug)$/)) {
      partial.file = partial.markup().toString();
      partial.name = path.basename(partial.file, path.extname(partial.file));
      partial.file = path.dirname(block.filePath) + '/' + partial.file;
      partial.markupText = fs.readFileSync(partial.file, 'utf8');
      section.markup = function() {
        return partial.markupText;
      };
    }

    return {
      header: generateDescription(section.header(), {noWrapper: true}),
      description: generateDescription(section.description()),
      modifiers: jsonModifiers(section.modifiers()),
      deprecated: section.deprecated(),
      experimental: section.experimental(),
      reference: section.reference(),
      markup: section.markup() ? section.markup().toString() : null
    };
  });
}
912747
function nodeClient (request) {

    var client = require('got');

    return new PromiseObj(function (resolve) {

        var url = request.getUrl();
        var body = request.getBody();
        var method = request.method;
        var headers = {}, handler;

        request.headers.forEach(function (value, name) {
            headers[name] = value;
        });

        client(url, {body: body, method: method, headers: headers}).then(handler = function (resp) {

            var response = request.respondWith(resp.body, {
                status: resp.statusCode,
                statusText: trim(resp.statusMessage)
            });

            each(resp.headers, function (value, name) {
                response.headers.set(name, value);
            });

            resolve(response);

        }, function (error$$1) { return handler(error$$1.response); });
    });
}