@plotdb/registry 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/route.js ADDED
@@ -0,0 +1,81 @@
1
+ (function(){
2
+ var pthk, lderror, fs, handle, route;
3
+ pthk = require('pthk');
4
+ lderror = require('lderror');
5
+ fs = require("fs-extra");
6
+ handle = function(arg$){
7
+ var provider, id, root, ref$, paths, obj;
8
+ provider = arg$.provider, id = arg$.id, root = arg$.root;
9
+ ref$ = [{}, {}, pthk.rectify(id)], paths = ref$[0], obj = ref$[1], id = ref$[2];
10
+ return Promise.resolve().then(function(){
11
+ var ids;
12
+ if (!/^[-_a-zA-Z0-9@./]+$/.exec(id)) {
13
+ return lderror.reject(404);
14
+ }
15
+ ids = id.split('/');
16
+ import$(obj, ids.length > 3
17
+ ? {
18
+ name: ids[0] + "/" + ids[1],
19
+ version: ids[2],
20
+ path: ids.slice(3).join('/')
21
+ }
22
+ : {
23
+ name: ids[0],
24
+ version: ids[1],
25
+ path: ids.slice(2).join('/')
26
+ });
27
+ if (!(obj.name && obj.version && obj.path)) {
28
+ return lderror.reject(404);
29
+ }
30
+ return provider.fetch({
31
+ root: root.fs,
32
+ name: obj.name,
33
+ version: obj.version,
34
+ force: false,
35
+ cachetime: 60 * 60
36
+ });
37
+ })['catch'](function(e){
38
+ if (lderror.id(e) === 998) {
39
+ return;
40
+ }
41
+ if (lderror.id(e) !== 404) {
42
+ return Promise.reject(e);
43
+ }
44
+ return lderror.reject(404);
45
+ });
46
+ };
47
+ route = function(arg$){
48
+ var provider, root;
49
+ provider = arg$.provider, root = arg$.root;
50
+ if (!root.pub.endsWith('/')) {
51
+ root.pub = root.pub + "/";
52
+ }
53
+ return function(req, res){
54
+ var url, id;
55
+ url = req.originalUrl;
56
+ id = url.replace(root.pub, '').replace(/[#?].*$/, '');
57
+ return handle({
58
+ provider: provider,
59
+ id: id,
60
+ root: root
61
+ }).then(function(){
62
+ res.set({
63
+ "X-Accel-Redirect": pthk.join(root.internal, id)
64
+ });
65
+ return res.send();
66
+ })['catch'](function(e){
67
+ if (lderror.id(e) !== 404) {
68
+ console.log(e);
69
+ res.status(500).send();
70
+ }
71
+ return res.status(404).send();
72
+ });
73
+ };
74
+ };
75
+ module.exports = route;
76
+ function import$(obj, src){
77
+ var own = {}.hasOwnProperty;
78
+ for (var key in src) if (own.call(src, key)) obj[key] = src[key];
79
+ return obj;
80
+ }
81
+ }).call(this);
package/dist/unbox.js ADDED
@@ -0,0 +1,70 @@
1
+ (function(){
2
+ var yauzl, tar, pthk, stream, fs, unzip, untar;
3
+ yauzl = require('yauzl');
4
+ tar = require('tar');
5
+ pthk = require('pthk');
6
+ stream = require('stream');
7
+ fs = require("fs-extra");
8
+ unzip = function(arg$){
9
+ var path, buf;
10
+ path = arg$.path, buf = arg$.buf;
11
+ return new Promise(function(res, rej){
12
+ return yauzl.fromBuffer(buf, {
13
+ autoClose: false,
14
+ lazyEntries: true
15
+ }, function(e, zipfile){
16
+ if (e) {
17
+ return rej(e);
18
+ }
19
+ zipfile.readEntry();
20
+ zipfile.on('end', function(){
21
+ zipfile.close();
22
+ return res();
23
+ });
24
+ return zipfile.on('entry', function(entry){
25
+ if (/\/$/.test(entry.fileName)) {
26
+ return zipfile.readEntry();
27
+ }
28
+ return zipfile.openReadStream(entry, function(e, rs){
29
+ var dirs, fn, desfile, desdir;
30
+ if (e) {
31
+ return rej(e);
32
+ }
33
+ rs.on('end', function(){
34
+ return zipfile.readEntry();
35
+ });
36
+ dirs = entry.fileName.split('/');
37
+ if (!(fn = dirs.slice(1).join('/'))) {
38
+ fn = entry.fileName;
39
+ }
40
+ desfile = pthk.join(path.base.version, pthk.rectify(fn));
41
+ desdir = pthk.dirname(desfile);
42
+ return fs.ensureDir(desdir).then(function(){
43
+ return rs.pipe(fs.createWriteStream(desfile));
44
+ });
45
+ });
46
+ });
47
+ });
48
+ });
49
+ };
50
+ untar = function(arg$){
51
+ var path, buf, ws;
52
+ path = arg$.path, buf = arg$.buf;
53
+ stream.Readable.from(buf).pipe(ws = tar.x({
54
+ strip: 1,
55
+ cwd: path.base.version
56
+ }));
57
+ return new Promise(function(res, rej){
58
+ ws.on('close', function(){
59
+ return res();
60
+ });
61
+ return ws.on('error', function(it){
62
+ return rej(it);
63
+ });
64
+ });
65
+ };
66
+ module.exports = {
67
+ unzip: unzip,
68
+ untar: untar
69
+ };
70
+ }).call(this);
package/doc/design.md ADDED
@@ -0,0 +1,68 @@
1
+ ## Module Naming
2
+
3
+ similar to `npm`, with a repo name and optional scope:
4
+
5
+ `@scope/repo`
6
+
7
+ for example:
8
+
9
+ `wrap-svg-text`
10
+ `@plotdb/form`
11
+
12
+ where names contain only [a-z-.] characters, and is case insensitive ( or, all lowercase characters ).
13
+
14
+ Naming should
15
+
16
+
17
+ ## Module Grouping
18
+
19
+ Use `.` in module name for semantic grouping:
20
+
21
+ - base library: `@plotdb/form`
22
+ - widgets
23
+ - `@plotdb/form.short-answer`
24
+ - `@plotdb/form.long-answer`
25
+
26
+ These modules ( `@plotdb/form`, `@plotdb/form.short-answer`, `@plotdb/form.long-answer` ) are independent modules and have their own repo and version. Grouping is just a semantic suggestion and there won't any checks against it.
27
+
28
+
29
+ ## Module Reference
30
+
31
+ Reference to module is possible with additional information or URL:
32
+
33
+ - `github:loadingio/ldcover`
34
+ - `https://plotdb.github.io/form/block/short-answer/0.0.1/index.html`
35
+
36
+ A formal definition of a reference to a module / a module's file can be done by following object:
37
+
38
+ {
39
+ ns: "namespace",
40
+ name: "module-name",
41
+ version: "0.0.1",
42
+ path: "path/some-file" /* optional path to file. default `index.html` if omitted. */
43
+ /* similar to web server rules, `path` may refer to `path/index.html`. */
44
+ }
45
+
46
+
47
+ ## Registry service
48
+
49
+ `@plotdb/registry` is also a concept of on demend module provider. It can be implemented with 2 parts:
50
+
51
+ - web server which maps URL to file, or fallback to an api server which helps in prepraing the requested module.
52
+ - an api server that prepares request modules
53
+
54
+
55
+ For example, we can setup a nginx server to serve module files as follow:
56
+
57
+ - accept requests of module in `https://site/assets/lib/<name>/<version>/<path>`
58
+ - try files `/<rootdir>/static/assets/lib/<name>/<version>/<path>`
59
+ - if file is not found, pass this request to api server.
60
+
61
+ Then in the api server:
62
+
63
+ - fetch the requested files from public registries such as github, npm or other cdn
64
+ - write downloaded files in `/<rootdir>/static/assets/lib/<name>/<version>/<path>`
65
+
66
+ It's also possible that the api server uses symlinks for semver rules to speed up assets requests. In this case, registry should properly manage these symlink to reflect the most up-to-date status of modules - for example, provide a trigger which flushes these symlinks by request.
67
+
68
+
package/doc/draft.md ADDED
@@ -0,0 +1,98 @@
1
+ ## 模組管理
2
+
3
+ `@plotdb/block` 概念有了以後, 會需要管理
4
+
5
+ - 開發 - 不管怎麼開發.
6
+ - 但 plotdb 自己會透過 git + branch + tag 來在 repo 自行管理版本
7
+ - 也有可能會需要將多個 block 置於一 monorepo 中一次做 publish
8
+ - 發布 - 類似 NPM. 指定名稱、版號.
9
+ - 倉儲 - 背後管理機制?
10
+ - 本地端 - 自己跑一個 registrey server ?
11
+ - 可以依靠簡單 http server 機制 serve 檔案
12
+ - 依簡單 http server 的本地發布法
13
+ - 比方說發布到特定目錄
14
+ - 或發布到本地端的中央 registry server
15
+
16
+
17
+ ## 命名規則
18
+
19
+ 與 github, npm 對齊. 使用 type, scope + package 的概念:
20
+
21
+ - wrap-svg-text
22
+ - @plotdb/form
23
+ - github:loadingio/ldcover
24
+
25
+
26
+ 考慮到前端元件可能有群組概念, 但我們又需要依賴現有機制管理, 因此我們在 package name 中利用 `.` 做語意上的分組:
27
+
28
+ - form.short-answer
29
+ - @plotdb/config.text
30
+ - github:loadingio/ldcover.error
31
+
32
+ 不一定是功能上 ( 比方說都是圖表 ), 也可能是單純的集合 ( makeweb 的基本區塊集 ), 這種情況下更像是認知上的輔助:
33
+
34
+ - @makeweb/basic.hero
35
+ - @makeweb/basic.paragraph
36
+ - @makeweb/basic.gallery
37
+ - @makeweb/basic.footer
38
+
39
+
40
+ 其它的選擇各有其問題.
41
+
42
+ - 使用子套件 ( @plotdb/form/short-answer )
43
+ - npm 跟 github 都不支援
44
+ - 若當成 @plotdb/form 下的 short-answer 檔案, 則版本就變成透過 @plotdb/form 管理, 會變得相依性很強, 造成問題.
45
+ - 使用 `@` ( @plotdb/form@short-ansmwer ) 或其它少見字元
46
+ - github 不支援. npm 不明, 但沒見過.
47
+ - 使用 `-` 或 `_` - 名稱太普遍.
48
+ - 使用 org 切分, 如 @plotdb-form/short-answer
49
+ - 語意較差因為實際上並沒有多出一個 @plotdb-form org.
50
+
51
+
52
+ ## 內部模組
53
+
54
+ 使用模組的套件, 不一定會全都依賴外部模組, 或者需要將所有模組都獨立管理. 套件本身也可能包含數個模組, 隨著套件本身進版.
55
+ 這種情況下, 就可以透過子元件的方式存取模組, 如:
56
+
57
+ @plotdb/form@0.0.1/short-answer/
58
+
59
+
60
+ 存取這類的模組可以有幾種做法:
61
+
62
+ - 完全繞過 registry, 自行管理 block.class
63
+ - 但若需要提供抽換機制, 我們還是得統一 "自行管理" 的方式 - 結果最好還是把機制做在 registry 中.
64
+ - 透過 registry, 但提供路徑概念.
65
+ - 如: `registry: ({name, version, path}) -> "/block/#name/#version/#path/index.html"`
66
+ - 接著就看套件如何將需求對應到 name, version, path 組
67
+
68
+ 透過 registry 的情況下, 如使用 @plotdb/config 時我們會有 text field. 可以想像存取路徑為:
69
+
70
+ @plotdb/config@0.0.1/text/index.html
71
+
72
+ 用戶則可能可以客製 text field, 並以下列套件名提供
73
+
74
+ @someone/config.text@.0.1
75
+ @someone/config.set@0.0.1/text/index.html
76
+
77
+ 在 @plotdb/config 使用 text 時, 可以直接明確指定模組, 亦或者做轉換. 轉換則由用戶提供方式:
78
+
79
+ text -> @someone/config.set@0.0.1/text/index.html
80
+
81
+ 也就是說, 套件提供一組預設轉換函式將 {name, version, type} 轉成 registry 要用的 {name, version, path}, 但這個預設函式可以被用戶客製. 如:
82
+
83
+ name: @plotdb/config -> name: @plotdb/config
84
+ version: 0.0.1 -> version: 0.0.1
85
+ type: text -> path: text/index.html
86
+
87
+ 客製後:
88
+
89
+ name: @plotdb/config -> name: @someone/config.text
90
+ version: 0.0.1 -> version: 0.0.1
91
+ type: text -> path: index.html
92
+
93
+
94
+ 指涉特定 block 的方式則為:
95
+
96
+ {name, version, path}
97
+
98
+ 忽略 path 時, 預設為 `index.html`. ( 或者, 依網頁伺服器定義? )
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "author": "zbryikt",
3
+ "name": "@plotdb/registry",
4
+ "license": "MIT",
5
+ "description": "registry",
6
+ "version": "0.0.1",
7
+ "main": "./dist/index.js",
8
+ "homepage": "https://github.com/plotdb/registry",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/plotdb/registry"
12
+ },
13
+ "engines": {
14
+ "node": ">=10.14.1",
15
+ "npm": ">=6.4.1"
16
+ },
17
+ "scripts": {
18
+ "start": "./node_modules/.bin/lsc web/server.ls"
19
+ },
20
+ "bin": {
21
+ "registry-ngx": "./bin/ngxgen"
22
+ },
23
+ "dependencies": {
24
+ "@zbryikt/template": "^2.3.33",
25
+ "fs-extra": "^8.1.0",
26
+ "js-yaml": "^4.1.0",
27
+ "lderror": "^2.3.2",
28
+ "livescript": "^1.6.0",
29
+ "node-fetch": "^2.6.7",
30
+ "pthk": "^0.0.1",
31
+ "request": "^2.88.2",
32
+ "tar": "^6.1.11",
33
+ "template-text": "^0.1.2",
34
+ "yargs": "^17.6.0",
35
+ "yauzl": "^2.10.0"
36
+ },
37
+ "devDependencies": {
38
+ "@loadingio/bootstrap.ext": "^0.0.9",
39
+ "@loadingio/debounce.js": "^1.0.1",
40
+ "@loadingio/ldquery": "^3.0.4",
41
+ "@plotdb/block": "^4.6.2",
42
+ "@plotdb/csscope": "^4.0.8",
43
+ "@plotdb/rescope": "^4.1.7",
44
+ "bootstrap": "^4.6.1",
45
+ "bootstrap.native": "^3.0.14",
46
+ "fedep": "^1.1.7",
47
+ "ldcover": "^3.3.0",
48
+ "ldloader": "^3.0.2",
49
+ "ldview": "^1.3.0",
50
+ "proxise": "^1.0.1"
51
+ },
52
+ "frontendDependencies": {
53
+ "root": "web/static/assets/lib",
54
+ "modules": [
55
+ "@loadingio/bootstrap.ext",
56
+ "@loadingio/debounce.js",
57
+ "@loadingio/ldquery",
58
+ "bootstrap",
59
+ "bootstrap.native",
60
+ "@plotdb/rescope",
61
+ "@plotdb/csscope",
62
+ "@plotdb/block",
63
+ "ldcover",
64
+ "ldloader",
65
+ "ldview",
66
+ "proxise"
67
+ ]
68
+ }
69
+ }
@@ -0,0 +1,54 @@
1
+ upstream apiserver {
2
+ server 127.0.0.1:9900;
3
+ }
4
+
5
+ proxy_cache_path /tmp/cache keys_zone=cache:10m levels=1:2 inactive=600s max_size=100m;
6
+
7
+ server {
8
+ listen 80;
9
+ server_name registry.loco;
10
+
11
+ # this should be put outside server block, where `<cache>` should be the same with `cache.name` config.
12
+ # proxy_cache_path /tmp/cache keys_zone=<cache>:10m levels=1:2 inactive=600s max_size=100m;
13
+
14
+ # requests to path under `internal` are from `X-Accel-Redirect` from registry backend
15
+ # and thus should not hit backend again.
16
+
17
+
18
+ location ~ ^/ilib/(.*)$ {
19
+ internal;
20
+ root /var/lib/cdn/cache/;
21
+ try_files /lib/$1 /lib/$1/index.html /$1/index.min.js =404;
22
+ }
23
+
24
+ location ~ ^/lib/(.*)$ {
25
+ root /var/lib/cdn/cache/;
26
+ # proxy_cache is file-based. here we use `.reg.404` for pkg-based 404 detection
27
+ # however, we don't know how to invalidate this. So this is not used for now.
28
+ # to use this, we have to use location pattern such as:
29
+ #
30
+ # location ~ ^/lib/(?<scope>.+)/(?<name>.+)/(?<version>.+)/(?<path>.*)$ { ... }
31
+ # location ~ ^/lib/(?<name>.+)/(?<version>.+)/(?<path>.*)$ { ... }
32
+ #
33
+ # if (-f /var/lib/cdn/cache/lib/$name/$version/.reg.404) {
34
+ # return 404 "";
35
+ # break;
36
+ # }
37
+ try_files /lib/$1 /lib/$1/index.html /lib/$1/index.min.js @registry_backend;
38
+ }
39
+
40
+ # a dedicated location for registry_backend so we can use a dedicated server for registry
41
+ # to offload requests from main backend. This is controlled by `upstream` config.
42
+ location @registry_backend {
43
+ proxy_set_header X-Real-IP $remote_addr;
44
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
45
+ proxy_set_header Host $http_host;
46
+ proxy_set_header X-NginX-Proxy true;
47
+ proxy_set_header X-Forwarded-Proto $scheme;
48
+ # cache 200 / 404 result for `cache-period` so user can't bombard our backend
49
+ proxy_cache cache;
50
+ proxy_cache_valid 200 404 10m;
51
+ proxy_pass http://apiserver;
52
+ }
53
+
54
+ }
@@ -0,0 +1,7 @@
1
+ internal: ilib
2
+ pub: lib
3
+ root: /var/lib/cdn/cache/
4
+ upstream: apiserver
5
+ cache:
6
+ name: cache
7
+ period: 10m
package/src/config.ngx ADDED
@@ -0,0 +1,43 @@
1
+
2
+ # this should be put outside server block, where `<cache>` should be the same with `cache.name` config.
3
+ # proxy_cache_path /tmp/cache keys_zone=<cache>:10m levels=1:2 inactive=600s max_size=100m;
4
+
5
+ # requests to path under `internal` are from `X-Accel-Redirect` from registry backend
6
+ # and thus should not hit backend again.
7
+
8
+
9
+ location ~ ^/!{internal}/(.*)$ {
10
+ internal;
11
+ root !{root};
12
+ try_files /!{pub}/$1 /!{pub}/$1/index.html /$1/index.min.js =404;
13
+ }
14
+
15
+ location ~ ^/!{pub}/(.*)$ {
16
+ root !{root};
17
+ # proxy_cache is file-based. here we use `.reg.404` for pkg-based 404 detection
18
+ # however, we don't know how to invalidate this. So this is not used for now.
19
+ # to use this, we have to use location pattern such as:
20
+ #
21
+ # location ~ ^/lib/(?<scope>.+)/(?<name>.+)/(?<version>.+)/(?<path>.*)$ { ... }
22
+ # location ~ ^/lib/(?<name>.+)/(?<version>.+)/(?<path>.*)$ { ... }
23
+ #
24
+ # if (-f /var/lib/cdn/cache/lib/$name/$version/.reg.404) {
25
+ # return 404 "";
26
+ # break;
27
+ # }
28
+ try_files /!{pub}/$1 /!{pub}/$1/index.html /!{pub}/$1/index.min.js @registry_backend;
29
+ }
30
+
31
+ # a dedicated location for registry_backend so we can use a dedicated server for registry
32
+ # to offload requests from main backend. This is controlled by `upstream` config.
33
+ location @registry_backend {
34
+ proxy_set_header X-Real-IP $remote_addr;
35
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
36
+ proxy_set_header Host $http_host;
37
+ proxy_set_header X-NginX-Proxy true;
38
+ proxy_set_header X-Forwarded-Proto $scheme;
39
+ # cache 200 / 404 result for `cache-period` so user can't bombard our backend
40
+ proxy_cache !{cache.name};
41
+ proxy_cache_valid 200 404 !{cache.period};
42
+ proxy_pass http://!{upstream};
43
+ }
package/src/index.ls ADDED
@@ -0,0 +1,2 @@
1
+ require! <[./route ./provider ./providers]>
2
+ module.exports = {route, provider, providers}
package/src/ngxgen.ls ADDED
@@ -0,0 +1,27 @@
1
+ require! <[fs path template-text js-yaml yargs]>
2
+
3
+ lib = fs.realpathSync path.dirname __filename
4
+ cfgfile = 'config.json'
5
+
6
+ argv = yargs
7
+ .option \config, do
8
+ alias: \c
9
+ description: "config json"
10
+ type: \string
11
+ .help \help
12
+ .alias \help, \h
13
+ .check (argv, options) ->
14
+ if !argv.c => throw new Error("config file required")
15
+ cfgfile := path.join(argv.c)
16
+ if !fs.exists-sync(cfgfile) => throw new Error("config file not found: #cfgfile")
17
+ return true
18
+ .argv
19
+
20
+ temp = fs.read-file-sync path.join(lib, '..', \dist, \config.ngx) .toString!
21
+ code = fs.read-file-sync cfgfile .toString!
22
+ try
23
+ cfg = JSON.parse(code)
24
+ catch e
25
+ cfg = js-yaml.load code
26
+
27
+ console.log template-text(temp, cfg, lib)
@@ -0,0 +1,112 @@
1
+ require! <[node-fetch lderror yauzl pthk tar]>
2
+ fs = require "fs-extra"
3
+
4
+ fetch = node-fetch
5
+ get-version-type = (v) ->
6
+ if v in <[latest main]> => \latest
7
+ else if /^\d+\.\d+\.\d+$/.test(v) => \specific
8
+ #else if /^[^~>]\d+\d.\d+\.\d+$/.test(v) => \range
9
+ else null
10
+
11
+ provider = (o = {}) ->
12
+ @_name = o.name or "unnamed#{provider._idx++}"
13
+ @_ps = [] ++ (o.chain or [])
14
+ @_fetch-real-version = o.fetch-real-version
15
+ @_fetch-bundle-file = o.fetch-bundle-file
16
+ @_check = o.check
17
+ @_opt = o.opt or {}
18
+ @
19
+
20
+ provider <<<
21
+ _hash: {}
22
+ _idx: 0
23
+ add: (p) -> @_hash[p._name] = p
24
+ get: (n) -> @_hash[n]
25
+
26
+ provider.prototype = Object.create(Object.prototype) <<<
27
+ opt: (o) -> @_opt = o or {}
28
+ fetch: (o = {}) ->
29
+ <~ Promise.resolve!then _
30
+ path = {base: {}}
31
+ {root, name, version, force, cachetime} = o
32
+ cachetime = cachetime or 60 * 60 # default 1hr
33
+ version-type = get-version-type(version)
34
+ if !version-type => return lderror.reject 400
35
+ params = {path, version-type, root, name, version, force, cachetime}
36
+ if !/^(?:@[0-9a-z._-]+\/)?[0-9a-z._-]+$/.test(name) => return lderror.reject 400
37
+ path.base.pkg = pthk.join(root, pthk.rectify name)
38
+ path.base.version = pthk.join(path.base.pkg, version)
39
+ path.version = pthk.join(path.base.version, '.reg.version')
40
+ path.404 = pthk.join(path.base.version, '.reg.404')
41
+ _ = (idx = -1) ~>
42
+ if idx >= 0 =>
43
+ if !(pr = @_ps[idx]) => return lderror.reject 404
44
+ p = pr.check({name, version}).then ~> pr._fetch params
45
+ else
46
+ p = @check({name, version})
47
+ .then ~>
48
+ if !@_fetch-real-version => lderror.reject 404
49
+ else @_fetch params
50
+ p.catch (e) -> return if (id = lderror.id e) != 404 => Promise.reject e else _(idx + 1)
51
+ _!catch (e) ->
52
+ if !((id = lderror.id(e)) in [403 404]) => return Promise.reject e
53
+ fs.ensure-dir path.base.version
54
+ .then -> fs.write-file path.404, ''
55
+ .then -> return lderror.reject 404
56
+
57
+ check: ({name, version}) -> if @_check => @_check {name, version} else Promise.resolve!
58
+ chain: (ps) -> @_ps.splice.apply @_ps, ([0, 0] ++ (if Array.isArray(ps) => ps else [ps]))
59
+
60
+ _fetch: (params) ->
61
+ {root, name, version, cachetime, force, path, version-type} = params
62
+ Promise.resolve!
63
+ .then ->
64
+ # 1. in this block, we test if a pkg is dirty/expired and should be fetched again.
65
+ if force => return
66
+ fs.exists path.version
67
+ .then (is-existed) ->
68
+ # return true if dirty
69
+ if !is-existed =>
70
+ return fs.exists path.404 .then (is404) ->
71
+ # not existed and 404 not found - never fetched and thus dirty
72
+ if !is404 => return true
73
+ (s) <- fs.stat path.404 .then _
74
+ # not existed, 404 - dirty if cache expires
75
+ dirty = Date.now! > s.mtime.getTime! + cachetime * 1000
76
+ return if !dirty => false else fs.remove path.404 .then -> true
77
+ # specific version existed. never dirty
78
+ if version-type == \specific => return false
79
+ # latest - dirty if cache expires.
80
+ if version-type == \latest =>
81
+ return fs.stat path.version .then (s) ->
82
+ Date.now! > s.mtime.getTime! + cachetime * 1000
83
+ # TODO range version
84
+ return false
85
+ .then (is-dirty) -> if !is-dirty => return lderror.reject 998
86
+ .then ~>
87
+ # 2. in this block, we peek real version for latest / range(TODO) version
88
+ (remote-info) <~ @_fetch-real-version params .then _
89
+ Promise.resolve!
90
+ .then ->
91
+ if force or version-type == \specific => return remote-info
92
+ # compare remote version with local version
93
+ fs.exists path.version .then (is-existed) ->
94
+ # no local version -> must fetch
95
+ if !is-existed => return
96
+ (r) <- fs.read-file path.version .then _
97
+ # local is older -> must fetch
98
+ if remote-info.version > JSON.parse(r).version => return
99
+ # no new version. skip fetch. touch version file for reset cache counter
100
+ now = new Date!
101
+ fs.utimes path.version, now, now
102
+ lderror.reject 998
103
+ .then ->
104
+ fs.remove path.base.version
105
+ #fs.remove path.404
106
+ .then -> fs.ensure-dir path.base.version
107
+ .then -> fs.write-file path.version, JSON.stringify(remote-info)
108
+ .then -> remote-info
109
+ .then (remote-info) ~> @_fetch-bundle-file({remote-info} <<< params)
110
+
111
+ if module? => module.exports = provider
112
+ else if window? => window.registry = provider
@@ -0,0 +1,38 @@
1
+ require! <[node-fetch lderror ../provider ../unbox]>
2
+
3
+ get-token = ({name, opt}) ->
4
+ ret = /^@([^/]+)\/(.+)$/.exec(name)
5
+ scope = if ret => ret.1 else null
6
+ token = if !opt => null else opt.{}scope[scope] or opt.{}repo[name] or opt.token or null
7
+
8
+ pvd = new provider do
9
+ name: \github
10
+ fetch-real-version: ({root, path, name, cachetime, version, version-type, force}) ->
11
+ headers = if (token = get-token({name, opt: @_opt})) => {"Authorization": "token #{token}"} else {}
12
+ release = if version-type == \latest => "releases/latest" else "releases/tags/v#version"
13
+ jsonurl = "https://api.github.com/repos/#{name.replace('@','')}/#release"
14
+ node-fetch jsonurl, {method: \GET, headers}
15
+ .then (r) -> if r.status != 200 => lderror.reject 404 else r.json!
16
+ .then (r) -> {version: (r.tag_name or '').replace(/^v/,''), url: r.tarball_url}
17
+
18
+ fetch-bundle-file: ({root, path, name, cachetime, version, remote-info, version-type, force}) ->
19
+ headers = if (token = get-token({name, opt: @_opt})) => {"Authorization": "token #{token}"} else {}
20
+ node-fetch remote-info.url, {method: \GET, headers}
21
+ .then (r) -> r.buffer!
22
+ .then (buf) -> unbox.untar {path, buf}
23
+
24
+ module.exports = pvd
25
+ /*
26
+ params =
27
+ root: 'lib'
28
+ name: 'some-repo'
29
+ version: 'latest'
30
+ cachetime: 1
31
+ opt: {token: "some-token"}
32
+
33
+ pvd.fetch-module params
34
+ .catch (e) ->
35
+ if !(lderror.id(e) in [404 998]) => return Promise.reject e
36
+ else console.log "return code: ", lderror.id(e)
37
+ .then -> console.log \done.
38
+ */
@@ -0,0 +1,3 @@
1
+ require! <[./github ./npm]>
2
+ module.exports = {github, npm}
3
+