UNPKG

2.53 kBJavaScriptView Raw
1/*
2 * init-opts.js
3 *
4 * async initOpts(cb) interface used by clientside _generator.js
5 * invokes $.getJSON to fetch opts (with in-line serialized data) and plugins
6 * if necessary fetch access token(s) from gatekeeper
7 * possibly by directing browser to gatekeeper for auth roundabout
8 * TODO: implement a mechanism to force re-authentication (logout gatekeeper)
9 *
10 * copyright 2015, Jurgen Leschner - github.com/jldec - MIT license
11*/
12
13
14var dbg = require('debug')
15var debug = dbg('pub:generator');
16var asyncbuilder = require('asyncbuilder');
17var u = require('pub-util');
18
19var srcGitHub = require('pub-src-github'); // dummy require for browserify
20
21module.exports = function initOpts(cb) {
22 cb = u.onceMaybe(cb);
23console.log(location.pathname)
24 $.getJSON(pubRef.relPath + '/pub/_opts.json')
25 .fail(function(jqXHR) { cb(new Error(jqXHR.responseText)); })
26 .done(function(respData) {
27
28 // opts includes source.file data for all sources
29 // see pub-server serve-scripts
30 var opts = respData;
31
32 // enable debug tracing on client
33 dbg.enable(opts.dbg);
34
35 // auto-infer staticRoot
36 opts.staticRoot = location.pathname.slice(0,location.pathname.length - pubRef.href.length);
37 debug('opts.staticRoot: "' + opts.staticRoot + '"');
38
39 var ab = asyncbuilder(function(err) { cb(err, opts); });
40
41 // recreate opts.source$ map (not serialized)
42 // and initialize credentials for writable static sources
43 opts.source$ = {};
44
45 opts.sources.forEach(function(source) {
46 opts.source$[source.name] = source;
47
48 // connect to static editor sources: github or dropbox
49 if (opts.staticHost && source.staticSrc) {
50 if (source.gatekeeper) {
51 var append = ab.asyncAppend();
52 debug('authenticating ' + source.gatekeeper);
53 $.getJSON(source.gatekeeper + '/status' + location.search)
54 .fail(function(jqXHR) { append(new Error(jqXHR.responseText)); })
55 .done(function(status) {
56
57 // if not logged in, send browser to gatekeeper for oauth
58 if (!status || !status.access_token) {
59 location.assign(source.gatekeeper +
60 '?ref=' + encodeURIComponent(location.href));
61 }
62 // finally we can create the source adapter to save to
63 else {
64 source.auth = status;
65 source.src = require(source.staticSrc)(source);
66 }
67 debug(status);
68 append(status);
69 });
70 }
71 }
72 });
73 ab.complete();
74
75 });
76}