diff --git a/.project b/.project
new file mode 100644
--- /dev/null
+++ b/.project
@@ -0,0 +1,17 @@
+
+id
+ * @param{dojo.store} opts.store Родительское хранилище
+ */
+ constructor : function(opts) {
+ safe.argumentNotNull(opts, "opts");
+ safe.argumentNotNull(opts.store, "opts.store");
+
+ this._store = opts.store;
+ delete opts.store;
+ declare.safeMixin(this, opts);
+ this.idProperty = opts.idProperty || this._store.idProperty || "id";
+ },
+
+ getParentStore : function() {
+ return this._store;
+ },
+
+ get : function(id) {
+ var me = this;
+ return when(me._store.get(id), function(x) {
+ var m = me.mapItem(x);
+ if (!(me.idProperty in m))
+ m[me.idProperty] = id;
+ return m;
+ });
+ },
+
+ /**
+ * Выполняет запрос в родительском хранилище, для этого используется
+ * translateQuery для подготовки запроса, затем,
+ * mapItem для преобразования результатов.
+ */
+ query : function(q, options) {
+ var me = this, store = this._store;
+ return when(store.query(me.translateQuery(q), me
+ .translateOptions(options)), function(res) {
+ var total = res.total;
+ var mapped = res.map(function(x) {
+ var m = me.mapItem(x);
+ if (!(me.idProperty in m))
+ m[me.idProperty] = store.getIdentity &&
+ store.getIdentity(x);
+ return m;
+ });
+ mapped.total = total;
+ var results = new QueryResults(mapped);
+ console.log(results);
+ return results;
+ });
+ },
+
+ getIdentity : function(obj) {
+ return obj && obj[this.idProperty];
+ },
+
+ /**
+ * Преобразование запроса в формат родительского хранилища.
+ *
+ * @param{Object} q Запрос в формате текущего хранилища
+ * @returns{Object} Запрос в формате родительского хранилища
+ */
+ translateQuery : function(q) {
+ return q;
+ },
+
+ translateOptions : function(options) {
+ return options;
+ },
+
+ /**
+ * Преобразование объекта из родительского хранилища. При преобразовании
+ * в объекте можно задать идентификатор, иначе идентификатор будет
+ * автоматически получен и присвоен из родительского хранилища
+ *
+ * @param{Object} item Объект из родительского хранилища
+ * @returns{Object} результат преобразования
+ */
+ mapItem : function(item) {
+ return item;
+ }
+ });
+
+});
\ No newline at end of file
diff --git a/src/js/data/_ModelBase.js b/src/js/data/_ModelBase.js
new file mode 100644
--- /dev/null
+++ b/src/js/data/_ModelBase.js
@@ -0,0 +1,37 @@
+define(["dojo/_base/declare"], function(declare) {
+
+ return declare(null, {
+ dataContext : null,
+ idField : "id",
+ loaded : false,
+
+ constructor : function(opts){
+ if (opts) {
+ if(opts.dataContext)
+ this.dataContext = opts.dataContext;
+ if(opts.id)
+ this[this.idField] = opts.id;
+ }
+ },
+
+ getId : function() {
+ return this[this.idField];
+ },
+
+ attach : function(id, dc) {
+ if (this.dataContext)
+ throw new Error("The object is already attached");
+ this[this.idField] = id;
+ this.dataContext = dc;
+ },
+
+ isAttached : function() {
+ return this.dataContext ? true : false;
+ },
+
+ onPopulate : function() {
+ this.loaded = true;
+ }
+
+ });
+});
\ No newline at end of file
diff --git a/src/js/data/_StatefulModelMixin.js b/src/js/data/_StatefulModelMixin.js
new file mode 100644
--- /dev/null
+++ b/src/js/data/_StatefulModelMixin.js
@@ -0,0 +1,5 @@
+define(["dojo/_base/declare", "dojo/Stateful"], function(declare, Stateful) {
+ return declare([Stateful], {
+
+ });
+});
\ No newline at end of file
diff --git a/src/js/data/declare-model.js b/src/js/data/declare-model.js
new file mode 100644
--- /dev/null
+++ b/src/js/data/declare-model.js
@@ -0,0 +1,72 @@
+define([ "dojo/_base/declare", "./_ModelBase", "./MapSchema" ], function(
+ declare, _ModelBase, MapSchema) {
+ /**
+ * Создает новый класс, унаследованный от ./ModelBase, с указанной схемой
+ * отображения данных.
+ *
+ * @details Модель представляет собой объект, живущий в рамках контекста
+ * данных, также имеющий две схемы отображения: из модели хранения
+ * в источнике данных (toObjectMap) и наооборот в модель хранения в
+ * источнике данных (fromObjectMap).
+ *
+ * Описание схемы выглядит следующим образом
+ *
+ * {
+ * name : null, // отображение в обе стороны без преобразования
+ *
+ * age : Number, // при преобразоваении к объекту поле будет преобразовано dst.age = Number(src.age)
+ * // обратное преобразование отсутстсвует
+ *
+ * age : [Number, null] // тоже самое что и age : Number
+ *
+ * date : [Date, function(v) { return v.toString() }] // указывается преобразование в одну и в другую сторону
+ * }
+ *
+ */
+ return function(schema, mixins, opts) {
+ var fromObjectSchema = {}, toObjectSchema = {};
+ if (schema !== null && schema !== undefined) {
+ for ( var p in schema) {
+ var mapper = schema[p];
+
+ if (mapper instanceof Array) {
+ toObjectSchema[p] = mapper[0];
+ fromObjectSchema[p] = mapper[1];
+ } else {
+ toObjectSchema[p] = mapper;
+ fromObjectSchema[p] = null;
+ }
+ }
+ }
+
+ if (arguments.length < 3) {
+ opts = mixins;
+ mixins = undefined;
+ }
+
+ var base = [ _ModelBase ];
+ if (mixins) {
+ if (mixins instanceof Array)
+ base = base.concat(mixins);
+ else
+ base.push(mixins);
+ }
+
+ var model = declare(base, opts);
+
+ model.toObjectMap = new MapSchema(toObjectSchema);
+
+ model.fromObjectMap = new MapSchema(fromObjectSchema);
+
+ model.readData = function(that, data, context) {
+ model.toObjectMap.map(data, that, context);
+ };
+
+ model.writeData = function(that, data, context) {
+ data = data || {};
+ model.fromObjectMap.map(that, data, context);
+ };
+
+ return model;
+ };
+});
\ No newline at end of file
diff --git a/src/js/declare.js b/src/js/declare.js
new file mode 100644
--- /dev/null
+++ b/src/js/declare.js
@@ -0,0 +1,6 @@
+define([
+ './declare/_load!'
+], function(declare) {
+ 'use strict';
+ return declare;
+});
\ No newline at end of file
diff --git a/src/js/declare/_load.js b/src/js/declare/_load.js
new file mode 100644
--- /dev/null
+++ b/src/js/declare/_load.js
@@ -0,0 +1,12 @@
+define([], function () {
+ 'use strict';
+
+ return {
+ load: function (id, require, callback) {
+ require(['dojo/_base/declare'], function (declare) {
+ callback(declare);
+ });
+ }
+ };
+
+});
\ No newline at end of file
diff --git a/src/js/declare/override.js b/src/js/declare/override.js
new file mode 100644
--- /dev/null
+++ b/src/js/declare/override.js
@@ -0,0 +1,73 @@
+"use strict";
+define([], function () {
+ var slice = Array.prototype.slice;
+ var override = function (method) {
+ var proxy;
+
+ /** @this target object */
+ proxy = function () {
+ var me = this;
+ var inherited = (this.getInherited && this.getInherited(proxy.nom, {
+ callee: proxy
+ })) || function () {};
+
+ return method.apply(me, [function () {
+ return inherited.apply(me, arguments);
+ }].concat(slice.apply(arguments)));
+ };
+
+ proxy.method = method;
+ proxy.overrides = true;
+
+ return proxy;
+ };
+
+ override.before = function (method) {
+ var proxy;
+
+ /** @this target object */
+ proxy = function () {
+ var me = this;
+ var inherited = (this.getInherited && this.getInherited(proxy.nom, {
+ callee: proxy
+ })) || function () {};
+
+
+ method.apply(me, arguments);
+ return inherited.apply(me, arguments);
+ };
+
+ proxy.method = method;
+ proxy.overrides = true;
+
+ return proxy;
+ };
+
+ override.after = function (method) {
+ var proxy;
+
+ /** @this target object */
+ proxy = function () {
+ var me = this;
+ var inherited = (this.getInherited && this.getInherited(proxy.nom, {
+ callee: proxy
+ })) || function () {};
+
+ inherited.apply(me, arguments);
+
+ return method.apply(me, arguments);
+ };
+
+ proxy.method = method;
+ proxy.overrides = true;
+
+ return proxy;
+ };
+
+ override.hide = function (method) {
+ method.overrides = false;
+ return method;
+ };
+
+ return override;
+});
\ No newline at end of file
diff --git a/src/js/di/ActivationContext.js b/src/js/di/ActivationContext.js
new file mode 100644
--- /dev/null
+++ b/src/js/di/ActivationContext.js
@@ -0,0 +1,138 @@
+define([
+ "../declare",
+ "../safe",
+ "./Descriptor",
+ "./ValueDescriptor",
+ "../log/trace!"
+], function (declare, safe, Descriptor, Value, trace) {
+ var Context = declare(null, {
+
+ _cache: null,
+
+ _services: null,
+
+ _stack: null,
+
+ _visited: null,
+
+ container: null,
+
+ _trace: true,
+
+ constructor: function (container, services, cache, visited) {
+ safe.argumentNotNull(container, "container");
+ safe.argumentNotNull(services, "services");
+
+ this._visited = visited || {};
+ this._stack = [];
+ this._cache = cache || {};
+ this._services = services;
+ this.container = container;
+ },
+
+ getService: function (name, def) {
+ var d = this._services[name];
+
+ if (!d)
+ if (arguments.length > 1)
+ return def;
+ else
+ throw new Error("Service '" + name + "' not found");
+
+ return d.activate(this, name);
+ },
+
+ /**
+ * registers services local to the the activation context
+ *
+ * @name{string} the name of the service
+ * @service{string} the service descriptor to register
+ */
+ register: function (name, service) {
+ safe.argumentNotEmptyString(name, "name");
+
+ if (!(service instanceof Descriptor))
+ service = new Value(service, true);
+ this._services[name] = service;
+ },
+
+ clone: function () {
+ return new Context(
+ this.container,
+ Object.create(this._services),
+ this._cache,
+ this._visited
+ );
+
+ },
+
+ has: function (id) {
+ return id in this._cache;
+ },
+
+ get: function (id) {
+ return this._cache[id];
+ },
+
+ store: function (id, value) {
+ return (this._cache[id] = value);
+ },
+
+ parse: function (data, name) {
+ var me = this;
+ if (safe.isPrimitive(data))
+ return data;
+
+ if (data instanceof Descriptor) {
+ return data.activate(this, name);
+ } else if (data instanceof Array) {
+ me.enter(name);
+ var v = data.map(function (x, i) {
+ return me.parse(x, "." + i);
+ });
+ me.leave();
+ return v;
+ } else {
+ me.enter(name);
+ var result = {};
+ for (var p in data)
+ result[p] = me.parse(data[p], "." + p);
+ me.leave();
+ return result;
+ }
+ },
+
+ visit: function (id) {
+ var count = this._visited[id] || 0;
+ this._visited[id] = count + 1;
+ return count;
+ },
+
+ getStack: function () {
+ return this._stack.slice().reverse();
+ },
+
+ enter: function (name, d, localize) {
+ if (this._trace)
+ trace.log("enter " + name + " " + (d || "") +
+ (localize ? " localize" : ""));
+ this._stack.push({
+ name: name,
+ service: d,
+ scope: this._services
+ });
+ if (localize)
+ this._services = Object.create(this._services);
+ },
+
+ leave: function () {
+ var ctx = this._stack.pop();
+ this._services = ctx.scope;
+
+ if (this._trace)
+ trace.log("leave " + ctx.name + " " + (ctx.service || ""));
+ }
+ });
+
+ return Context;
+});
\ No newline at end of file
diff --git a/src/js/di/ActivationError.js b/src/js/di/ActivationError.js
new file mode 100644
--- /dev/null
+++ b/src/js/di/ActivationError.js
@@ -0,0 +1,39 @@
+define([
+ "../declare"
+], function (declare) {
+ return declare(null, {
+ activationStack: null,
+
+ service: null,
+
+ innerException: null,
+
+ message: null,
+
+ constructor: function (service, activationStack, innerException) {
+ this.message = "Failed to activate the service";
+ this.activationStack = activationStack;
+ this.service = service;
+ this.innerException = innerException;
+ },
+
+ toString: function () {
+ var parts = [this.message];
+ if (this.service)
+ parts.push("when activating: " + this.service.toString());
+
+ if (this.innerException)
+ parts.push("caused by: " + this.innerException.toString());
+
+ if (this.activationStack) {
+ parts.push("at");
+ this.activationStack.forEach(function (x) {
+ parts.push(" " + x.name + " " +
+ (x.service ? x.service.toString() : ""));
+ });
+ }
+
+ return parts.join("\n");
+ }
+ });
+});
\ No newline at end of file
diff --git a/src/js/di/Container.js b/src/js/di/Container.js
new file mode 100644
--- /dev/null
+++ b/src/js/di/Container.js
@@ -0,0 +1,299 @@
+define([
+ "../declare",
+ "../safe",
+ "../Uuid",
+ "../Deferred",
+ "./ActivationContext",
+ "./Descriptor",
+ "./ValueDescriptor",
+ "./ReferenceDescriptor",
+ "./ServiceDescriptor",
+ "./ActivationError"
+], function (
+ declare,
+ safe,
+ Uuid,
+ Deferred,
+ ActivationContext,
+ Descriptor,
+ Value,
+ Reference,
+ Service,
+ ActivationError) {
+ var Container = declare(null, {
+ _services: null,
+ _cache: null,
+ _cleanup: null,
+ _root: null,
+ _parent: null,
+
+ constructor: function (parent) {
+ this._parent = parent;
+ this._services = parent ? Object.create(parent._services) : {};
+ this._cache = {};
+ this._cleanup = [];
+ this._root = parent ? parent.getRootContainer() : this;
+ this._services.container = new Value(this, true);
+ },
+
+ getRootContainer: function () {
+ return this._root;
+ },
+
+ getParent: function () {
+ return this._parent;
+ },
+
+ /**
+ *
+ */
+ getService: function (name, def) {
+ var d = this._services[name];
+ if (!d)
+ if (arguments.length > 1)
+ return def;
+ else
+ throw new Error("Service '" + name + "' isn't found");
+ if (d.isInstanceCreated())
+ return d.getInstance();
+
+ var context = new ActivationContext(this, this._services);
+
+ try {
+ return d.activate(context, name);
+ } catch (error) {
+ throw new ActivationError(name, context.getStack(), error);
+ }
+ },
+
+ register: function (name, service) {
+ if (arguments.length == 1) {
+ var data = name;
+ for (name in data)
+ this.register(name, data[name]);
+ } else {
+ if (!(service instanceof Descriptor))
+ service = new Value(service, true);
+ this._services[name] = service;
+ }
+ return this;
+ },
+
+ onDispose: function (callback) {
+ if (!(callback instanceof Function))
+ throw new Error("The callback must be a function");
+ this._cleanup.push(callback);
+ },
+
+ dispose: function () {
+ if (this._cleanup) {
+ for (var i = 0; i < this._cleanup.length; i++)
+ this._cleanup[i].call(null);
+ this._cleanup = null;
+ }
+ },
+
+ /**
+ * @param{String|Object} config
+ * The configuration of the contaier. Can be either a string or an object,
+ * if the configuration is an object it's treated as a collection of
+ * services which will be registed in the contaier.
+ *
+ * @param{Function} opts.contextRequire
+ * The function which will be used to load a configuration or types for services.
+ *
+ */
+ configure: function (config, opts) {
+ var p, me = this,
+ contextRequire = (opts && opts.contextRequire);
+
+ if (typeof (config) === "string") {
+ p = new Deferred();
+ if (!contextRequire) {
+ var shim = [config, new Uuid()].join(config.indexOf("/") != -1 ? "-" : "/");
+ define(shim, ["require", config], function (ctx, data) {
+ p.resolve([data, {
+ contextRequire: ctx
+ }]);
+ });
+ require([shim]);
+ } else {
+ // TODO how to get correct contextRequire for the relative config module?
+ contextRequire([config], function (data) {
+ p.resolve([data, {
+ contextRequire: contextRequire
+ }]);
+ });
+ }
+
+ return p.then(function (args) {
+ return me._configure.apply(me, args);
+ });
+ } else {
+ return me._configure(config, opts);
+ }
+ },
+
+ createChildContainer: function () {
+ return new Container(this);
+ },
+
+ has: function (id) {
+ return id in this._cache;
+ },
+
+ get: function (id) {
+ return this._cache[id];
+ },
+
+ store: function (id, value) {
+ return (this._cache[id] = value);
+ },
+
+ _configure: function (data, opts) {
+ var typemap = {},
+ d = new Deferred(),
+ me = this,
+ p,
+ contextRequire = (opts && opts.contextRequire) || require;
+
+ var services = {};
+
+ for (p in data) {
+ var service = me._parse(data[p], typemap);
+ if (!(service instanceof Descriptor))
+ service = new Value(service, false);
+ services[p] = service;
+ }
+
+ me.register(services);
+
+ var names = [];
+
+ for (p in typemap)
+ names.push(p);
+
+ if (names.length) {
+ contextRequire(names, function () {
+ for (var i = 0; i < names.length; i++)
+ typemap[names[i]] = arguments[i];
+ d.resolve(me);
+ });
+ } else {
+ d.resolve(me);
+ }
+ return d.promise;
+ },
+
+ _parse: function (data, typemap) {
+ if (safe.isPrimitive(data) || data instanceof Descriptor)
+ return data;
+ if (data.$dependency)
+ return new Reference(
+ data.$dependency,
+ data.lazy,
+ data.optional,
+ data["default"],
+ data.services && this._parseObject(data.services, typemap));
+ if (data.$value) {
+ var raw = !data.parse;
+ return new Value(raw ? data.$value : this._parse(
+ data.$value,
+ typemap), raw);
+ }
+ if (data.$type || data.$factory)
+ return this._parseService(data, typemap);
+ if (data instanceof Array)
+ return this._parseArray(data, typemap);
+
+ return this._parseObject(data, typemap);
+ },
+
+ _parseService: function (data, typemap) {
+ var me = this,
+ opts = {
+ owner: this
+ };
+ if (data.$type) {
+
+ opts.type = data.$type;
+
+ if (typeof (data.$type) === "string") {
+ typemap[data.$type] = null;
+ opts.typeMap = typemap;
+ }
+ }
+
+ if (data.$factory)
+ opts.factory = data.$factory;
+
+ if (data.services)
+ opts.services = me._parseObject(data.services, typemap);
+ if (data.inject)
+ opts.inject = data.inject instanceof Array ? data.inject.map(function (x) {
+ return me._parseObject(x, typemap);
+ }) : me._parseObject(data.inject, typemap);
+ if (data.params)
+ opts.params = me._parse(data.params, typemap);
+
+ if (data.activation) {
+ if (typeof (data.activation) === "string") {
+ switch (data.activation.toLowerCase()) {
+ case "singleton":
+ opts.activation = Service.SINGLETON;
+ break;
+ case "container":
+ opts.activation = Service.CONTAINER;
+ break;
+ case "hierarchy":
+ opts.activation = Service.HIERARCHY;
+ break;
+ case "context":
+ opts.activation = Service.CONTEXT;
+ break;
+ case "call":
+ opts.activation = Service.CALL;
+ break;
+ default:
+ throw new Error("Unknown activation type: " +
+ data.activation);
+ }
+ } else {
+ opts.activation = Number(data.activation);
+ }
+ }
+
+ if (data.cleanup)
+ opts.cleanup = data.cleanup;
+
+ return new Service(opts);
+ },
+
+ _parseObject: function (data, typemap) {
+ if (data.constructor &&
+ data.constructor.prototype !== Object.prototype)
+ return new Value(data, true);
+
+ var o = {};
+
+ for (var p in data)
+ o[p] = this._parse(data[p], typemap);
+
+ return o;
+ },
+
+ _parseArray: function (data, typemap) {
+ if (data.constructor &&
+ data.constructor.prototype !== Array.prototype)
+ return new Value(data, true);
+
+ var me = this;
+ return data.map(function (x) {
+ return me._parse(x, typemap);
+ });
+ }
+
+ });
+
+ return Container;
+});
\ No newline at end of file
diff --git a/src/js/di/Descriptor.js b/src/js/di/Descriptor.js
new file mode 100644
--- /dev/null
+++ b/src/js/di/Descriptor.js
@@ -0,0 +1,4 @@
+define([], function() {
+ // abstract base type for descriptros
+ return function() {};
+});
\ No newline at end of file
diff --git a/src/js/di/ReferenceDescriptor.js b/src/js/di/ReferenceDescriptor.js
new file mode 100644
--- /dev/null
+++ b/src/js/di/ReferenceDescriptor.js
@@ -0,0 +1,90 @@
+define([
+ "../declare", "../safe", "./Descriptor", "./ActivationError", "./ValueDescriptor"
+],
+
+function(declare, safe, Descriptor, ActivationError, Value) {
+ return declare(Descriptor, {
+ _name : null,
+ _lazy : false,
+ _optional : false,
+ _default : undefined,
+
+ constructor : function(name, lazy, optional, def, services) {
+ safe.argumentNotEmptyString(name, "name");
+ this._name = name;
+ this._lazy = Boolean(lazy);
+ this._optional = Boolean(optional);
+ this._default = def;
+ this._services = services;
+ },
+
+ activate : function(context, name) {
+ var me = this;
+
+ context.enter(name, this, true);
+
+ // добавляем сервисы
+ if (me._services) {
+ for ( var p in me._services) {
+ var sv = me._services[p];
+ context.register(p, sv instanceof Descriptor ? sv : new Value(sv, false));
+ }
+ }
+
+ if (me._lazy) {
+ // сохраняем контекст активации
+ context = context.clone();
+ return function(cfg) {
+ // защищаем контекст на случай исключения в процессе
+ // активации
+ var ct = context.clone();
+ try {
+ if (cfg)
+ safe.each(cfg, function(v, k) {
+ ct.register(k, v instanceof Descriptor ? v : new Value(v, false));
+ });
+ return me._optional ? ct.getService(me._name, me._default) : ct
+ .getService(me._name);
+ } catch (error) {
+ throw new ActivationError(me._name, ct.getStack(), error);
+ }
+ };
+ }
+
+ var v = me._optional ? context.getService(me._name, me._default) : context
+ .getService(me._name);
+ context.leave(me);
+ return v;
+ },
+
+ isInstanceCreated : function() {
+ return false;
+ },
+
+ toString : function() {
+ var opts = [];
+ if (this._optional)
+ opts.push("optional");
+ if (this._lazy)
+ opts.push("lazy");
+
+ var parts = [
+ "@ref "
+ ];
+ if (opts.length) {
+ parts.push("{");
+ parts.push(opts.join());
+ parts.push("} ");
+ }
+
+ parts.push(this._name);
+
+ if (!safe.isNull(this._default)) {
+ parts.push(" = ");
+ parts.push(this._default);
+ }
+
+ return parts.join("");
+ }
+ });
+});
\ No newline at end of file
diff --git a/src/js/di/ServiceDescriptor.js b/src/js/di/ServiceDescriptor.js
new file mode 100644
--- /dev/null
+++ b/src/js/di/ServiceDescriptor.js
@@ -0,0 +1,289 @@
+define(
+ [
+ "../declare",
+ "../safe",
+ "./Descriptor",
+ "./ValueDescriptor"
+ ],
+
+ function (declare, safe, Descriptor, Value) {
+ var SINGLETON_ACTIVATION = 1,
+ CONTAINER_ACTIVATION = 2,
+ CONTEXT_ACTIVATION = 3,
+ CALL_ACTIVATION = 4,
+ HIERARCHY_ACTIVATION = 5;
+
+ var injectMethod = function (target, method, context, args) {
+ var m = target[method];
+ if (!m)
+ throw new Error("Method '" + method + "' not found");
+
+ if (args instanceof Array)
+ m.apply(target, context.parse(args, "." + method));
+ else
+ m.call(target, context.parse(args, "." + method));
+ };
+
+ var makeClenupCallback = function (target, method) {
+ if (typeof (method) === "string") {
+ return function () {
+ target[method]();
+ };
+ } else {
+ return function () {
+ method(target);
+ };
+ }
+ };
+
+ var cacheId = 0;
+
+ var cls = declare(
+ Descriptor, {
+ _instance: null,
+ _hasInstance: false,
+ _activationType: CALL_ACTIVATION,
+ _services: null,
+ _type: null,
+ _typeMap: null,
+ _factory: null,
+ _params: undefined,
+ _inject: null,
+ _cleanup: null,
+ _cacheId: null,
+ _owner: null,
+
+ constructor: function (opts) {
+ safe.argumentNotNull(opts, "opts");
+ safe.argumentNotNull(opts.owner, "opts.owner");
+
+ this._owner = opts.owner;
+
+ if (!(opts.type || opts.factory))
+ throw new Error(
+ "Either a type or a factory must be specified");
+
+ if (typeof (opts.type) === "string" && !opts.typeMap)
+ throw new Error(
+ "The typeMap is required when the type is specified by its name");
+
+ if (opts.activation)
+ this._activationType = opts.activation;
+ if (opts.type)
+ this._type = opts.type;
+ if (opts.params)
+ this._params = opts.params;
+ if (opts.inject)
+ this._inject = opts.inject instanceof Array ? opts.inject : [opts.inject];
+ if (opts.services)
+ this._services = opts.services;
+ if (opts.factory)
+ this._factory = opts.factory;
+ if (opts.typeMap)
+ this._typeMap = opts.typeMap;
+ if (opts.cleanup) {
+ if (!(typeof (opts.cleanup) === "string" || opts.cleanup instanceof Function))
+ throw new Error(
+ "The cleanup parameter must be either a function or a function name");
+
+ this._cleanup = opts.cleanup;
+ }
+
+ this._cacheId = ++cacheId;
+ },
+
+ activate: function (context, name) {
+
+ // if we have a local service records, register them first
+
+ var instance;
+
+ switch (this._activationType) {
+ case 1: // SINGLETON
+ // if the value is cached return it
+ if (this._hasInstance)
+ return this._instance;
+
+ var tof = this._type || this._factory;
+
+ // create the persistent cache identifier for the type
+ if (safe.isPrimitive(tof))
+ this._cacheId = this._type;
+ else
+ this._cacheId = safe.oid(tof);
+
+ // singletons are bound to the root container
+ var container = context.container.getRootContainer();
+
+ if (container.has(this._cacheId)) {
+ instance = container.get(this._cacheId);
+ } else {
+ instance = this._create(context, name);
+ container.store(this._cacheId, instance);
+ if (this._cleanup)
+ container.onDispose(
+ makeClenupCallback(instance, this._cleanup));
+ }
+
+ this._hasInstance = true;
+ return (this._instance = instance);
+
+ case 2: // CONTAINER
+ //return a cached value
+ if (this._hasInstance)
+ return this._instance;
+
+ // create an instance
+ instance = this._create(context, name);
+
+ // the instance is bound to the container
+ if (this._cleanup)
+ this._owner.onDispose(
+ makeClenupCallback(instance, this._cleanup));
+
+ // cache and return the instance
+ this._hasInstance = true;
+ return (this._instance = instance);
+ case 3: // CONTEXT
+ //return a cached value if one exists
+ if (context.has(this._cacheId))
+ return context.get(this._cacheId);
+ // context context activated instances are controlled by callers
+ return context.store(this._cacheId, this._create(
+ context,
+ name));
+ case 4: // CALL
+ // per-call created instances are controlled by callers
+ return this._create(context, name);
+ case 5: // HIERARCHY
+ // hierarchy activated instances are behave much like container activated
+ // except they are created and bound to the child container
+
+ // return a cached value
+ if (context.container.has(this._cacheId))
+ return context.container.get(this._cacheId);
+
+ instance = this._create(context, name);
+
+ if (this._cleanup)
+ context.container.onDispose(makeClenupCallback(
+ instance,
+ this._cleanup));
+
+ return context.container.store(this._cacheId, instance);
+ default:
+ throw "Invalid activation type: " + this._activationType;
+ }
+ },
+
+ isInstanceCreated: function () {
+ return this._hasInstance;
+ },
+
+ getInstance: function () {
+ return this._instance;
+ },
+
+ _create: function (context, name) {
+ context.enter(name, this, Boolean(this._services));
+
+ if (this._activationType != CALL_ACTIVATION &&
+ context.visit(this._cacheId) > 0)
+ throw new Error("Recursion detected");
+
+ if (this._services) {
+ for (var p in this._services) {
+ var sv = this._services[p];
+ context.register(p, sv instanceof Descriptor ? sv : new Value(sv, false));
+ }
+ }
+
+ var instance;
+
+ if (!this._factory) {
+ var ctor, type = this._type;
+
+ if (typeof (type) === "string") {
+ ctor = this._typeMap[type];
+ if (!ctor)
+ throw new Error("Failed to resolve the type '" +
+ type + "'");
+ } else {
+ ctor = type;
+ }
+
+ if (this._params === undefined) {
+ this._factory = function () {
+ return new ctor();
+ };
+ } else if (this._params instanceof Array) {
+ this._factory = function () {
+ var inst = Object.create(ctor.prototype);
+ var ret = ctor.apply(inst, arguments);
+ return typeof (ret) === "object" ? ret : inst;
+ };
+ } else {
+ this._factory = function (param) {
+ return new ctor(param);
+ };
+ }
+ }
+
+ if (this._params === undefined) {
+ instance = this._factory();
+ } else if (this._params instanceof Array) {
+ instance = this._factory.apply(this, context.parse(
+ this._params,
+ ".params"));
+ } else {
+ instance = this._factory(context.parse(
+ this._params,
+ ".params"));
+ }
+
+ if (this._inject) {
+ this._inject.forEach(function (spec) {
+ for (var m in spec)
+ injectMethod(instance, m, context, spec[m]);
+ });
+ }
+
+ context.leave();
+
+ return instance;
+ },
+
+ // @constructor {singleton} foo/bar/Baz
+ // @factory {singleton}
+ toString: function () {
+ var parts = [];
+
+ parts.push(this._type ? "@constructor" : "@factory");
+
+ parts.push(activationNames[this._activationType]);
+
+ if (typeof (this._type) === "string")
+ parts.push(this._type);
+
+ return parts.join(" ");
+ }
+
+ });
+
+ cls.SINGLETON = SINGLETON_ACTIVATION;
+ cls.CONTAINER = CONTAINER_ACTIVATION;
+ cls.CONTEXT = CONTEXT_ACTIVATION;
+ cls.CALL = CALL_ACTIVATION;
+ cls.HIERARCHY = HIERARCHY_ACTIVATION;
+
+ var activationNames = [
+ "",
+ "{singleton}",
+ "{container}",
+ "{context}",
+ "{call}",
+ "{hierarchy}"
+ ];
+
+ return cls;
+ });
\ No newline at end of file
diff --git a/src/js/di/ValueDescriptor.js b/src/js/di/ValueDescriptor.js
new file mode 100644
--- /dev/null
+++ b/src/js/di/ValueDescriptor.js
@@ -0,0 +1,38 @@
+define([ "../declare", "./Descriptor", "../safe" ],
+
+function(declare, Descriptor, safe) {
+ return declare(Descriptor, {
+ _value : undefined,
+ _raw : false,
+ constructor : function(value, raw) {
+ this._value = value;
+ this._raw = Boolean(raw);
+ },
+
+ activate : function(context, name) {
+ context.enter(name, this);
+ var v = this._raw ? this._value : context.parse(
+ this._value,
+ ".params");
+ context.leave(this);
+ return v;
+ },
+
+ isInstanceCreated : function() {
+ return this._raw;
+ },
+
+ getInstance : function() {
+ if (!this._raw)
+ throw new Error("The instance isn't constructed");
+ return this._value;
+ },
+
+ toString : function() {
+ if (this._raw)
+ return "@value {raw}";
+ else
+ return safe.isNull(this._value) ? "@value " : "@value";
+ }
+ });
+});
\ No newline at end of file
diff --git a/src/js/log/ConsoleLogChannel.js b/src/js/log/ConsoleLogChannel.js
new file mode 100644
--- /dev/null
+++ b/src/js/log/ConsoleLogChannel.js
@@ -0,0 +1,30 @@
+define(
+ [ "dojo/_base/declare", "../text/format" ],
+ function(declare, format) {
+ return declare(
+ null,
+ {
+ name : null,
+
+ constructor : function(name) {
+ this.name = name;
+ },
+
+ log : function() {
+ console.log(this._makeMsg(arguments));
+ },
+
+ warn : function() {
+ console.warn(this._makeMsg(arguments));
+ },
+
+ error : function() {
+ console.error(this._makeMsg(arguments));
+ },
+
+ _makeMsg : function(args) {
+ return this.name ? this.name + " " +
+ format.apply(null, args) : format.apply(null, args);
+ }
+ });
+ });
\ No newline at end of file
diff --git a/src/js/log/_LogMixin.js b/src/js/log/_LogMixin.js
new file mode 100644
--- /dev/null
+++ b/src/js/log/_LogMixin.js
@@ -0,0 +1,67 @@
+define([ "dojo/_base/declare" ],
+
+function(declare) {
+ var cls = declare(null, {
+ _logChannel : null,
+
+ _logLevel : 1,
+
+ constructor : function(opts) {
+ if (typeof opts == "object") {
+ if ("logChannel" in opts)
+ this._logChannel = opts.logChannel;
+ if ("logLevel" in opts)
+ this._logLevel = opts.logLevel;
+ }
+ },
+
+ getLogChannel : function() {
+ return this._logChannel;
+ },
+
+ setLogChannel : function(v) {
+ this._logChannel = v;
+ },
+
+ getLogLevel : function() {
+ return this._logLevel;
+ },
+
+ setLogLevel : function(v) {
+ this._logLevel = v;
+ },
+
+ log : function(format) {
+ if (this._logChannel && this._logLevel > 2)
+ this._logChannel.log.apply(this._logChannel, arguments);
+ },
+ warn : function(format) {
+ if (this._logChannel && this._logLevel > 1)
+ this._logChannel.warn.apply(this._logChannel, arguments);
+ },
+ error : function(format) {
+ if (this._logChannel && this._logLevel > 0)
+ this._logChannel.error.apply(this._logChannel, arguments);
+ },
+
+ /**
+ * Used to by widgets
+ */
+ startup : function() {
+ var me = this, parent;
+ if (!me.getLogChannel()) {
+ parent = me;
+ while (parent = parent.getParent()) {
+ if (parent.getLogChannel) {
+ me.setLogChannel(parent.getLogChannel());
+ if(parent.getLogLevel)
+ me.setLogLevel(parent.getLogLevel());
+ break;
+ }
+ }
+ }
+ this.inherited(arguments);
+ }
+ });
+ return cls;
+});
\ No newline at end of file
diff --git a/src/js/log/listeners/console.js b/src/js/log/listeners/console.js
new file mode 100644
--- /dev/null
+++ b/src/js/log/listeners/console.js
@@ -0,0 +1,25 @@
+define([], function () {
+ if (console && console.log)
+ return function (ch, name, msg) {
+
+ var args = [ch + ":"];
+
+ switch (name) {
+ case "warn":
+ case "error":
+ case "log":
+ break;
+ default:
+ args.push(name + ":");
+ name = "log";
+ }
+
+
+ if (msg instanceof Array)
+ args.push.apply(args, msg);
+ else
+ args.push(msg);
+
+ console[name].apply(console, args);
+ };
+});
\ No newline at end of file
diff --git a/src/js/log/trace.js b/src/js/log/trace.js
new file mode 100644
--- /dev/null
+++ b/src/js/log/trace.js
@@ -0,0 +1,116 @@
+define(["../text/format"], function (format) {
+ 'use strict';
+
+ var listeners = [];
+ var channels = {};
+
+ var Trace = function (name) {
+ this.name = name;
+ this._subscribers = [];
+ };
+
+ Trace.prototype.debug = function () {
+ if (Trace.level >= 4)
+ this.notify("debug", format.apply(null, arguments));
+ };
+
+ Trace.prototype.log = function () {
+ if (Trace.level >= 3)
+ this.notify("log", format.apply(null, arguments));
+ };
+
+ Trace.prototype.warn = function () {
+ if (Trace.level >= 2)
+ this.notify("warn", format.apply(null, arguments));
+
+ };
+
+ Trace.prototype.error = function () {
+ if (Trace.level >= 1)
+ this.notify("error", format.apply(null, arguments));
+ };
+
+ Trace.prototype.notify = function (name, msg) {
+ var me = this;
+ me._subscribers.forEach(function (cb) {
+ cb(me, name, msg);
+ });
+ };
+
+ Trace.prototype.subscribe = function (cb) {
+ this._subscribers.push(cb);
+ };
+
+ Trace.prototype.toString = function () {
+ return this.name;
+ };
+
+ Trace.createChannel = function (type, name, cb) {
+ var chId = name;
+ if (channels[chId])
+ return channels[chId];
+
+ var channel = new type(chId);
+ channels[chId] = channel;
+
+ Trace._onNewChannel(chId, channel);
+ cb(channel);
+ };
+
+ Trace._onNewChannel = function (chId, ch) {
+ listeners.forEach(function (listener) {
+ listener(chId, ch);
+ });
+ };
+
+ Trace.on = function (filter, cb) {
+ if (arguments.length == 1) {
+ cb = filter;
+ filter = undefined;
+ }
+ var d, test;
+ if (filter instanceof RegExp) {
+ test = function (chId) {
+ return filter.test(chId);
+ };
+ } else if (filter instanceof Function) {
+ test = filter;
+ } else if (filter) {
+ test = function (chId) {
+ return chId == filter;
+ };
+ }
+
+ if (test) {
+ d = function(chId, ch) {
+ if(test(chId))
+ ch.subscribe(cb);
+ };
+ } else {
+ d = function(chId, ch) {
+ ch.subscribe(cb);
+ };
+ }
+ listeners.push(d);
+
+ for(var chId in channels)
+ d(chId,channels[chId]);
+ };
+
+ Trace.load = function (id, require, cb) {
+ if (id)
+ Trace.createChannel(Trace, id, cb);
+ else if (require.module && require.module.mid)
+ Trace.createChannel(Trace, require.module.mid, cb);
+ else
+ require(['module'], function (module) {
+ Trace.createChannel(Trace, module && module.id, cb);
+ });
+ };
+
+ Trace.dynamic = true;
+
+ Trace.level = 4;
+
+ return Trace;
+});
\ No newline at end of file
diff --git a/src/js/main.js b/src/js/main.js
new file mode 100644
--- /dev/null
+++ b/src/js/main.js
@@ -0,0 +1,3 @@
+declare([], function(){
+ // does nothing yet...
+});
\ No newline at end of file
diff --git a/src/js/messaging/Client.js b/src/js/messaging/Client.js
new file mode 100644
--- /dev/null
+++ b/src/js/messaging/Client.js
@@ -0,0 +1,61 @@
+define(
+ [ "dojo/_base/declare", "dojo/_base/lang", "dojo/Evented", "../log/_LogMixin" ],
+
+ function(declare, lang, Evented, _LogMixin) {
+ return declare([ Evented, _LogMixin ], {
+ _session : null,
+ _destination : null,
+ _id : null,
+
+ constructor : function(session, destination, options) {
+ this._destination = destination;
+ this._session = session;
+ },
+
+ getDestination : function() {
+ return this._destination;
+ },
+
+ start : function() {
+ var me = this;
+ return me._session.createClient(me.prepareOptions({})).then(
+ function(id) {
+ me._id = id;
+ return me;
+ });
+ },
+
+ prepareOptions : function(options) {
+ var me = this;
+ options.mode = me.getMode();
+ options.destination = me.getDestination();
+ options.client = function(msg) {
+ me.process(msg);
+ };
+ return options;
+ },
+
+ process : function(msg) {
+ this.warn("Messages are not acceped by this client");
+ },
+
+ stop : function() {
+ var me = this;
+ if (me._id) {
+ me.log("stop");
+ return me._session.deleteClient({'clientId': me._id}).then(function() {
+ me._id = null;
+ return me;
+ });
+ }
+ },
+
+ toString : function() {
+ return "["
+ + [
+ this.getMode().toUpperCase(),
+ this.getDestination(),
+ this._id ].join(',') + "]";
+ }
+ });
+ });
\ No newline at end of file
diff --git a/src/js/messaging/Destination.js b/src/js/messaging/Destination.js
new file mode 100644
--- /dev/null
+++ b/src/js/messaging/Destination.js
@@ -0,0 +1,34 @@
+define([ "dojo/_base/declare", "./Listener" ],
+
+function(declare, Listener) {
+ return declare(null, {
+ _session : null,
+ _destination : null,
+ _listenerClass : null,
+
+ constructor : function(session, destination, options) {
+ if (!session)
+ throw new Error("A session is required");
+ if (!destination)
+ throw new Error("A destination is required");
+
+ this._session = session;
+ this._destination = destination;
+ if (options) {
+ if (options.listenerClass)
+ this._listenerClass = options.listenerClass;
+ }
+ },
+
+ listen : function(callback) {
+ var factory = this._listenerClass || Listener;
+ var listener = new factory(this._session, this._destination, {
+ listener : callback
+ });
+ listener.start();
+
+ return listener;
+ }
+
+ });
+});
diff --git a/src/js/messaging/Listener.js b/src/js/messaging/Listener.js
new file mode 100644
--- /dev/null
+++ b/src/js/messaging/Listener.js
@@ -0,0 +1,64 @@
+define([ "dojo/_base/declare", "dojo/_base/lang", "./Client" ],
+
+function(declare, lang, Client) {
+ return declare([ Client ], {
+ _listener : null,
+
+ constructor : function(session, destination, options) {
+ if (!options || !options.listener)
+ throw new Error("A listener is required");
+ this._listener = options.listener;
+ if (options.transform)
+ this._transform = options.transform;
+ },
+
+ getMode : function() {
+ return "listener";
+ },
+
+ process : function(result) {
+ switch (result.type) {
+ case "message":
+ try {
+ this._handleMessage(result.message);
+ } catch (ex) {
+ var err = new Error("Failed to handle message");
+ err.envelope = result.message;
+ err.innerException = ex;
+ this._handleError(err);
+ }
+ break;
+ case "error":
+ this._handleError(result.error);
+ break;
+ }
+
+ },
+
+ _transform : function(envelope) {
+ return envelope;
+ },
+
+ _handleMessage : function(envelope) {
+ this.log(
+ "MESSAGE type = ${0}, headers = ${2}: ${1}",
+ envelope.bodyType,
+ envelope.body,
+ JSON.stringify(envelope.headers));
+ var data = this._transform(envelope);
+ this._listener(data);
+ this.emit("message", data);
+ },
+
+ _handleError : function(ex) {
+ if (ex.innerException)
+ this.error(
+ "ERROR: ${0} -> ${1}",
+ ex.message,
+ ex.innerException.message);
+ else
+ this.error("ERROR: ${0}", ex.message);
+ this.emit("error", ex);
+ }
+ });
+});
\ No newline at end of file
diff --git a/src/js/messaging/Session.js b/src/js/messaging/Session.js
new file mode 100644
--- /dev/null
+++ b/src/js/messaging/Session.js
@@ -0,0 +1,217 @@
+define(
+ [
+ "dojo/_base/declare",
+ "dojo/_base/lang",
+ "dojo/request",
+ "./Destination",
+ "dojo/Evented",
+ "dojo/Deferred",
+ "../log/_LogMixin" ],
+
+ function(declare, lang, request, Destination, Evented, Deferred, _LogMixin) {
+
+ var cls = declare(
+ [ Evented, _LogMixin ],
+ {
+ _id : null,
+ _baseUrl : null,
+ _destinations : null,
+ _timeout : 100000,
+ _clients : null,
+ _started : null,
+ _starting : false,
+
+ constructor : function(baseUrl, options) {
+ if (!baseUrl)
+ throw new Error("baseUrl is required");
+ options = options || {};
+
+ this._baseUrl = baseUrl.replace(/\/*$/, "");
+ this._destinations = {};
+ this._pending = [];
+ this._clients = {};
+ if (options.timeout)
+ this._timeout = options.timeout;
+
+ this._started = new Deferred();
+ },
+
+ start : function() {
+ if (this._starting)
+ return this._started;
+ this._starting = true;
+
+ var me = this;
+ me.log("START");
+ request(this._baseUrl, {
+ method : "POST",
+ handleAs : "json"
+ }).then(function(result) {
+ me._id = result;
+ me._emitConnected();
+ me._poll();
+ me._started.resolve(me);
+ }, function(error) {
+ me._emitError(error);
+ me._started.reject(me);
+ });
+ return me._started.promise;
+ },
+
+ createClient : function(options) {
+ if (!options || !options.destination || !options.mode)
+ throw new Error("Invalid argument");
+
+ var me = this;
+
+ return me._started
+ .then(function() {
+ var url = me._makeUrl(me._id);
+ me.log(
+ "CREATE mode=${0}, destination=${1}",
+ options.mode,
+ options.destination);
+
+ return request(url, {
+ method : "POST",
+ data : {
+ mode : options.mode,
+ destination : options.destination
+ },
+ handleAs : 'json'
+ })
+ .then(
+ function(id) {
+ me
+ .log(
+ "CLIENT id=${0}, mode=${1}, destination=${2}",
+ id,
+ options.mode,
+ options.destination);
+ me._clients[id] = options.client
+ ? options.client
+ : function(msg) {
+ me
+ .warn(
+ "The client id=${0}, mode=${1}, destination=${2} isn't accepting mesages",
+ id,
+ options.mode,
+ options.destination);
+ };
+ return id;
+ });
+ });
+
+ },
+
+ deleteClient : function(options) {
+ if (!options || !options.clientId)
+ throw new Error("Invalid argument");
+
+ var me = this, id = options.clientId;
+
+ return me._started.then(function() {
+ var url = me._makeUrl(me._id, options.clientId);
+
+ me.log("DELETE CLIENT ${0}", options.clientId);
+
+ return request(url, {
+ method : "DELETE",
+ handleAs : 'json'
+ }).then(function() {
+ me.log("CLIENT DELETED ${0}", options.clientId);
+ me._clients[id] = undefined;
+ });
+ });
+ },
+
+ _poll : function() {
+ var me = this, url = this._makeUrl(this._id);
+ me.log("POLL timeout=${0}", me._timeout);
+ request(url, {
+ method : "GET",
+ handleAs : "json",
+ query : {
+ timeout : me._timeout
+ }
+ }).then(function(response) {
+ me._handlePoll(response);
+ me._poll();
+ }, function(err) {
+ me.error("POLL faield with ${0}", err);
+ me._emitError(err);
+ });
+ },
+
+ _handlePoll : function(response) {
+ if (!response) {
+ this.log("POLL response undefined, looks like a bug");
+ return;
+ }
+ if (!response.results || !response.results.length) {
+ this.log("POLL response is empty");
+ return;
+ }
+
+ var results = response.results;
+ this.log("POLL got ${0} results", results.length);
+
+ for (var i = 0; i < results.length; i++) {
+ var result = results[i];
+ var client = this._clients[result.clientId];
+ if (!client) {
+ // TODO this could happen due to client isn't
+ // registered yet
+ this.error("Unknown client ${0}", result.clientId);
+ continue;
+ }
+ client.call(this, result);
+ }
+ },
+
+ _emitError : function(err) {
+ this.emit("error", err);
+ },
+
+ _emitConnected : function() {
+ var me = this;
+ me.log("CONNECTED");
+ me.emit("connected");
+ },
+
+ _makeUrl : function() {
+ var parts = [ this._baseUrl ];
+ for (var i = 0; i < arguments.length; i++)
+ parts.push(arguments[i].replace(/\/*$/, ""));
+ return parts.join('/');
+ },
+
+ queue : function(name) {
+ return this._getDestination("queue://" + name);
+ },
+
+ topic : function(name) {
+ return this._getDestination("topic://" + name);
+ },
+
+ _getDestination : function(uri) {
+ if (uri in this._destinations)
+ return this._destinations[uri];
+
+ var dest = new Destination(this, uri);
+ this._destinations[uri] = dest;
+ return dest;
+ },
+
+ toString : function() {
+ return [ "[", "SESSION ", this._id, "]" ].join(" ");
+ }
+ });
+
+ cls.connect = function(url, options) {
+ var session = new cls(url, options);
+ return session.start();
+ };
+
+ return cls;
+ });
diff --git a/src/js/safe.js b/src/js/safe.js
new file mode 100644
--- /dev/null
+++ b/src/js/safe.js
@@ -0,0 +1,323 @@
+define([],
+
+ function () {
+ var _create = Object.create,
+ _keys = Object.keys;
+
+ var safe = null;
+ safe = {
+ argumentNotNull: function (arg, name) {
+ if (arg === null || arg === undefined)
+ throw new Error("The argument " + name + " can't be null or undefined");
+ },
+
+ argumentNotEmptyString: function (arg, name) {
+ if (typeof (arg) !== "string" || !arg.length)
+ throw new Error("The argument '" + name + "' must be a not empty string");
+ },
+
+ argumentNotEmptyArray: function (arg, name) {
+ if (!(arg instanceof Array) || !arg.length)
+ throw new Error("The argument '" + name + "' must be a not empty array");
+ },
+
+ argumentOfType: function (arg, type, name) {
+ if (!(arg instanceof type))
+ throw new Error("The argument '" + name + "' type doesn't match");
+ },
+
+ isNull: function (arg) {
+ return (arg === null || arg === undefined);
+ },
+
+ isPrimitive: function (arg) {
+ return (arg === null || arg === undefined || typeof (arg) === "string" ||
+ typeof (arg) === "number" || typeof (arg) === "boolean");
+ },
+
+ isInteger: function (arg) {
+ return parseInt(arg) == arg;
+ },
+
+ isNumber: function (arg) {
+ return parseFloat(arg) == arg;
+ },
+
+ isString: function (val) {
+ return typeof (val) == "string" || val instanceof String;
+ },
+
+ isNullOrEmptyString: function (str) {
+ if (str === null || str === undefined ||
+ ((typeof (str) == "string" || str instanceof String) && str.length === 0))
+ return true;
+ },
+
+ isNotEmptyArray: function (arg) {
+ return (arg instanceof Array && arg.length > 0);
+ },
+
+ /**
+ * Выполняет метод для каждого элемента массива, останавливается, когда
+ * либо достигнут конец массива, либо функция cb вернула
+ * значение.
+ *
+ * @param{Array | Object} obj массив элементов для просмотра
+ * @param{Function} cb функция, вызываемая для каждого элемента
+ * @param{Object} thisArg значение, которое будет передано в качестве
+ * this в cb .
+ * @returns Результат вызова функции cb , либо undefined
+ * если достигнут конец массива.
+ */
+ each: function (obj, cb, thisArg) {
+ safe.argumentNotNull(cb, "cb");
+ var i, x;
+ if (obj instanceof Array) {
+ for (i = 0; i < obj.length; i++) {
+ x = cb.call(thisArg, obj[i], i);
+ if (x !== undefined)
+ return x;
+ }
+ } else {
+ var keys = _keys(obj);
+ for (i = 0; i < keys.length; i++) {
+ var k = keys[i];
+ x = cb.call(thisArg, obj[k], k);
+ if (x !== undefined)
+ return x;
+ }
+ }
+ },
+
+ /**
+ * Копирует свойства одного объекта в другой.
+ *
+ * @param{Any} dest объект в который нужно скопировать значения
+ * @param{Any} src источник из которого будут копироваться значения
+ * @tmpl{Object|Array} tmpl шаблон по которому будет происходить
+ * копирование. Если шаблон является массивом
+ * (список свойств), тогда значения этого массива
+ * являются именами свойсвт которые будут
+ * скопированы. Если шаблон является объектом (карта
+ * преобразования имен свойств src->dst), тогда
+ * копирование будет осуществляться только
+ * собственных свойств источника, присутсвующих в
+ * шаблоне, при этом значение свойства шаблона
+ * является именем свойства в которое будет
+ * произведено коприрование
+ */
+ mixin: function (dest, src, tmpl) {
+ safe.argumentNotNull(dest, "dest");
+ if (!src)
+ return dest;
+
+ var keys, i, p;
+ if (arguments.length < 3) {
+ keys = _keys(src);
+ for (i = 0; i < keys.length; i++) {
+ p = keys[i];
+ dest[p] = src[p];
+ }
+ } else {
+ if (tmpl instanceof Array) {
+ for (i = 0; i < tmpl.length; i++) {
+ p = tmpl[i];
+ if (p in src)
+ dest[p] = src[p];
+ }
+
+ } else {
+ keys = _keys(src);
+ for (i = 0; i < keys.length; i++) {
+ p = keys[i];
+ if (p in tmpl)
+ dest[tmpl[p]] = src[p];
+ }
+ }
+ }
+ return dest;
+ },
+
+ /** Wraps the specified function to emulate an asynchronous execution.
+ * @param{Object} thisArg [Optional] Object which will be passed as 'this' to the function.
+ * @param{Function|String} fn [Required] Function wich will be wrapped.
+ */
+ async: function (fn, thisArg) {
+ if (arguments.length == 2 && !(fn instanceof Function))
+ fn = thisArg[fn];
+
+ if (fn == null)
+ throw new Error("The function must be specified");
+
+ function wrapresult(x, e) {
+ if (e) {
+ return {
+ then: function (cb, eb) {
+ try {
+ return eb ? wrapresult(eb(e)) : this;
+ } catch (e2) {
+ return wrapresult(null, e2);
+ }
+ }
+ };
+ } else {
+ if (x && x.then)
+ return x;
+ return {
+ then : function(cb) {
+ try {
+ return cb ? wrapresult(cb(x)) : this;
+ } catch(e2) {
+ return wrapresult(e2);
+ }
+ }
+ };
+ }
+ }
+
+ try {
+ return wrapresult(fn.apply(thisArg, arguments));
+ } catch (e) {
+ return wrapresult(null, e);
+ };
+ },
+
+ create: function () {
+ if (console && console.warn)
+ console.warn("implab/safe::create is deprecated use Object.create instead");
+ _create.apply(this, arguments);
+ },
+
+ delegate: function (target, method) {
+ if (!(method instanceof Function)) {
+ this.argumentNotNull(target, "target");
+ method = target[method];
+ }
+
+ if (!(method instanceof Function))
+ throw new Error("'method' argument must be a Function or a method name");
+
+ return function () {
+ return method.apply(target, arguments);
+ };
+ },
+
+ /**
+ * Для каждого элемента массива вызывает указанную функцию и сохраняет
+ * возвращенное значение в массиве результатов.
+ *
+ * @remarks cb может выполняться асинхронно, при этом одновременно будет
+ * только одна операция.
+ *
+ * @async
+ */
+ pmap: function (items, cb) {
+ safe.argumentNotNull(cb, "cb");
+
+ if (items && items.then instanceof Function)
+ return items.then(function (data) {
+ return safe.pmap(data, cb);
+ });
+
+ if (safe.isNull(items) || !items.length)
+ return items;
+
+ var i = 0,
+ result = [];
+
+ function next() {
+ var r, ri;
+
+ function chain(x) {
+ result[ri] = x;
+ return next();
+ }
+
+ while (i < items.length) {
+ r = cb(items[i], i);
+ ri = i;
+ i++;
+ if (r && r.then) {
+ return r.then(chain);
+ } else {
+ result[ri] = r;
+ }
+ }
+ return result;
+ }
+
+ return next();
+ },
+
+ /**
+ * Для каждого элемента массива вызывает указанную функцию, результаты
+ * не сохраняются
+ *
+ * @remarks cb может выполняться асинхронно, при этом одновременно будет
+ * только одна операция.
+ * @async
+ */
+ pfor: function (items, cb) {
+ safe.argumentNotNull(cb, "cb");
+
+ if (items && items.then instanceof Function)
+ return items.then(function (data) {
+ return safe.pmap(data, cb);
+ });
+
+ if (safe.isNull(items) || !items.length)
+ return items;
+
+ var i = 0;
+
+ function next() {
+ while (i < items.length) {
+ var r = cb(items[i], i);
+ i++;
+ if (r && r.then)
+ return r.then(next);
+ }
+ }
+
+ return next();
+ },
+
+ /**
+ * Выбирает первый элемент из последовательности, или обещания, если в
+ * качестве параметра используется обещание, оно должно вернуть массив.
+ *
+ * @param{Function} cb обработчик результата, ему будет передан первый
+ * элемент последовательности в случае успеха
+ * @param{Fucntion} err обработчик исключения, если массив пустой, либо
+ * не массив
+ *
+ * @remarks Если не указаны ни cb ни err, тогда функция вернет либо
+ * обещание, либо первый элемент.
+ * @async
+ */
+ first: function (sequence, cb, err) {
+ if (sequence) {
+ if (sequence.then instanceof Function) {
+ return sequence.then(function (res) {
+ return safe.first(res, cb, err);
+ }, err);
+ } else if (sequence && "length" in sequence) {
+ if (sequence.length === 0) {
+ if (err)
+ return err(new Error("The sequence is empty"));
+ else
+ throw new Error("The sequence is empty");
+ }
+ return cb ? cb(sequence[0]) : sequence[0];
+ }
+ }
+
+ if (err)
+ return err(new Error("The sequence is required"));
+ else
+ throw new Error("The sequence is required");
+ }
+ };
+
+ return safe;
+ });
\ No newline at end of file
diff --git a/src/js/text/format-compile.js b/src/js/text/format-compile.js
new file mode 100644
--- /dev/null
+++ b/src/js/text/format-compile.js
@@ -0,0 +1,101 @@
+define(
+ [],
+ function() {
+ var map = {
+ "\\{" : "&curlopen;",
+ "\\}" : "&curlclose;",
+ "&" : "&",
+ "\\:" : ":"
+ };
+
+ var rev = {
+ curlopen : "{",
+ curlclose : "}",
+ amp : "&",
+ colon : ":"
+ };
+
+ var espaceString = function(s) {
+ if (!s)
+ return s;
+ return "'" + s.replace(/('|\\)/g, "\\$1") + "'";
+ };
+
+ var encode = function(s) {
+ if (!s)
+ return s;
+ return s.replace(/\\{|\\}|&|\\:/g, function(m) {
+ return map[m] || m;
+ });
+ };
+
+ var decode = function(s) {
+ if (!s)
+ return s;
+ return s.replace(/&(\w+);/g, function(m, $1) {
+ return rev[$1] || m;
+ });
+ };
+
+ var subst = function(s) {
+ var i = s.indexOf(":"), name, pattern;
+ if (i >= 0) {
+ name = s.substr(0, i);
+ pattern = s.substr(i + 1);
+ } else {
+ name = s;
+ }
+
+ if (pattern)
+ return [
+ espaceString(decode(name)),
+ espaceString(decode(pattern)) ];
+ else
+ return [ espaceString(decode(name)) ];
+ };
+
+ var compile = function(str) {
+ if (!str)
+ return function() {};
+
+ var chunks = encode(str).split("{"), chunk;
+
+ var code = [ "var result=[];" ];
+
+ for (var i = 0; i < chunks.length; i++) {
+ chunk = chunks[i];
+
+ if (i === 0) {
+ if (chunk)
+ code.push("result.push(" + espaceString(decode(chunk)) +
+ ");");
+ } else {
+ var len = chunk.indexOf("}");
+ if (len < 0)
+ throw new Error("Unbalanced substitution #" + i);
+
+ code.push("result.push(subst(" +
+ subst(chunk.substr(0, len)).join(",") + "));");
+ if (chunk.length > len + 1)
+ code.push("result.push(" +
+ espaceString(decode(chunk.substr(len + 1))) + ");");
+ }
+ }
+
+ code.push("return result.join('');");
+
+ /* jshint -W054 */
+ return new Function("subst", code.join("\n"));
+ };
+
+ var cache = {};
+
+ return function(template) {
+ var compiled = cache[template];
+ if (!compiled) {
+ compiled = compile(template);
+ cache[template] = compiled;
+ }
+ return compiled;
+ };
+ });
\ No newline at end of file
diff --git a/src/js/text/format.js b/src/js/text/format.js
new file mode 100644
--- /dev/null
+++ b/src/js/text/format.js
@@ -0,0 +1,87 @@
+define([
+ "../safe",
+ "./format-compile",
+ "dojo/number",
+ "dojo/date/locale",
+ "dojo/_base/array" ], function(safe, compile, number, date, array) {
+
+ // {short,medium,full,long}-{date,time}
+ var convert = function(value, pattern) {
+ if (!pattern)
+ return value.toString();
+
+ if (pattern.toLocaleLowerCase() == "json") {
+ var cache = [];
+ return JSON.stringify(value, function(k, v) {
+ if (!safe.isPrimitive(v)) {
+ var id = array.indexOf(cache, v);
+ if (id >= 0)
+ return "@ref-" + id;
+ else
+ return v;
+ } else {
+ return v;
+ }
+ },2);
+ }
+
+ if (safe.isNumber(value)) {
+ var nopt = {};
+ if (pattern.indexOf("!") === 0) {
+ nopt.round = -1;
+ pattern = pattern.substr(1);
+ }
+ nopt.pattern = pattern;
+ return number.format(value, nopt);
+ } else if (value instanceof Date) {
+ var m = pattern.match(/^(\w+)-(\w+)$/);
+ if (m)
+ return date.format(value, {
+ selector : m[2],
+ formatLength : m[1]
+ });
+ else if (pattern == "iso")
+ return value.toISOString();
+ else
+ return date.format(value, {
+ selector : "date",
+ datePattern : pattern
+ });
+ } else {
+ return value.toString(pattern);
+ }
+ };
+
+ function formatter(format) {
+ var data;
+
+ if (arguments.length <= 1)
+ return format;
+
+ data = Array.prototype.slice.call(arguments, 1);
+
+ var template = compile(format);
+
+ return template(function(name, pattern) {
+ var value = data[name];
+ return !safe.isNull(value) ? convert(value, pattern) : "";
+ });
+ }
+
+ formatter.compile = function(format) {
+ var template = compile(format);
+
+ return function() {
+ var data = arguments;
+
+ return template(function(name, pattern) {
+ var value = data[name];
+ return !safe.isNull(value) ? convert(value, pattern) : "";
+ });
+ };
+ };
+
+ formatter.convert = convert;
+
+ return formatter;
+});
\ No newline at end of file
diff --git a/src/js/text/template-compile.js b/src/js/text/template-compile.js
new file mode 100644
--- /dev/null
+++ b/src/js/text/template-compile.js
@@ -0,0 +1,134 @@
+define(
+ ["dojo/request", "./format", "../log/trace!"],
+ function (request, format, trace) {
+
+ // разбивает строку шаблона на токены, возвращает контекст для
+ // дальнейшей обработки в visitTemplate
+ var parseTemplate = function (str) {
+ var tokens = str.split(/(<%=|\[%=|<%|\[%|%\]|%>)/);
+ var pos = -1;
+ var data = [],
+ code = [];
+
+ return {
+ next: function () {
+ pos++;
+ return pos < tokens.length;
+ },
+ token: function () {
+ return tokens[pos];
+ },
+ pushData: function () {
+ var i = data.length;
+ data.push.apply(data, arguments);
+ return i;
+ },
+ pushCode : function() {
+ var i = code.length;
+ code.push.apply(code, arguments);
+ return i;
+ },
+ compile: function () {
+ var text = "var $p = [];\n" +
+ "var print = function(){\n" +
+ " $p.push(format.apply(null,arguments));\n" +
+ "};\n" +
+ // Introduce the data as local variables using with(){}
+ "with(obj){\n" +
+ code.join("\n") +
+ "}\n" +
+ "return $p.join('');";
+
+ try {
+ var compiled = new Function("obj, format, $data", text);
+ /**
+ * Функция форматирования по шаблону
+ *
+ * @type{Function}
+ * @param{Object} obj объект с параметрами для подстановки
+ */
+ return function (obj) {
+ return compiled(obj || {}, format, data);
+ };
+ } catch (e) {
+ trace.error([e]);
+ trace.log([text, data]);
+ throw e;
+ }
+ }
+ }
+ };
+
+ function visitTemplate(context) {
+ while (context.next()) {
+ switch (context.token()) {
+ case "<%":
+ case "[%":
+ visitCode(context);
+ break;
+ case "<%=":
+ case "[%=":
+ visitInline(context);
+ break;
+ default:
+ visitTextFragment(context);
+ break;
+ }
+ }
+ }
+
+ function visitInline(context) {
+ var code = ["$p.push("];
+ while (context.next()) {
+ if (context.token() == "%>" || context.token() == "%]")
+ break;
+ code.push(context.token());
+ }
+ code.push(");");
+ context.pushCode(code.join(''));
+ }
+
+ function visitCode(context) {
+ var code = [];
+ while (context.next()) {
+ if (context.token() == "%>" || context.token() == "%]")
+ break;
+ code.push(context.token());
+ }
+ context.pushCode(code.join(''));
+ }
+
+ function visitTextFragment(context) {
+ var i = context.pushData(context.token());
+ context.pushCode("$p.push($data["+i+"]);");
+ }
+
+ var compile = function (str) {
+ if (!str)
+ return function() { return "";};
+
+ var ctx = parseTemplate(str);
+ visitTemplate(ctx);
+ return ctx.compile();
+ };
+
+ var cache = {};
+
+ compile.load = function (id, require, callback) {
+ var url = require.toUrl(id);
+ if (url in cache) {
+ callback(cache[url]);
+ } else {
+ request(url).then(compile).then(function (tc) {
+ callback(cache[url] = tc);
+ }, function (err) {
+ require.signal("error", [{
+ error: err,
+ src: 'implab/text/template-compile'
+ }]);
+ });
+ }
+ };
+
+ return compile;
+ });
\ No newline at end of file