@plotdb/registry 0.0.8 → 0.0.10

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/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # Change Logs
2
2
 
3
+ ## v0.0.10
4
+
5
+ - features:
6
+ - split `main` / `latest` semantics ( previously aliases ):
7
+ - `latest` always tracks the upstream newest ( npm dist-tag convention ) and is
8
+ 302-redirect-resolved like ranges -- never materialized on disk. resolution cached
9
+ per provider in `<pkg>/.reg.latest.<provider>` with cachetime expiry.
10
+ - `main` is the admin-designated version: a symlink pointing at a specific version
11
+ dir, served from disk with no redirect hop. frozen until an admin decision --
12
+ `force` fetch re-designates to upstream latest ( existing flush routes keep working
13
+ unchanged ), `designate` pins a chosen version. first touch auto-designates to
14
+ the latest at that moment.
15
+ - add `provider.designate` and a `registry.designate` admin route factory
16
+ ( recommended mount: `/staff/registry/designate/*`, aligned with
17
+ `/staff/registry/flush/*` ).
18
+ - protect manually-placed `main`: a preinstalled real dir or a manual symlink
19
+ ( e.g. pointing at a dev working copy ) is never touched by normal requests, and a
20
+ symlink's target is never deleted -- force / designate only replaces the link itself.
21
+ - tweaks:
22
+ - `main` / `latest` no longer create `.reg.404` marker files; negative results are
23
+ absorbed by the nginx proxy cache instead.
24
+ - dev ( no-nginx ) behavior of `main` now matches production: frozen, no TTL refetch.
25
+ - doc:
26
+ - add "Caching Model" section in README: cache layers, version-type behaviors,
27
+ query-string ( cachestamp ) reach, and deliberate choices ( headerless 302,
28
+ Set-Cookie handling, chain-order resolution ). all claims verified against
29
+ a local nginx + backend setup.
30
+
31
+
32
+ ## v0.0.9
33
+
34
+ - features:
35
+ - support semver range version ( `~x.y.z` / `^x.y.z`, `^` comes url-encoded as `%5E` ):
36
+ range urls are resolved to the latest satisfying version and 302-redirected to the
37
+ specific version url, so content urls stay immutable and range dirs never land on disk.
38
+ - `provider.resolve` resolves a range against the provider chain; version lists are
39
+ cached per provider in `<pkg>/.reg.versions.<provider>` with cachetime-based expiry.
40
+ - providers implement `fetch-version-list`: github via `releases?per_page=100`
41
+ ( most recent 100 only ), npm via registry metadata `versions`.
42
+ - ngx config: `proxy_cache_valid` now covers 302 ( ttl of range resolving ) and 400.
43
+ - ngx config: ignore / hide `Set-Cookie` in registry backend proxy -- session middleware
44
+ sets cookie on every response, which silently disabled proxy cache altogether.
45
+ - bug fix:
46
+ - fix npm provider name ( was `github` )
47
+ - route now responds 400 ( instead of 404 ) for invalid version / range syntax,
48
+ and no longer double-sends response on 500.
49
+ - tweaks:
50
+ - move `@plotdb/semver` to dependencies ( requires v0.0.4+, for `max-satisfying` etc. )
51
+ and drop the duplicate devDependencies entry
52
+ - add `build` / `test` npm scripts; add stub-based tests covering range resolving,
53
+ redirect routing, cache reuse and error codes ( `test/index.ls`, no network needed )
54
+ - upgrade `tar` 6 -> 7.5.21 for critical path-traversal / symlink-poisoning advisories
55
+ ( registry extracts remote tarballs into an nginx-served dir, so these matter here );
56
+ api usage ( `tar.x {strip, cwd}` ) is unchanged, but node >= 18 is now required
57
+ ( `engines` updated; was >= 10 )
58
+
59
+
3
60
  ## v0.0.8
4
61
 
5
62
  - prevent long package name (>128 chars) and long version (>40 chars)
package/README.md CHANGED
@@ -75,6 +75,92 @@ where the config file ( `myconfig.yaml` above ) should contains following fields
75
75
  Check `sample/config.ngx` and `sample/config.yaml` for a reference of nginx config file and corresponding config yaml.
76
76
 
77
77
 
78
+ ### Admin Routes
79
+
80
+ Two admin operations are expected, mounted under a guarded prefix
81
+ ( recommended naming: `/staff/registry/<operation>/` ):
82
+
83
+ # flush: force re-fetch. for `main`, this re-designates to the upstream latest.
84
+ app.get("/staff/registry/flush/*", isAdmin, registry.route({
85
+ provider: myprovider,
86
+ opt: function() { return {force: true}; },
87
+ root: {pub: "/staff/registry/flush/", fs: "...", internal: "/ilib/"}
88
+ }));
89
+
90
+ # designate: pin `main` of a package to a chosen version.
91
+ # url format: <name>/<version>; trailing path segments are ignored,
92
+ # so a public asset url can be pasted with only the prefix swapped.
93
+ app.get("/staff/registry/designate/*", isAdmin, registry.designate({
94
+ provider: myprovider,
95
+ root: {pub: "/staff/registry/designate/", fs: "..."}
96
+ }));
97
+
98
+
99
+ ## Caching Model
100
+
101
+ Four cache layers are involved when serving a package file. From the client inward:
102
+
103
+ 1. **browser cache**: keyed by full URL including query string.
104
+ 2. **nginx `proxy_cache`**: caches backend responses ( 200 / 302 / 400 / 404, for `cache.period` ).
105
+ the default `proxy_cache_key` includes `$request_uri`, **query string included**.
106
+ 3. **nginx `try_files` ( disk )**: files materialized under `fs` root are served directly;
107
+ matching is done on `$uri`, **query string excluded**. requests never reach the backend
108
+ once the file exists on disk.
109
+ 4. **registry backend internal caches**: version-list cache ( `.reg.versions.<provider>` ),
110
+ negative cache ( `.reg.404` ) and `main` staleness check, all expired by
111
+ file mtime + `cachetime`. the backend strips query strings entirely.
112
+
113
+ How each version type travels through these layers:
114
+
115
+ - **specific version** ( `1.2.3` ): immutable by definition. the first request falls through
116
+ to the backend, which downloads and unpacks the package, then replies with
117
+ `X-Accel-Redirect`; every later request is served from disk by `try_files` ( layer 3 )
118
+ without touching the backend. this is correct exactly because the content never changes.
119
+ - **range version** ( `~1.2.3` / `^1.2.3`, `^` arrives url-encoded as `%5E` ): never
120
+ materialized on disk, so `try_files` always misses and the request reaches the backend,
121
+ which 302-redirects to the resolved specific version. effective staleness bound for
122
+ seeing a newly released version = `cache.period` ( layer 2, caches the 302 )
123
+ + `cachetime` ( layer 4, caches the version list ).
124
+ - **`latest`**: always tracks the upstream newest ( github latest release / npm dist-tag
125
+ `latest` -- the keyword follows the npm dist-tag convention ). handled exactly like a
126
+ range: never on disk, 302-redirected, same staleness bound.
127
+ - **`main`**: the admin-designated version, kept as a **symlink** pointing at a specific
128
+ version dir, served from disk by layer 3 ( no redirect hop ). frozen semantics: nothing
129
+ updates `main` automatically -- not on requests, not on upstream releases. it changes only
130
+ through a `force` fetch ( re-designate to upstream latest, e.g. an admin flush route ),
131
+ an explicit `designate` call ( pin to a chosen version ), or manual placement:
132
+ a real ( non-symlink ) dir at `main` is treated as preinstalled and never touched by
133
+ normal requests; a manual symlink ( e.g. pointing at a dev working copy ) likewise
134
+ survives everything except an explicit force / designate, and even then only the link
135
+ is replaced -- its target is never deleted. first touch of a package with nothing at
136
+ `main` auto-designates to the upstream latest at that moment.
137
+
138
+ Query-string cache busting ( e.g. a `cachestamp` param ) therefore only goes so deep:
139
+ it always busts layer 1 and layer 2 ( new query = new cache key, the request reaches the
140
+ backend ), but never layer 3 ( disk files, including `main` ) nor layer 4 ( backend TTLs ).
141
+ a bumped cachestamp on a range URL yields a fresh 302, but the resolved version may still
142
+ come from the version-list cache until `cachetime` expires.
143
+
144
+ Some deliberate choices worth knowing before changing them:
145
+
146
+ - **the 302 carries no cache headers on purpose.** browsers do not cache a redirect
147
+ without freshness info ( heuristic caching needs `Last-Modified`, which we do not send ),
148
+ so clients re-request the range URL every time, while nginx still absorbs the load via
149
+ `proxy_cache_valid`. do NOT add `Cache-Control: no-cache` to make browser behavior
150
+ "explicit": upstream `Cache-Control` overrides `proxy_cache_valid`, which would disable
151
+ the nginx 302 cache as well ( unless you also add `proxy_ignore_headers Cache-Control` ).
152
+ - **`Set-Cookie` must be ignored and hidden in the backend proxy location.** session
153
+ middleware sets a cookie on every response, which by default prevents nginx from caching
154
+ anything at all. the generated config includes `proxy_ignore_headers Set-Cookie` +
155
+ `proxy_hide_header Set-Cookie`; the latter is required, otherwise a cached response
156
+ would replay one user's session cookie to other users.
157
+ - **range resolution follows chain order, not the union of providers.** the first provider
158
+ with any satisfying version wins ( consistent with how `fetch` falls through on 404 ).
159
+ if a package has github releases, github is the source of truth for ranges: a newer
160
+ version published only to npm stays invisible. keep github releases and npm publishes
161
+ in sync for packages available on both.
162
+
163
+
78
164
  ## Registry Provider Specification
79
165
 
80
166
  Registry providers are used to access a requested resource which is defined by its `namespace`, `name`, `version`, `path` and optionally `type`.
@@ -116,6 +202,11 @@ A registry provider object should contain following fields:
116
202
  - `fetchBundleFile(opt)`: fetch the given package and ectract it.
117
203
  - return a promise resolves when bundle file is extracted completely.
118
204
  - check `fetchRealVersion` for the definition of `opt`.
205
+ - `fetchVersionList({name})`: ( optional ) list available versions of a given package, for range resolving.
206
+ - return a promise resolves a list of version strings ( e.g., `["1.0.0", "1.1.0"]` ).
207
+ - github provider lists via `releases?per_page=100` ( most recent 100 releases only );
208
+ npm provider lists via registry metadata `versions` field.
209
+ - a provider without `fetchVersionList` is simply skipped when resolving a range.
119
210
 
120
211
  A provider provides following APIs:
121
212
 
@@ -125,10 +216,13 @@ A provider provides following APIs:
125
216
  - `opt` is an object with following fields:
126
217
  - `root`: root directory for keeping cached files.
127
218
  - `name`: package name. scope is possible, such as `@plotdb/block`.
128
- - `version`: package version. should always in semver format (e.g., `1.0.0`) or one of `latest` or `main`.
129
- - in `@plotdb/block` `main` is the locked version, however there is no locked version defined here,
130
- so `main` is equivalent to `latest`.
219
+ - `version`: package version. should always in semver format (e.g., `1.0.0`) or `main`.
220
+ - `main` is the designated ( locked ) version: frozen once set, updated only by
221
+ `force` ( re-designate to upstream latest ) or `designate()`. see "Caching Model".
131
222
  - in github, tags is used for fetching release. tags should be in format `vx.y.z`. e.g., `v1.0.0`.
223
+ - range ( e.g. `^1.2.3` ) and `latest` versions are rejected with 400: they should be
224
+ resolved to a specific version with `resolve()` / `resolveLatest()` first,
225
+ so their dirs never land on disk.
132
226
  - `force`: default false. when true, ignore cache / 404 status and always try fetching package again.
133
227
  - `cachetime`: default 3600 seconds. cache for how long (in seconds) since the last fetch attempts.
134
228
  - return value: a Promise, resolves if package is found and downloaded. reject `e` in following situation:
@@ -139,6 +233,28 @@ A provider provides following APIs:
139
233
  if it's actually 404, nginx will then look up the file and report 404 after found not found.
140
234
  - the result will then cached by nginx and won't hit registry backend until cache expires.
141
235
  - otherwise, it's an internal exception and should be logged and tracked.
236
+ - `resolve(opt)`: resolve a range version ( `~x.y.z` / `^x.y.z`, also `>` / `>=` ) to the latest
237
+ specific version satisfying it, walking the provider chain like `fetch` does.
238
+ - `opt` takes `root` / `name` / `version` / `force` / `cachetime` as in `fetch`,
239
+ where `version` must be a range.
240
+ - version lists are cached per provider in `<pkg>/.reg.versions.<provider>`,
241
+ expired by mtime + `cachetime` like other cache files.
242
+ - return value: a Promise resolving the version string; rejects 400 for a non-range
243
+ version, 404 if no provider has a satisfying version.
244
+ - `registry.route` uses this to serve range urls: it responds a 302 redirect to the
245
+ specific version url ( `^` arrives url-encoded as `%5E`; `~` needs no encoding ),
246
+ so content urls stay immutable and the redirect ttl is governed by nginx
247
+ `proxy_cache_valid 302`.
248
+ - `resolveLatest(opt)`: resolve what `latest` currently means ( github latest release /
249
+ npm dist-tag ), walking the provider chain. results are cached per provider in
250
+ `<pkg>/.reg.latest.<provider>` with `cachetime` expiry. `registry.route` uses this
251
+ to serve `latest` urls as a 302 redirect, same as ranges.
252
+ - `designate(opt)`: point `main` at a specific version.
253
+ - `opt`: `root` / `name` / `version` ( must be specific ) / `cachetime`.
254
+ - ensures the version is cached ( via the provider chain ), then atomically repoints
255
+ the `main` symlink ( relative link, tmp + rename ). a real dir at `main`
256
+ ( preinstalled / legacy ) is replaced only here; a symlink's target is never deleted.
257
+ - return value: a Promise resolving `{name, version}`.
142
258
  - `check({name, version})`: call the `check()` function provided in constructor.
143
259
  - `chain(providers)`: chain given `providers` in this provider.
144
260
  - `providers`: either another provider, or a list of other providers.
package/config.ngx CHANGED
@@ -36,8 +36,17 @@ location @registry_backend {
36
36
  proxy_set_header Host $http_host;
37
37
  proxy_set_header X-NginX-Proxy true;
38
38
  proxy_set_header X-Forwarded-Proto $scheme;
39
- # cache 200 / 404 result for `cache-period` so user can't bombard our backend
39
+ # session middleware ( e.g. express-session ) sets cookie on every response,
40
+ # which by default prevents nginx from caching anything -- so we ignore it.
41
+ # `proxy_hide_header` is REQUIRED along with `proxy_ignore_headers`: without it
42
+ # a cached response would replay one user's session cookie to other users.
43
+ proxy_ignore_headers Set-Cookie;
44
+ proxy_hide_header Set-Cookie;
45
+ # cache 200 / 404 result for `cache-period` so user can't bombard our backend.
46
+ # 302 is the range-version redirect ( e.g. `^1.2.3` -> resolved specific version ):
47
+ # its cache period is effectively the ttl of range resolving.
48
+ # 400 is for invalid range / version syntax.
40
49
  proxy_cache !{cache.name};
41
- proxy_cache_valid 200 404 !{cache.period};
50
+ proxy_cache_valid 200 302 400 404 !{cache.period};
42
51
  proxy_pass http://!{upstream};
43
52
  }
package/designate.js ADDED
@@ -0,0 +1,60 @@
1
+ // Generated by LiveScript 1.6.0
2
+ (function(){
3
+ var pthk, lderror, designate;
4
+ pthk = require('pthk');
5
+ lderror = require('lderror');
6
+ designate = function(arg$){
7
+ var provider, root, opt;
8
+ provider = arg$.provider, root = arg$.root, opt = arg$.opt;
9
+ if (!root.pub.endsWith('/')) {
10
+ root.pub = root.pub + "/";
11
+ }
12
+ return function(req, res){
13
+ var url, id, _o;
14
+ url = req.originalUrl;
15
+ id = pthk.rectify(url.replace(root.pub, '').replace(/[#?].*$/, ''));
16
+ _o = !opt
17
+ ? {}
18
+ : typeof opt === 'function' ? opt(req, res) : opt;
19
+ return Promise.resolve().then(function(){
20
+ var ids, ref$, name, version;
21
+ if (!(id && /^[-_a-zA-Z0-9@./]+$/.exec(id))) {
22
+ return lderror.reject(404);
23
+ }
24
+ ids = id.split('/');
25
+ ref$ = (ids[0] || '')[0] === '@'
26
+ ? [ids[0] + "/" + ids[1], ids[2]]
27
+ : [ids[0], ids[1]], name = ref$[0], version = ref$[1];
28
+ if (!(name && version)) {
29
+ return lderror.reject(404);
30
+ }
31
+ return provider.designate(import$({
32
+ root: root.fs,
33
+ name: name,
34
+ version: version
35
+ }, _o));
36
+ }).then(function(arg$){
37
+ var name, version;
38
+ name = arg$.name, version = arg$.version;
39
+ return res.status(200).json({
40
+ name: name,
41
+ version: version
42
+ });
43
+ })['catch'](function(e){
44
+ var code;
45
+ code = lderror.id(e);
46
+ if (code === 400 || code === 404) {
47
+ return res.status(code).send();
48
+ }
49
+ console.log(e);
50
+ return res.status(500).send();
51
+ });
52
+ };
53
+ };
54
+ module.exports = designate;
55
+ function import$(obj, src){
56
+ var own = {}.hasOwnProperty;
57
+ for (var key in src) if (own.call(src, key)) obj[key] = src[key];
58
+ return obj;
59
+ }
60
+ }).call(this);
package/index.js CHANGED
@@ -1,11 +1,14 @@
1
+ // Generated by LiveScript 1.6.0
1
2
  (function(){
2
- var route, provider, providers;
3
+ var route, provider, providers, designate;
3
4
  route = require('./route');
4
5
  provider = require('./provider');
5
6
  providers = require('./providers');
7
+ designate = require('./designate');
6
8
  module.exports = {
7
9
  route: route,
8
10
  provider: provider,
9
- providers: providers
11
+ providers: providers,
12
+ designate: designate
10
13
  };
11
14
  }).call(this);
package/ngxgen.js CHANGED
@@ -1,3 +1,4 @@
1
+ // Generated by LiveScript 1.6.0
1
2
  (function(){
2
3
  var fs, path, templateText, jsYaml, yargs, lib, cfgfile, argv, temp, code, cfg, e;
3
4
  fs = require('fs');
package/package.json CHANGED
@@ -1 +1 @@
1
- {"author":"zbryikt","name":"@plotdb/registry","license":"MIT","description":"registry","version":"0.0.8","main":"index.js","homepage":"https://github.com/plotdb/registry","repository":{"type":"git","url":"https://github.com/plotdb/registry"},"engines":{"node":">=10.14.1","npm":">=6.4.1"},"scripts":{"start":"npx server -r web -o true","server":"cd web; ../node_modules/.bin/lsc server.ls"},"bin":{"registry-ngx":"./../bin/ngxgen"},"dependencies":{"@zbryikt/template":"^2.4.1","fs-extra":"^8.1.0","js-yaml":"^4.1.1","lderror":"^2.4.6","livescript":"^1.6.0","node-fetch":"^2.6.7","pthk":"^0.0.1","tar":"^6.1.11","template-text":"^0.2.0","yargs":"^17.6.0","yauzl":"^2.10.0"},"devDependencies":{"@loadingio/bootstrap.ext":"^0.0.12","@loadingio/debounce.js":"^1.0.1","@loadingio/ldquery":"^3.0.6","@plotdb/block":"^5.6.3","@plotdb/csscope":"^5.0.4","@plotdb/rescope":"^5.0.17","@plotdb/semver":"^0.0.3","bootstrap":"^4.6.1","bootstrap.native":"^3.0.14","fedep":"^1.6.0","ldcover":"^3.5.6","ldloader":"^3.0.3","ldview":"^1.7.0","proxise":"^1.0.1"},"frontendDependencies":{"root":"web/static/assets/lib","modules":["@loadingio/bootstrap.ext","@loadingio/debounce.js","@loadingio/ldquery","bootstrap","bootstrap.native","@plotdb/block","@plotdb/csscope","@plotdb/rescope","@plotdb/semver","ldcover","ldloader","ldview","proxise"]}}
1
+ {"author":"zbryikt","name":"@plotdb/registry","license":"MIT","description":"registry","version":"0.0.10","main":"index.js","homepage":"https://github.com/plotdb/registry","repository":{"type":"git","url":"https://github.com/plotdb/registry"},"engines":{"node":">=18","npm":">=6.4.1"},"scripts":{"start":"npx server -r web -o true","server":"cd web; ../node_modules/.bin/lsc server.ls","build":"lsc -c -o dist src/index.ls src/route.ls src/provider.ls src/designate.ls src/unbox.ls src/ngxgen.ls && lsc -c -o dist/providers src/providers/index.ls src/providers/github.ls src/providers/npm.ls && cp src/config.ngx dist/config.ngx","test":"lsc test/index.ls"},"bin":{"registry-ngx":"./../bin/ngxgen"},"dependencies":{"@plotdb/guides":"github:plotdb/guides#master","@plotdb/semver":"^0.0.4","@zbryikt/template":"^2.4.2","fs-extra":"^8.1.0","js-yaml":"^4.1.1","lderror":"^2.4.6","livescript":"^1.6.0","node-fetch":"^2.6.7","pthk":"^0.0.1","tar":"^7.5.21","template-text":"^0.2.0","yargs":"^17.6.0","yauzl":"^2.10.0"},"devDependencies":{"@loadingio/bootstrap.ext":"^0.0.12","@loadingio/debounce.js":"^1.0.1","@loadingio/ldquery":"^3.0.6","@plotdb/block":"^5.6.3","@plotdb/csscope":"^5.0.4","@plotdb/rescope":"^5.0.17","bootstrap":"^4.6.1","bootstrap.native":"^3.0.14","fedep":"^1.7.3","ldcover":"^3.5.6","ldloader":"^3.0.3","ldview":"^1.7.0","proxise":"^1.0.1"},"frontendDependencies":{"root":"web/static/assets/lib","modules":["@loadingio/bootstrap.ext","@loadingio/debounce.js","@loadingio/ldquery","bootstrap","bootstrap.native","@plotdb/block","@plotdb/csscope","@plotdb/rescope","@plotdb/semver","ldcover","ldloader","ldview","proxise"]}}
package/provider.js CHANGED
@@ -1,17 +1,23 @@
1
+ // Generated by LiveScript 1.6.0
1
2
  (function(){
2
- var nodeFetch, lderror, yauzl, pthk, tar, fs, fetch, getVersionType, provider, ref$;
3
+ var nodeFetch, lderror, yauzl, pthk, tar, semver, fs, fetch, getVersionType, provider, ref$;
3
4
  nodeFetch = require('node-fetch');
4
5
  lderror = require('lderror');
5
6
  yauzl = require('yauzl');
6
7
  pthk = require('pthk');
7
8
  tar = require('tar');
9
+ semver = require('@plotdb/semver');
8
10
  fs = require("fs-extra");
9
11
  fetch = nodeFetch;
10
12
  getVersionType = function(v){
11
- if (v === 'latest' || v === 'main') {
13
+ if (v === 'main') {
14
+ return 'main';
15
+ } else if (v === 'latest') {
12
16
  return 'latest';
13
17
  } else if (/^\d+\.\d+\.\d+$/.test(v)) {
14
18
  return 'specific';
19
+ } else if (/^[~^>]/.test(v) && semver.validRange(v)) {
20
+ return 'range';
15
21
  } else {
16
22
  return null;
17
23
  }
@@ -22,6 +28,7 @@
22
28
  this._ps = [].concat(o.chain || []);
23
29
  this._fetchRealVersion = o.fetchRealVersion;
24
30
  this._fetchBundleFile = o.fetchBundleFile;
31
+ this._fetchVersionList = o.fetchVersionList;
25
32
  this._check = o.check;
26
33
  this._opt = o.opt || {};
27
34
  return this;
@@ -34,6 +41,7 @@
34
41
  provider.get = function(n){
35
42
  return this._hash[n];
36
43
  };
44
+ provider.versionType = getVersionType;
37
45
  provider.prototype = (ref$ = Object.create(Object.prototype), ref$.opt = function(o){
38
46
  return this._opt = o || {};
39
47
  }, ref$.fetch = function(o){
@@ -50,6 +58,9 @@
50
58
  if (!versionType) {
51
59
  return lderror.reject(400, "incorrect version-type when accessing " + name + "@" + version);
52
60
  }
61
+ if (versionType === 'range' || versionType === 'latest') {
62
+ return lderror.reject(400, versionType + " version should be resolved before fetch");
63
+ }
53
64
  if ((name + "").length > 128 || (version + "").length > 40) {
54
65
  return lderror.reject(998);
55
66
  }
@@ -69,6 +80,9 @@
69
80
  path.base.version = pthk.join(path.base.pkg, version);
70
81
  path.version = pthk.join(path.base.version, '.reg.version');
71
82
  path[404] = pthk.join(path.base.version, '.reg.404');
83
+ if (versionType === 'main') {
84
+ return this$._fetchMain(params);
85
+ }
72
86
  _ = function(idx){
73
87
  var pr, p;
74
88
  idx == null && (idx = -1);
@@ -131,6 +145,271 @@
131
145
  return this._ps.splice.apply(this._ps, [0, 0].concat(Array.isArray(ps)
132
146
  ? ps
133
147
  : [ps]));
148
+ }, ref$._fetchMain = function(arg$){
149
+ var root, name, version, force, cachetime, path, this$ = this;
150
+ root = arg$.root, name = arg$.name, version = arg$.version, force = arg$.force, cachetime = arg$.cachetime, path = arg$.path;
151
+ return Promise.resolve().then(function(){
152
+ return fs.lstat(path.base.version)['catch'](function(){
153
+ return null;
154
+ });
155
+ }).then(function(s){
156
+ if (s && !force) {
157
+ return lderror.reject(998);
158
+ }
159
+ return this$.resolveLatest({
160
+ root: root,
161
+ name: name,
162
+ cachetime: cachetime,
163
+ force: force
164
+ }).then(function(v){
165
+ return this$.designate({
166
+ root: root,
167
+ name: name,
168
+ version: v,
169
+ cachetime: cachetime
170
+ });
171
+ });
172
+ });
173
+ }, ref$.resolveLatest = function(o){
174
+ var this$ = this;
175
+ o == null && (o = {});
176
+ return Promise.resolve().then(function(){
177
+ var root, name, force, cachetime, base, peek, _;
178
+ root = o.root, name = o.name, force = o.force, cachetime = o.cachetime;
179
+ cachetime = cachetime || 60 * 60;
180
+ if ((name + "").length > 128) {
181
+ return lderror.reject(404);
182
+ }
183
+ if (!/^(?:@[0-9a-z._-]+\/)?[0-9a-z._-]+$/.test(name)) {
184
+ return lderror.reject(400);
185
+ }
186
+ base = pthk.join(root, pthk.rectify(name));
187
+ peek = function(pvd){
188
+ var file;
189
+ if (!pvd._fetchRealVersion) {
190
+ return lderror.reject(404);
191
+ }
192
+ file = pthk.join(base, ".reg.latest." + pvd._name);
193
+ return Promise.resolve().then(function(){
194
+ if (force) {
195
+ return null;
196
+ }
197
+ return fs.exists(file).then(function(isExisted){
198
+ if (!isExisted) {
199
+ return null;
200
+ }
201
+ return fs.stat(file).then(function(s){
202
+ if (Date.now() > s.mtime.getTime() + cachetime * 1000) {
203
+ return null;
204
+ }
205
+ return fs.readFile(file).then(function(r){
206
+ return JSON.parse(r);
207
+ });
208
+ });
209
+ });
210
+ }).then(function(cached){
211
+ if (cached) {
212
+ return cached.version;
213
+ }
214
+ return pvd._fetchRealVersion({
215
+ root: root,
216
+ name: name,
217
+ cachetime: cachetime,
218
+ version: 'latest',
219
+ versionType: 'latest'
220
+ }).then(function(info){
221
+ return fs.ensureDir(base).then(function(){
222
+ return fs.writeFile(file, JSON.stringify({
223
+ version: info.version
224
+ }));
225
+ }).then(function(){
226
+ return info.version;
227
+ });
228
+ });
229
+ });
230
+ };
231
+ _ = function(idx){
232
+ var pvd;
233
+ idx == null && (idx = -1);
234
+ pvd = idx < 0
235
+ ? this$
236
+ : this$._ps[idx];
237
+ if (!pvd) {
238
+ return lderror.reject(404);
239
+ }
240
+ return pvd.check({
241
+ name: name,
242
+ version: 'latest'
243
+ }).then(function(){
244
+ return peek(pvd);
245
+ })['catch'](function(e){
246
+ if (lderror.id(e) !== 404) {
247
+ return Promise.reject(e);
248
+ } else {
249
+ return _(idx + 1);
250
+ }
251
+ });
252
+ };
253
+ return _()['catch'](function(e){
254
+ if (lderror.id(e) === 403) {
255
+ return lderror.reject(404);
256
+ } else {
257
+ return Promise.reject(e);
258
+ }
259
+ });
260
+ });
261
+ }, ref$.designate = function(o){
262
+ var this$ = this;
263
+ o == null && (o = {});
264
+ return Promise.resolve().then(function(){
265
+ var root, name, version, cachetime, base, ref$, mainPath, tmp;
266
+ root = o.root, name = o.name, version = o.version, cachetime = o.cachetime;
267
+ if (getVersionType(version) !== 'specific') {
268
+ return lderror.reject(400, "designate requires a specific version");
269
+ }
270
+ if ((name + "").length > 128 || (version + "").length > 40) {
271
+ return lderror.reject(404);
272
+ }
273
+ if (!/^(?:@[0-9a-z._-]+\/)?[0-9a-z._-]+$/.test(name)) {
274
+ return lderror.reject(400);
275
+ }
276
+ base = pthk.join(root, pthk.rectify(name));
277
+ ref$ = [pthk.join(base, 'main'), pthk.join(base, ".main." + process.pid + ".tmp")], mainPath = ref$[0], tmp = ref$[1];
278
+ return Promise.resolve().then(function(){
279
+ return fs.exists(pthk.join(base, version, '.reg.version')).then(function(isExisted){
280
+ if (isExisted) {
281
+ return;
282
+ }
283
+ return this$.fetch({
284
+ root: root,
285
+ name: name,
286
+ version: version,
287
+ force: false,
288
+ cachetime: cachetime
289
+ });
290
+ });
291
+ }).then(function(){
292
+ return fs.lstat(mainPath)['catch'](function(){
293
+ return null;
294
+ });
295
+ }).then(function(s){
296
+ return Promise.resolve().then(function(){
297
+ if (s && !s.isSymbolicLink()) {
298
+ return fs.remove(mainPath);
299
+ }
300
+ }).then(function(){
301
+ return fs.remove(tmp);
302
+ }).then(function(){
303
+ return fs.symlink(version, tmp);
304
+ }).then(function(){
305
+ return fs.rename(tmp, mainPath);
306
+ });
307
+ }).then(function(){
308
+ return {
309
+ name: name,
310
+ version: version
311
+ };
312
+ });
313
+ });
314
+ }, ref$.resolve = function(o){
315
+ var this$ = this;
316
+ o == null && (o = {});
317
+ return Promise.resolve().then(function(){
318
+ var root, name, version, force, cachetime, base, list, _;
319
+ root = o.root, name = o.name, version = o.version, force = o.force, cachetime = o.cachetime;
320
+ cachetime = cachetime || 60 * 60;
321
+ if (getVersionType(version) !== 'range') {
322
+ return lderror.reject(400, "not a range version: " + name + "@" + version);
323
+ }
324
+ if ((name + "").length > 128 || (version + "").length > 40) {
325
+ return lderror.reject(404);
326
+ }
327
+ if (!/^(?:@[0-9a-z._-]+\/)?[0-9a-z._-]+$/.test(name)) {
328
+ return lderror.reject(400);
329
+ }
330
+ base = pthk.join(root, pthk.rectify(name));
331
+ list = function(pvd){
332
+ var file;
333
+ if (!pvd._fetchVersionList) {
334
+ return lderror.reject(404);
335
+ }
336
+ file = pthk.join(base, ".reg.versions." + pvd._name);
337
+ return Promise.resolve().then(function(){
338
+ if (force) {
339
+ return null;
340
+ }
341
+ return fs.exists(file).then(function(isExisted){
342
+ if (!isExisted) {
343
+ return null;
344
+ }
345
+ return fs.stat(file).then(function(s){
346
+ if (Date.now() > s.mtime.getTime() + cachetime * 1000) {
347
+ return null;
348
+ }
349
+ return fs.readFile(file).then(function(r){
350
+ return JSON.parse(r);
351
+ });
352
+ });
353
+ });
354
+ }).then(function(cached){
355
+ if (cached) {
356
+ return cached.versions;
357
+ }
358
+ return pvd._fetchVersionList({
359
+ name: name
360
+ })['catch'](function(e){
361
+ if (lderror.id(e) === 404) {
362
+ return [];
363
+ } else {
364
+ return Promise.reject(e);
365
+ }
366
+ }).then(function(vs){
367
+ return fs.ensureDir(base).then(function(){
368
+ return fs.writeFile(file, JSON.stringify({
369
+ versions: vs
370
+ }));
371
+ }).then(function(){
372
+ return vs;
373
+ });
374
+ });
375
+ });
376
+ };
377
+ _ = function(idx){
378
+ var pvd;
379
+ idx == null && (idx = -1);
380
+ pvd = idx < 0
381
+ ? this$
382
+ : this$._ps[idx];
383
+ if (!pvd) {
384
+ return lderror.reject(404);
385
+ }
386
+ return pvd.check({
387
+ name: name,
388
+ version: version
389
+ }).then(function(){
390
+ return list(pvd);
391
+ }).then(function(vs){
392
+ var v;
393
+ if (v = semver.maxSatisfying(vs, version)) {
394
+ return v;
395
+ }
396
+ return lderror.reject(404);
397
+ })['catch'](function(e){
398
+ if (lderror.id(e) !== 404) {
399
+ return Promise.reject(e);
400
+ } else {
401
+ return _(idx + 1);
402
+ }
403
+ });
404
+ };
405
+ return _()['catch'](function(e){
406
+ if (lderror.id(e) === 403) {
407
+ return lderror.reject(404);
408
+ } else {
409
+ return Promise.reject(e);
410
+ }
411
+ });
412
+ });
134
413
  }, ref$._fetch = function(params){
135
414
  var root, name, version, cachetime, force, path, versionType, this$ = this;
136
415
  root = params.root, name = params.name, version = params.version, cachetime = params.cachetime, force = params.force, path = params.path, versionType = params.versionType;
@@ -155,14 +434,6 @@
155
434
  });
156
435
  });
157
436
  }
158
- if (versionType === 'specific') {
159
- return false;
160
- }
161
- if (versionType === 'latest') {
162
- return fs.stat(path.version).then(function(s){
163
- return Date.now() > s.mtime.getTime() + cachetime * 1000;
164
- });
165
- }
166
437
  return false;
167
438
  }).then(function(isDirty){
168
439
  if (!isDirty) {
@@ -172,24 +443,6 @@
172
443
  }).then(function(){
173
444
  return this$._fetchRealVersion(params).then(function(remoteInfo){
174
445
  return Promise.resolve().then(function(){
175
- if (force || versionType === 'specific') {
176
- return remoteInfo;
177
- }
178
- return fs.exists(path.version).then(function(isExisted){
179
- if (!isExisted) {
180
- return;
181
- }
182
- return fs.readFile(path.version).then(function(r){
183
- var now;
184
- if (remoteInfo.version > JSON.parse(r).version) {
185
- return;
186
- }
187
- now = new Date();
188
- fs.utimes(path.version, now, now);
189
- return lderror.reject(998);
190
- });
191
- });
192
- }).then(function(){
193
446
  return fs.remove(path.base.version);
194
447
  }).then(function(){
195
448
  return fs.ensureDir(path.base.version);
@@ -1,9 +1,11 @@
1
+ // Generated by LiveScript 1.6.0
1
2
  (function(){
2
- var nodeFetch, lderror, provider, unbox, getToken, pvd;
3
+ var nodeFetch, lderror, provider, unbox, semver, getToken, pvd;
3
4
  nodeFetch = require('node-fetch');
4
5
  lderror = require('lderror');
5
6
  provider = require('../provider');
6
7
  unbox = require('../unbox');
8
+ semver = require('@plotdb/semver');
7
9
  getToken = function(arg$){
8
10
  var name, opt, ret, scope, token;
9
11
  name = arg$.name, opt = arg$.opt;
@@ -15,6 +17,35 @@
15
17
  };
16
18
  pvd = new provider({
17
19
  name: 'github',
20
+ fetchVersionList: function(arg$){
21
+ var name, headers, token, jsonurl;
22
+ name = arg$.name;
23
+ headers = (token = getToken({
24
+ name: name,
25
+ opt: this._opt
26
+ }))
27
+ ? {
28
+ "Authorization": "token " + token
29
+ }
30
+ : {};
31
+ jsonurl = "https://api.github.com/repos/" + name.replace('@', '') + "/releases?per_page=100";
32
+ return nodeFetch(jsonurl, {
33
+ method: 'GET',
34
+ headers: headers
35
+ }).then(function(r){
36
+ if (r.status !== 200) {
37
+ return lderror.reject(404);
38
+ } else {
39
+ return r.json();
40
+ }
41
+ }).then(function(rs){
42
+ return rs.map(function(it){
43
+ return (it.tag_name + "").replace(/^v/, '');
44
+ }).filter(function(it){
45
+ return semver.valid(it);
46
+ });
47
+ });
48
+ },
18
49
  fetchRealVersion: function(arg$){
19
50
  var root, path, name, cachetime, version, versionType, force, headers, token, release, jsonurl;
20
51
  root = arg$.root, path = arg$.path, name = arg$.name, cachetime = arg$.cachetime, version = arg$.version, versionType = arg$.versionType, force = arg$.force;
@@ -1,3 +1,4 @@
1
+ // Generated by LiveScript 1.6.0
1
2
  (function(){
2
3
  var github, npm;
3
4
  github = require('./github');
package/providers/npm.js CHANGED
@@ -1,11 +1,31 @@
1
+ // Generated by LiveScript 1.6.0
1
2
  (function(){
2
- var nodeFetch, lderror, provider, unbox, pvd;
3
+ var nodeFetch, lderror, provider, unbox, semver, pvd;
3
4
  nodeFetch = require('node-fetch');
4
5
  lderror = require('lderror');
5
6
  provider = require('../provider');
6
7
  unbox = require('../unbox');
8
+ semver = require('@plotdb/semver');
7
9
  pvd = new provider({
8
- name: 'github',
10
+ name: 'npm',
11
+ fetchVersionList: function(arg$){
12
+ var name, jsonurl;
13
+ name = arg$.name;
14
+ jsonurl = "https://registry.npmjs.org/" + name;
15
+ return nodeFetch(jsonurl, {
16
+ method: 'GET'
17
+ }).then(function(r){
18
+ if (r.status !== 200) {
19
+ return lderror.reject(404);
20
+ } else {
21
+ return r.json();
22
+ }
23
+ }).then(function(r){
24
+ return Object.keys(r.versions || {}).filter(function(it){
25
+ return semver.valid(it);
26
+ });
27
+ });
28
+ },
9
29
  fetchRealVersion: function(arg$){
10
30
  var root, path, name, cachetime, version, versionType, force, opt, jsonurl;
11
31
  root = arg$.root, path = arg$.path, name = arg$.name, cachetime = arg$.cachetime, version = arg$.version, versionType = arg$.versionType, force = arg$.force, opt = arg$.opt;
package/route.js CHANGED
@@ -1,8 +1,10 @@
1
+ // Generated by LiveScript 1.6.0
1
2
  (function(){
2
- var pthk, lderror, fs, handle, route;
3
+ var pthk, lderror, fs, versionType, handle, route;
3
4
  pthk = require('pthk');
4
5
  lderror = require('lderror');
5
6
  fs = require("fs-extra");
7
+ versionType = require('./provider').versionType;
6
8
  handle = function(arg$){
7
9
  var provider, id, root, opt, ref$, paths, obj;
8
10
  provider = arg$.provider, id = arg$.id, root = arg$.root, opt = arg$.opt;
@@ -11,8 +13,8 @@
11
13
  }
12
14
  ref$ = [{}, {}, pthk.rectify(id)], paths = ref$[0], obj = ref$[1], id = ref$[2];
13
15
  return Promise.resolve().then(function(){
14
- var ids;
15
- if (!/^[-_a-zA-Z0-9@./]+$/.exec(id)) {
16
+ var ids, e, vt, p;
17
+ if (!/^[-_a-zA-Z0-9@./~^%]+$/.exec(id)) {
16
18
  return lderror.reject(404);
17
19
  }
18
20
  ids = id.split('/');
@@ -30,6 +32,33 @@
30
32
  if (!(obj.name && obj.version && obj.path)) {
31
33
  return lderror.reject(404);
32
34
  }
35
+ try {
36
+ obj.version = decodeURIComponent(obj.version);
37
+ } catch (e$) {
38
+ e = e$;
39
+ return lderror.reject(404);
40
+ }
41
+ if ((vt = versionType(obj.version)) === 'range' || vt === 'latest') {
42
+ p = vt === 'range'
43
+ ? provider.resolve(import$({
44
+ root: root.fs,
45
+ name: obj.name,
46
+ version: obj.version,
47
+ force: false,
48
+ cachetime: 60 * 60
49
+ }, opt))
50
+ : provider.resolveLatest(import$({
51
+ root: root.fs,
52
+ name: obj.name,
53
+ force: false,
54
+ cachetime: 60 * 60
55
+ }, opt));
56
+ return p.then(function(v){
57
+ return {
58
+ redirect: pthk.join(root.pub, obj.name, v, obj.path)
59
+ };
60
+ });
61
+ }
33
62
  return provider.fetch(import$({
34
63
  root: root.fs,
35
64
  name: obj.name,
@@ -65,18 +94,22 @@
65
94
  id: id,
66
95
  root: root,
67
96
  opt: _o
68
- }).then(function(){
97
+ }).then(function(r){
98
+ if (r && r.redirect) {
99
+ return res.redirect(302, r.redirect);
100
+ }
69
101
  res.set({
70
102
  "X-Accel-Redirect": pthk.join(root.internal, id)
71
103
  });
72
104
  return res.send();
73
105
  })['catch'](function(e){
74
- var ref$;
75
- if (!((ref$ = lderror.id(e)) === 400 || ref$ === 404)) {
76
- console.log(e);
77
- res.status(500).send();
106
+ var code;
107
+ code = lderror.id(e);
108
+ if (code === 400 || code === 404) {
109
+ return res.status(code).send();
78
110
  }
79
- return res.status(404).send();
111
+ console.log(e);
112
+ return res.status(500).send();
80
113
  });
81
114
  };
82
115
  };
package/unbox.js CHANGED
@@ -1,3 +1,4 @@
1
+ // Generated by LiveScript 1.6.0
1
2
  (function(){
2
3
  var yauzl, tar, pthk, stream, fs, unzip, untar;
3
4
  yauzl = require('yauzl');