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 { Time } from '../utils/time.js';
import { validateMessageSignatureIntegrity } from '../core/auth.js';
import { DwnError, DwnErrorCode } from '../index.js';
import { DwnInterfaceName, DwnMethodName, Message } from '../core/message.js';
import { normalizeProtocolUrl, normalizeSchemaUrl, validateProtocolUrlNormalized, validateSchemaUrlNormalized } from '../utils/url.js';
export class ProtocolsConfigure extends Message {
    static parse(message) {
        return __awaiter(this, void 0, void 0, function* () {
            Message.validateJsonSchema(message);
            ProtocolsConfigure.validateProtocolDefinition(message.descriptor.definition);
            yield validateMessageSignatureIntegrity(message.authorization.signature, message.descriptor);
            Time.validateTimestamp(message.descriptor.messageTimestamp);
            return new ProtocolsConfigure(message);
        });
    }
    static create(options) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const descriptor = {
                interface: DwnInterfaceName.Protocols,
                method: DwnMethodName.Configure,
                messageTimestamp: (_a = options.messageTimestamp) !== null && _a !== void 0 ? _a : Time.getCurrentTimestamp(),
                definition: ProtocolsConfigure.normalizeDefinition(options.definition)
            };
            const authorization = yield Message.createAuthorization(descriptor, options.signer, { permissionsGrantId: options.permissionsGrantId });
            const message = { descriptor, authorization };
            Message.validateJsonSchema(message);
            ProtocolsConfigure.validateProtocolDefinition(message.descriptor.definition);
            const protocolsConfigure = new ProtocolsConfigure(message);
            return protocolsConfigure;
        });
    }
    static validateProtocolDefinition(definition) {
        const { protocol, types } = definition;
        // validate protocol url
        validateProtocolUrlNormalized(protocol);
        // validate schema url normalized
        for (const typeName in types) {
            const schema = types[typeName].schema;
            if (schema !== undefined) {
                validateSchemaUrlNormalized(schema);
            }
        }
        // validate `structure
        ProtocolsConfigure.validateStructure(definition);
    }
    static validateStructure(definition) {
        // gather $globalRoles
        const globalRoles = [];
        for (const rootRecordPath in definition.structure) {
            const rootRuleSet = definition.structure[rootRecordPath];
            if (rootRuleSet.$globalRole) {
                globalRoles.push(rootRecordPath);
            }
        }
        // Traverse nested rule sets
        for (const rootRecordPath in definition.structure) {
            const rootRuleSet = definition.structure[rootRecordPath];
            // gather $contextRoles
            const contextRoles = [];
            for (const childRecordType in rootRuleSet) {
                if (childRecordType.startsWith('$')) {
                    continue;
                }
                const childRuleSet = rootRuleSet[childRecordType];
                if (childRuleSet.$contextRole) {
                    contextRoles.push(`${rootRecordPath}/${childRecordType}`);
                }
            }
            ProtocolsConfigure.validateRuleSet(rootRuleSet, rootRecordPath, [...globalRoles, ...contextRoles]);
        }
    }
    /**
     * Validates the given rule set structure then recursively validates its nested child rule sets.
     */
    static validateRuleSet(ruleSet, protocolPath, roles) {
        var _a;
        const depth = protocolPath.split('/').length;
        if (ruleSet.$globalRole && depth !== 1) {
            throw new DwnError(DwnErrorCode.ProtocolsConfigureGlobalRoleAtProhibitedProtocolPath, `$globalRole is not allowed at protocol path (${protocolPath}). Only root records may set $globalRole true.`);
        }
        else if (ruleSet.$contextRole && depth !== 2) {
            throw new DwnError(DwnErrorCode.ProtocolsConfigureContextRoleAtProhibitedProtocolPath, `$contextRole is not allowed at protocol path (${protocolPath}). Only second-level records may set $contextRole true.`);
        }
        // Validate $actions in the ruleset
        const actions = (_a = ruleSet.$actions) !== null && _a !== void 0 ? _a : [];
        for (const action of actions) {
            // Validate that all `role` properties contain protocol paths $globalRole or $contextRole records
            if (action.role !== undefined && !roles.includes(action.role)) {
                throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidRole, `Invalid role '${action.role}' found at protocol path '${protocolPath}'`);
            }
            // Validate that if `who` is set to `anyone` then `of` is not set
            if (action.who === 'anyone' && action.of) {
                throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidActionOfNotAllowed, `'of' is not allowed at protocol path (${protocolPath})`);
            }
            // Validate that if `who` is not set to `anyone` then `of` is set
            if (action.who !== undefined && ['author', 'recipient'].includes(action.who) && !action.of) {
                throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidActionMissingOf, `'of' is required at protocol path (${protocolPath})`);
            }
        }
        // Validate nested rule sets
        for (const recordType in ruleSet) {
            if (recordType.startsWith('$')) {
                continue;
            }
            const rootRuleSet = ruleSet[recordType];
            const nextProtocolPath = `${protocolPath}/${recordType}`;
            ProtocolsConfigure.validateRuleSet(rootRuleSet, nextProtocolPath, roles);
        }
    }
    static normalizeDefinition(definition) {
        const typesCopy = Object.assign({}, definition.types);
        // Normalize schema url
        for (const typeName in typesCopy) {
            const schema = typesCopy[typeName].schema;
            if (schema !== undefined) {
                typesCopy[typeName].schema = normalizeSchemaUrl(schema);
            }
        }
        return Object.assign(Object.assign({}, definition), { protocol: normalizeProtocolUrl(definition.protocol), types: typesCopy });
    }
}
//# sourceMappingURL=protocols-configure.js.map