All files / blong-gogo/src layerProxy.ts

85.55% Statements 231/270
74.5% Branches 38/51
85.71% Functions 6/7
85.55% Lines 231/270

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 2711x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 169x 169x 169x 169x 1x 90x 90x 90x       90x 90x 90x 169x 169x 82x 82x 82x 82x 82x 179x 179x     179x 23x 23x 11x 179x 179x 82x 179x 179x 179x 179x     179x     179x 179x 179x 179x 156x 156x 156x 156x 156x 156x 156x         156x 20x 156x 136x 136x 136x 136x 156x 179x 179x 82x 76x 1x 1x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 579x 579x 579x 579x 579x 579x   579x   579x 292x 579x 287x 287x 287x 287x 287x 287x 285x 285x 285x 285x 394x 394x 394x 394x 394x 185x 394x 394x 285x 285x 285x 209x                                               209x 209x 99x 99x 99x 99x 99x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 99x 99x 99x 99x 99x 99x   55x 55x 55x 55x 209x 209x 209x 285x 285x 76x 76x 76x 76x 76x 76x 76x 76x 76x 285x 285x 285x 287x 287x 579x 579x 292x 292x 292x  
import {
    kind,
    type Adapter,
    type IAdapterFactory,
    type IApiSchema,
    type IConfigRuntime,
    type IErrorFactory,
    type ILib,
    type IMeta,
    type IModuleConfig,
} from '@feasibleone/blong/types';
import merge from 'ut-function.merge';
 
import createPort from './AdapterBase.ts';
import ConfigRuntime from './ConfigRuntime.ts';
import createHandlerProxy from './handlerProxy.ts';
import {methodId} from './lib.ts';
import type {IPort} from './Port.ts';
 
/**
 * Create the handler closure that is pushed into `where.methods[]`.
 *
 * This closure is invoked later by `Registry._createHandlers()` to assemble the
 * layerApi object, load libraries, and process handler/validation/api/model items.
 */
function createHandlerClosure(
    others: any[], // eslint-disable-line @typescript-eslint/no-explicit-any
    moduleConfigSlice: unknown,
    name: string,
    namespace: string,
    source: string,
    target: {result: {error: unknown}},
    apiSchema: IApiSchema | undefined,
    configRuntime: IConfigRuntime | undefined,
): (params: {
    remote: (methodName: string) => () => unknown;
    lib: ILib;
    local: object;
    literals: unknown[];
    port: Adapter;
    attachCheckpoint?: (meta: IMeta) => void;
}) => Promise<void> {
    return async function ({
        remote,
        lib,
        local,
        literals,
        port,
        attachCheckpoint,
        ...rest
    }: {
        remote: (methodName: string) => () => unknown;
        lib: ILib;
        local: object;
        literals: unknown[];
        port: Adapter;
        attachCheckpoint?: (meta: IMeta) => void;
    }) {
        const mergedConfig = ConfigRuntime.mergeLayerConfig(
            moduleConfigSlice,
            port?.config?.[namespace],
        );
        const layerApi = {
            ...rest,
            config: mergedConfig,
            lib: new Proxy(lib, {
                get(target: ILib, functionName: string) {
                    const rec = target as unknown as Record<string, unknown>;
                    let fn: () => unknown;
                    return (
                        rec[functionName] ??
                        function (...params: unknown[]) {
                            fn ||= rec[functionName] as () => unknown;
                            if (!fn)
                                throw new Error(
                                    `Lib property '${functionName.toString()}' not found. Available properties are: ${Object.keys(
                                        rec,
                                    ).sort()}`,
                                );
                            return fn.apply(port, params as []);
                        }
                    );
                },
            }),
            handler: createHandlerProxy(local, port, remote, attachCheckpoint, lib, mergedConfig),
            errors: target.result.error,
        };
        for (let what of others) {
            switch (`${typeof what}:${kind(what)}`) {
                case 'object:lib':
                    merge(lib, what);
                    break;
                case 'function:lib':
                    what = await what(layerApi);
                    if (typeof what === 'function') (lib as unknown as Record<string, unknown>)[what.name] = what;
                    else merge(lib, what);
            }
        }
        for (let what of others) {
            const kindOfWhat = kind(what);
            switch (`${typeof what}:${kindOfWhat}`) {
                case 'object:handler':
                case 'object:validation':
                    merge(local, what);
                    break;
                case 'function:api':
                    merge(local, await apiSchema!.schema(what(layerApi), source));
                    break;
                case 'function:handler':
                case 'function:validation':
                case 'function:model':
                case 'function:fixture':
                    configRuntime?.enterConfig();
                    try {
                        what = await what(layerApi);
                    } finally {
                        configRuntime?.exitConfig();
                    }
                    const created = await (port as unknown as {createHandlers?: (opts: unknown) => Promise<unknown>})?.createHandlers?.({
                        handlers: typeof what === 'function' ? [what] : what,
                        layerApi,
                        kind: kindOfWhat,
                    });
                    if (typeof what === 'function') {
                        (local as Record<string, unknown>)[methodId(what.name)] = what;
                    } else {
                        literals.push(what);
                        what = methodId(what);
                        merge(local, what);
                    }
                    Object.assign(local, methodId(created));
            }
        }
    };
}
 
export default function layerProxy(
    errors: IErrorFactory | undefined,
    apiSchema: IApiSchema | undefined,
    port: (() => void) | undefined,
    moduleConfig: {
        pkg: IModuleConfig['pkg'];
        base: string;
        configNames?: string[];
    } & {
        [name: string]: object;
    },
    configRuntime?: IConfigRuntime,
): {result: {error: unknown}; feature: unknown} {
    return new Proxy(
        {
            error: errors?.register.bind(errors),
            result: {error: errors?.get()},
            feature() {},
        },
        {
            get(
                target: {error: unknown; result: {error: unknown}; feature: unknown},
                name: string,
                receiver: unknown,
            ) {
                switch (name) {
                    case 'utPort':
                        return port;
                    case 'registerErrors':
                        return target.error;
                    case 'result':
                        return target.result;
                    default:
                        return (fn: unknown, namespace: string, source: string) => {
                            type Where = {methods: unknown[]; port?: unknown; source?: string; config?: unknown};
                            const resultRecord = target.result as Record<string, Where>;
                            const where: Where = (resultRecord[name] ??= {methods: [], source});
                            const targetRec = target as unknown as Record<string, ((fn: unknown) => void) | undefined>;
                            if (targetRec[name]) merge(where, targetRec[name]!(fn));
                            else {
                                const fnArr: unknown[] = Array.isArray(fn) ? fn : fn != null ? [fn] : [];
                                const [ports, others] = fnArr.reduce(
                                    (prev: [unknown[], unknown[]], item: unknown) => {
                                        if (
                                            (port && (item as {prototype?: unknown}).prototype instanceof port) ||
                                            ['adapter', 'orchestrator'].includes(kind(item as unknown as Parameters<typeof kind>[0]))
                                        )
                                            prev[0].push(item);
                                        else prev[1].push(item);
                                        return prev;
                                    },
                                    [[], []] as [unknown[], unknown[]],
                                ) as [unknown[], unknown[]];
                                ports.forEach(what => {
                                    if (what && port && (what as {prototype?: unknown}).prototype instanceof port) {
                                        where.port = async (
                                            {
                                                id,
                                                ...portApi
                                            }: Parameters<IAdapterFactory>[0] & {id: string},
                                            configOverride: object,
                                        ) => {
                                            const config = {
                                                ...moduleConfig?.[name],
                                                id,
                                                pkg: moduleConfig.pkg,
                                            };
                                            const port = new (what as unknown as IPort)({
                                                ...portApi,
                                                config: configOverride
                                                    ? merge({}, config, configOverride)
                                                    : config,
                                                configBase: moduleConfig.base,
                                            });
                                            await (port as unknown as {init: () => Promise<void>}).init();
                                            return port;
                                        };
                                        (where.port as unknown as {config: unknown}).config = moduleConfig?.[name];
                                    } else if (what && ['adapter', 'orchestrator'].includes(kind(what as unknown as Parameters<typeof kind>[0]))) {
                                        where.port = async (
                                            api: Parameters<IAdapterFactory>[0] & {id: string},
                                            configOverride: object,
                                        ) => {
                                            const {id} = api;
                                            if (!id) return (what as IAdapterFactory)(api as Parameters<IAdapterFactory>[0]);
                                            // Assign `handlers` directly onto the api object rather
                                            // than creating a spread copy.  AdapterBase stores
                                            // `_api = api`, and Registry.ts sets
                                            // `api.attachHandlers = fn` *after* this factory
                                            // returns.  Keeping the same object reference ensures
                                            // that assignment is visible to `_api.attachHandlers`
                                            // when `start()` is called later.
                                            (api as unknown as Record<string, unknown>).handlers = what;
                                            const port = await createPort(
                                                api as unknown as Parameters<typeof createPort>[0],
                                                moduleConfig.base,
                                                moduleConfig.configNames,
                                            );
                                            const config = {
                                                ...moduleConfig?.[name],
                                                id,
                                                pkg: moduleConfig.pkg,
                                            };
                                            await port.init(
                                                configOverride
                                                    ? merge({}, config, configOverride)
                                                    : config,
                                            );
                                            return port;
                                        };
                                        (where.port as unknown as {config: unknown}).config = moduleConfig?.[name];
                                    }
                                });
                                if (others.length)
                                    where.methods.push(
                                        createHandlerClosure(
                                            others as unknown[],
                                            moduleConfig[name],
                                            name,
                                            namespace,
                                            source,
                                            target,
                                            apiSchema,
                                            configRuntime,
                                        ),
                                    );
                            }
                            return receiver;
                        };
                }
            },
        },
    );
}