查找相关的数据, 更新或者插入
@param {object} source source model
@param {string} model target model
@param {object|array} args 要生成的参数
@param {any} t 事务标志
@return {Promise.<void>}
@this model
774530
async function many2many (source, model, args = [], t) {
  let pluralModel = pluralize.plural(model)
  let current = []

  if (args.every(arg => _.isObject(arg))) {
    for (let arg of args) {
      let obj = await util.insertOrUpdate(this.models[model], arg, t)

      if (obj) {
        current.push(obj)
      }
    }
  } else {
    current = await this.models[model].findAll({
      where: {id: {[Op.in]: args}},
      transaction: t
    })
  }

  await source[`set${_.upperFirst(this.associations[pluralModel].as)}`](current, {transaction: t})
}
1169458
function logEvent(model, event, state) {
  console.groupCollapsed('event:', event)
  console.log('new state:', state)
  if (model !== state.model) {
    console.log('model: from', model, 'to', state.model)
  } else {
    console.log('model (not changed):', model)
  }
  console.log('effect:', state.effect)
  console.groupEnd()
}
1345289
function(args, callback) {
      // Make sure the ID exists
      var t = this, model = args.model;
      if (!model || !model.id) {
        return callback({msg:'SyncProbe create - Data model with ID not present'});
      }

      // Make sure the file doesn't already exist
      t.getFullPath(model.id, function(error, response) {
        if (error) {
          return callback(error);
        }

        if (response.stats) {
          return callback({msg:'Document with this ID already exists'});
        }

        // Forward to the update control
        t.update_control(args, callback);
      });
    }
856189
async function setup (payload, ...args) {
    let msg = await store.logon(payload);
    prtUtil.print(`Logon status: ${msg}`);
    debugger;
    let {modelPublish} = await store.addServices(...args);
    console.log(store.getServices());

    let links = modelPublish.links();
    //console.log(JSON.stringify(links, null, 4));

    console.log('------------- root links');
    links.map((v,k) => {
        console.log(`rel: ${k}`);
        console.log(JSON.stringify(v.get('link'), null, 4));

    })
    
    payload = {
        qs: {
            limit: 1000
        }
    }

    let r = await store.apiCall(modelPublish.links('getPublishedModel'), payload);

    console.log('------------------ links from getPublishedModel');
    links = r.links();
    links.map((v,k) => {
        console.log(`rel: ${k}`);
        console.log(JSON.stringify(v.get('link'), null, 4));

    })

    r = await store.apiCall(r.links('up'));

    return true;
    }
438037
public <T> T invoke(Object target, Object... args) {
        return ReflectUtil.invoke(target, method, args);
    }
1222955
public <R> PromisesArray<R> map(final Function<T, Promise<R>> fun) {
        return mapSourcePromises(srcPromise -> new Promise<R>(resolver -> {
            srcPromise.then(t -> {
                Promise<R> mapped = fun.apply(t);
                mapped.then(t2 -> resolver.result(t2));
                mapped.failure(e -> resolver.error(e));
            });
            srcPromise.failure(e -> resolver.error(e));
        }));
    }
73456
function makeTxClient(trx, client, connection) {
  const trxClient = Object.create(client.constructor.prototype);
  trxClient.version = client.version;
  trxClient.config = client.config;
  trxClient.driver = client.driver;
  trxClient.connectionSettings = client.connectionSettings;
  trxClient.transacting = true;
  trxClient.valueForUndefined = client.valueForUndefined;
  trxClient.logger = client.logger;

  trxClient.on('query', function(arg) {
    trx.emit('query', arg);
    client.emit('query', arg);
  });

  trxClient.on('query-error', function(err, obj) {
    trx.emit('query-error', err, obj);
    client.emit('query-error', err, obj);
  });

  trxClient.on('query-response', function(response, obj, builder) {
    trx.emit('query-response', response, obj, builder);
    client.emit('query-response', response, obj, builder);
  });

  const _query = trxClient.query;
  trxClient.query = function(conn, obj) {
    const completed = trx.isCompleted();
    return Promise.try(function() {
      if (conn !== connection)
        throw new Error('Invalid connection for transaction query.');
      if (completed) completedError(trx, obj);
      return _query.call(trxClient, conn, obj);
    });
  };
  const _stream = trxClient.stream;
  trxClient.stream = function(conn, obj, stream, options) {
    const completed = trx.isCompleted();
    return Promise.try(function() {
      if (conn !== connection)
        throw new Error('Invalid connection for transaction query.');
      if (completed) completedError(trx, obj);
      return _stream.call(trxClient, conn, obj, stream, options);
    });
  };
  trxClient.acquireConnection = function() {
    return Promise.resolve(connection);
  };
  trxClient.releaseConnection = function() {
    return Promise.resolve();
  };

  return trxClient;
}
313077
function eventSourceUnit (server) {
  var sources = {};

  function Source () {
    this.conn = [];
    this.history = [];
    this.lastMsgId = 0;
  }

  Source.prototype.removeConn = function(res) {
    var i = this.conn.indexOf(res);
    if (i !== -1) {
      this.conn.splice(i, 1);
    }
  };

  Source.prototype.sendSSE = function (res, id, event, message) {
    var data = '';
    if (event !== null) {
      data += 'event:' + event + '\n';
    }

    // Blank id resets the id counter.
    if (id !== null) {
      data += 'id:' + id + '\n';
    } else {
      data += 'id\n';
    }

    if (message) {
      data += 'data:' + message.split('\n').join('\ndata:') + '\n';
    }
    data += '\n';

    res.write(data);

    if (res.hasOwnProperty('xhr')) {
      clearTimeout(res.xhr);
      var self = this;
      res.xhr = setTimeout(function () {
        res.end();
        self.removeConn(res);
      }, 250);
    }
  };

  Source.prototype.emit = function (event, msg) {
    this.lastMsgId++;
    this.history.push({
      id: this.lastMsgId,
      event: event,
      msg: msg
    });

    for (var i = 0; i < this.conn.length; i++) {
      this.sendSSE(this.conn[i], this.lastMsgId, event, msg);
    }
  }

  Source.prototype.send = function (msg) {
    this.emit(null, JSON.stringify(msg));
  }

  function eventSource (channel) {
    if (channel[0] !== '/') { channel = '/$' + channel; }
    return sources[channel] = new Source();
  }

  server.eventSource = eventSource;


  return function eventSourceLayer (req, res, next) {
    if (sources[req.path] === undefined) return next();
    var source = sources[req.path];
    if (!source || req.headers.accept !== 'text/event-stream')
      return next();    // Don't bother if the client cannot handle it.

    // Remy Sharp's Polyfill support.
    if (req.headers['x-requested-with'] == 'XMLHttpRequest') {
      res.xhr = null;
    }

    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');

    if (req.headers['last-event-id']) {
      var id = parseInt(req.headers['last-event-id']);
      for (var i = 0; i < source.history.length; i++)
        if (source.history[i].id > id)
          source.sendSSE(res, source.history[i].id,
              source.history[i].event, source.history[i].msg);
    } else res.write('id\n\n');      // Reset id.

    source.conn.push(res);

    // Every 15s, send a comment (avoids proxy dropping HTTP connection).
    var to = setInterval(function () {res.write(':\n');}, 15000);

    // This can only end in blood.
    req.on('close', function () {
      source.removeConn(res);
      clearInterval(to);
    });
  };
}
1274558
function() {
    return new Promise((resolve, reject) => {
      let instance;
      if (this.modelElement.name === this.node.getName()) {
        instance = this.node;
      } else {
        instance = this.mapper.getObject(this.modelElement.path());
      }

      if (instance) {
        if (instance.isStarted()) {
          instance.__update__(timesUp('update(...)', 30000, (err) => {
            if (err) {
              this.log.error('Unable to update ' + instance.getPath());
              reject(err);
            } else {
              this.log.debug(instance.getPath());
              this.node.kCore.emitter.emit('instanceUpdated', instance);
              resolve();
            }
          }));
        }
      } else {
        reject(new Error(this.toString() + ' error: unable to update instance ' + this.modelElement.name));
      }
    });
  }
1368197
function generate(argv, config) {
  return new Promise((resolve, reject) => {
    _generate(argv, config, resolve, reject);
  });
}
1256749
function callAndCatchPromiseError(fn, ...args) {
  // args 最后一个参数如果是如果是 function 则表示 next()
  // 如果执行时出错，调用 next(err)
  const next = args[args.length - 1];
  let p = null;
  try {
    p = fn.apply(null, args);
  } catch (err) {
    return next(err);
  }
  if (p && p.then && p.catch) {
    p.catch(err => next(err));
  }
}
492030
function reloadState(model, notify) {
    return function reload() {
        let { pathname, histories } = model,
            method = actionTypes.replace;

        // 更新监听
        return notify({
            pathname, method, histories, length: histories.length
        });
    };
}
907075
function emit(event /* , args... */) {
  this._events = this._events || {};
  // NOTE: copy array so that removing listeners in listeners (once etc)
  // NOTE: does not affect the iteration
  var list = (this._events[event] || []).slice(0);
  for(var i = 0; i < list.length; i++) {
    list[i].apply(this, Array.prototype.slice.call(arguments, 1))
  }
  return list.length > 0;
}
893381
function goState(model) {
    return function go(pathname, { method = actionTypes.push } = {}) {

        // 忽略同一跳转
        if (pathname === model.pathname) {
            return false;
        }

        // 更新状态
        model.state = { method, pathname, action: actionTypes.push };
        return model.history.push(pathname);
    };
}
557555
function(model, at){
        model = new this._Model(model, this.options.Model.options);

        if (!this.hasModel(model)) {
            // Attach events to the model that will signal collection events
            this.attachModelEvents(model);

            // If _models is empty, then we make sure to push instead of splice.
            at = this.length == 0 ? void 0 : at;

            if (at != void 0) {
                this._models.splice(at, 0, model);
            } else {
                this._models.push(model);
            }

            this.length = this._models.length;

            this._changed = true;

            // if at is undefined, then it would be at the end of the array, thus this.length-1
            this.signalAdd(model, at != void 0 ? at : this.length - 1);
        }

        return this;
    }
702752
function ArrayEmitter(...args) {

  // Need to generate an actual array here for proper behaviour (in a full ES6 environment we
  // should be able to subclass array. But alas)
  var arr = new Array(...args);

  // Non enumerable so that we can send the array over postMessage
  Object.defineProperty(arr, '$emitter', {
    enumerable: false,
    value: new EventEmitter()
  });

  // Generate our Array Emitter methods
  var ArrayEmitterMethods = {};
  ['on', 'once', 'addListener', 'removeListener'].forEach(function(key) {
    ArrayEmitterMethods[key] = {
      enumerable: false,
      value: function(...args) {
        return this.$emitter[key](...args);
      }
    };
  });

  // These methods create new arrays
  ['reverse', 'sort', 'splice'].forEach(function(key) {
    ArrayEmitterMethods[key] = {
      enumerable: false,
      value: function(...args) {
        var _emitter = this.$emitter;
        incrMaxListeners(_emitter);
        _emitter.on('update', () => {
          ArrayProto[key].apply(this, args);
        });

        ArrayProto[key].apply(this, args);
        return this;
      }
    };
  });

  ['filter', 'map', 'slice'].forEach(function(key) {
    ArrayEmitterMethods[key] = {
      enumerable: false,
      value: function(...args) {
        var newArr = new ArrayEmitter();
        var _emitter = this.$emitter;
        incrMaxListeners(_emitter);
        _emitter.on('update', () => {
          updateNewArr(ArrayProto[key].apply(this, args));
          newArr.$emitter.emit('update', newArr);
        });

        updateNewArr(ArrayProto[key].apply(this, args));

        function updateNewArr(arr) {
          newArr.length = 0;
          for (var i = 0; i < arr.length; i++) {
            newArr.push(arr[i]);
          }
        }

        return newArr;
      }
    };
  });

  ArrayEmitterMethods.concat = {
    enumerable: false,
    value: function(...args) {
      var newArr = new ArrayEmitter();
      var allArrs = [this, ...args];
      var qries = allArrs.filter((obj) => (Array.isArray(obj) && obj.$emitter));
      qries.forEach((_qry) => {
        var _emitter = _qry.$emitter;
        incrMaxListeners(_emitter);
        _emitter.on('update', () => {
          updateConcat();
          newArr.$emitter.emit('update', newArr);
        });
      });

      updateConcat();

      return newArr;

      function updateConcat() {
        var concatted = ArrayProto.concat.call(...allArrs);
        newArr.length = 0;
        newArr.push(...concatted);
      }
    }
  };

  Object.defineProperties(arr, ArrayEmitterMethods);

  return arr;
}
1353370
function emit(event) {
  if (typeof EVENTS[event] === 'undefined') return;
  var args = Array.prototype.slice.call(arguments);
  args.splice(0, 1);
  for (var i = 0; i < EVENTS[event].length; i++) {
    EVENTS[event][i].apply(loglet, args);
  }
}