var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { generateApolloClient } from '@deep-foundation/hasura/client.js';
import { ApolloServerPluginDrainHttpServer, ApolloServerPluginLandingPageGraphQLPlayground } from 'apollo-server-core';
import { ApolloServer } from 'apollo-server-express';
import Gists from 'gists';
import gql from 'graphql-tag';
import _ from 'lodash';
import os from 'os';
import path from 'path';
import url from 'url';
import { DeepClient } from '../client.js';
import { Packager } from '../packager.js';
const tmpdir = os.tmpdir();
const client = generateApolloClient({
    path: `${process.env.DEEPLINKS_HASURA_PATH}/v1/graphql`,
    ssl: !!+process.env.DEEPLINKS_HASURA_SSL,
    secret: process.env.DEEPLINKS_HASURA_SECRET,
});
const deep = new DeepClient({ apolloClient: client });
const packager = new Packager(deep);
export const typeDefsString = `
  type Query {
    packager_install(input: PackagerInstallInput): PackagerInstallOutput
    packager_publish(input: PackagerPublishInput): PackagerPublishOutput
  }
  input PackagerInstallInput {
    address: String
  }
  type PackagerInstallOutput {
    ids: [Int]
    errors: [String]
    packageId: Int
  }
  input PackagerPublishInput {
    id: Int
    address: String
  }
  type PackagerPublishOutput {
    errors: [String]
    address: String
  }
`;
export const typeDefs = gql `${typeDefsString}`;
export const packagerInstallCore = (errors = [], address) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b;
    const uri = new url.URL(address);
    const isGist = uri.hostname === 'gist.github.com';
    const isNpm = uri.hostname === 'npmjs.com' || uri.hostname === 'www.npmjs.com';
    if (isGist) {
        const username = uri.username;
        const gistId = uri.pathname.split('/')[2];
        if (!username) {
            errors.push('gist requires token');
        }
        if (!gistId) {
            errors.push('gist valid address like http://gist.github.com/account/gist');
        }
        if (errors.length)
            return { errors };
        const gists = new Gists({ token: username });
        const result = yield gists.get(gistId);
        const files = (_a = result === null || result === void 0 ? void 0 : result.body) === null || _a === void 0 ? void 0 : _a.files;
        const deepPckgContent = (_b = files === null || files === void 0 ? void 0 : files['deep.json']) === null || _b === void 0 ? void 0 : _b.content;
        if (deepPckgContent) {
            try {
                const deepPckg = JSON.parse(deepPckgContent);
                const { ids, errors, packageId } = yield packager.import(deepPckg);
                return { ids, errors, packageId };
            }
            catch (e) {
                errors.push(String(e));
            }
        }
        else {
            errors.push(`deep.json not found in gist`);
        }
    }
    else {
        errors.push(`address is not valid`);
    }
});
export const packagerPublishCore = (errors = [], address, id) => __awaiter(void 0, void 0, void 0, function* () {
    var _c, _d, _e, _f, _g, _h;
    console.log('packagerPublishCore');
    if (!id)
        return { errors: ['!id'] };
    const packageResults = yield deep.select(id);
    if (!((_c = packageResults.data) === null || _c === void 0 ? void 0 : _c.length))
        return { errors: ['!package'] };
    const uri = new url.URL(address);
    const isGist = uri.hostname === 'gist.github.com';
    const isNpm = uri.hostname === 'npmjs.com' || uri.hostname === 'www.npmjs.com';
    console.log('packagerPublishCore', { isGist, isNpm });
    if (isGist) {
        const username = uri.username;
        const gistId = uri.pathname.split('/')[2];
        console.log('packagerPublishCore', { username, gistId });
        if (!username) {
            errors.push('gist requires token');
        }
        if (errors.length)
            return { errors };
        if (gistId) {
            const deepPckgContent = yield packager.export({ packageLinkId: id });
            console.log('packagerPublishCore deepPckgContent', deepPckgContent);
            if ((_d = deepPckgContent === null || deepPckgContent === void 0 ? void 0 : deepPckgContent.errors) === null || _d === void 0 ? void 0 : _d.length) {
                errors.push(...deepPckgContent.errors);
            }
            if (_.isEmpty(deepPckgContent === null || deepPckgContent === void 0 ? void 0 : deepPckgContent.package)) {
                errors.push('!package');
            }
            if (_.isEmpty(deepPckgContent === null || deepPckgContent === void 0 ? void 0 : deepPckgContent.data)) {
                errors.push('!data');
            }
            if (errors.length)
                return { errors };
            const gists = new Gists({ token: username });
            console.log('packagerPublishCore gists.edit', gistId, { files: { 'deep.json': { content: JSON.stringify(deepPckgContent) } } });
            const result = yield gists.edit(gistId, { files: { 'deep.json': { content: JSON.stringify(deepPckgContent) } } });
            console.log('packagerPublishCore result', result);
            if ((_e = result === null || result === void 0 ? void 0 : result.body) === null || _e === void 0 ? void 0 : _e.id)
                return { errors, address: `https://${username}@gist.github.com${uri.pathname}` };
        }
        else {
            const deepPckgContent = yield packager.export({ packageLinkId: id });
            if ((_f = deepPckgContent === null || deepPckgContent === void 0 ? void 0 : deepPckgContent.errors) === null || _f === void 0 ? void 0 : _f.length) {
                errors.push(...deepPckgContent.errors);
                return { errors };
            }
            const gists = new Gists({ token: username });
            const result = yield gists.create({ files: { 'deep.json': { content: JSON.stringify(deepPckgContent) } } });
            if ((_g = result === null || result === void 0 ? void 0 : result.body) === null || _g === void 0 ? void 0 : _g.id)
                return { errors, address: `https://${username}@gist.github.com${path.normalize(`${uri.pathname}/${(_h = result === null || result === void 0 ? void 0 : result.body) === null || _h === void 0 ? void 0 : _h.id}`)}` };
        }
        if (errors.length)
            return { errors };
    }
});
const resolvers = {
    Query: {
        packager_install: (source, args, context, info) => __awaiter(void 0, void 0, void 0, function* () {
            var _j, _k, _l, _m;
            const errors = [];
            if (((_j = context === null || context === void 0 ? void 0 : context.headers) === null || _j === void 0 ? void 0 : _j['x-hasura-role']) !== 'admin' &&
                !(yield deep.can(yield deep.id('@deep-foundation/core', 'AllowPackageInstall'), +((_k = context === null || context === void 0 ? void 0 : context.headers) === null || _k === void 0 ? void 0 : _k['x-hasura-user-id']), yield deep.id('@deep-foundation/core', 'AllowPackageInstall'))) &&
                !(yield deep.can(null, +((_l = context === null || context === void 0 ? void 0 : context.headers) === null || _l === void 0 ? void 0 : _l['x-hasura-user-id']), yield deep.id('@deep-foundation/core', 'AllowAdmin')))) {
                errors.push('cant');
                return { errors };
            }
            const { address } = args.input;
            const result = yield packagerInstallCore(errors, (_m = args.input) === null || _m === void 0 ? void 0 : _m.address);
            if (result)
                return result;
            return { ids: [], errors };
        }),
        packager_publish: (source, args, context, info) => __awaiter(void 0, void 0, void 0, function* () {
            var _o, _p, _q, _r, _s, _t, _u;
            const errors = [];
            console.log({
                userId: +((_o = context === null || context === void 0 ? void 0 : context.headers) === null || _o === void 0 ? void 0 : _o['x-hasura-user-id']),
                roleAdmin: ((_p = context === null || context === void 0 ? void 0 : context.headers) === null || _p === void 0 ? void 0 : _p['x-hasura-role']) === 'admin',
                AllowPackagePublish: yield deep.can(yield deep.id('@deep-foundation/core', 'AllowPackagePublish'), +((_q = context === null || context === void 0 ? void 0 : context.headers) === null || _q === void 0 ? void 0 : _q['x-hasura-user-id']), yield deep.id('@deep-foundation/core', 'AllowPackagePublish')),
                AllowAdmin: yield deep.can(null, +((_r = context === null || context === void 0 ? void 0 : context.headers) === null || _r === void 0 ? void 0 : _r['x-hasura-user-id']), yield deep.id('@deep-foundation/core', 'AllowAdmin')),
            });
            if (((_s = context === null || context === void 0 ? void 0 : context.headers) === null || _s === void 0 ? void 0 : _s['x-hasura-role']) !== 'admin' &&
                !(yield deep.can(yield deep.id('@deep-foundation/core', 'AllowPackagePublish'), +((_t = context === null || context === void 0 ? void 0 : context.headers) === null || _t === void 0 ? void 0 : _t['x-hasura-user-id']), yield deep.id('@deep-foundation/core', 'AllowPackagePublish'))) &&
                !(yield deep.can(null, +((_u = context === null || context === void 0 ? void 0 : context.headers) === null || _u === void 0 ? void 0 : _u['x-hasura-user-id']), yield deep.id('@deep-foundation/core', 'AllowAdmin')))) {
                errors.push('cant');
                return { errors };
            }
            const { id, address } = args.input;
            const result = yield packagerPublishCore(errors, address, id);
            if (result)
                return result;
            return { errors };
        }),
    }
};
const context = ({ req }) => {
    return { headers: req.headers };
};
const generateApolloServer = (httpServer) => {
    return new ApolloServer({
        introspection: true,
        typeDefs,
        resolvers,
        context,
        plugins: [
            ApolloServerPluginDrainHttpServer({ httpServer }),
            ApolloServerPluginLandingPageGraphQLPlayground()
        ]
    });
};
export default generateApolloServer;
//# sourceMappingURL=packager.js.map