/* ** Copyright (c) 2026 Oracle and/or its affiliates. All rights reserved. ** Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ 'use strict'; import { randomBytes } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import { basename } from 'node:path'; import type { ProjectCommandType } from '../../api/project/ProjectCommand'; import { sendSuiteCloudRequest } from '../../services/http/SuiteCloudRequestService'; import { PROJECT_API } from '../../services/translation/TranslationKeys'; import { translationService } from '../../services/translation/TranslationService'; export type ProjectCommandRequest = { command: ProjectCommandType; hostName: string; accessToken: string; projectArchivePath: string; params: Record; flags: string[]; userAgent?: string; timeoutMs: number; }; export type ProjectCommandHttpResponse = { statusCode: number; body: string; serverTimestamp?: string; }; const PROJECT_API_PATH = '/api/internal/sdf/v1/projects'; const MULTIPART_EOL = '\r\n'; const PROJECT_ACTION_FIELD_NAME = 'action'; const PROJECT_FILE_FIELD_NAME = 'sdfProjectZip'; const QUERY_PARAM_APPLY_INSTALLATION_PREFERENCES = 'applyinstallprefs'; const QUERY_PARAM_ACCOUNT_SPECIFIC_VALUES = 'accountspecificvalues'; const BOOLEAN_TRUE_T = 'T'; const BOOLEAN_FALSE_F = 'F'; const ACCOUNT_SPECIFIC_VALUES_DEFAULT = 'ERROR'; const HEADER_SDF_ACTION = 'Sdf-Action'; export async function sendProjectCommandRequest( request: ProjectCommandRequest ): Promise { const multipartPayload = await buildMultipartPayload(request.command, request.projectArchivePath); return sendHttpsMultipartRequest({ hostName: request.hostName, pathname: buildProjectRequestPath(request.params, request.flags), accessToken: request.accessToken, payload: multipartPayload.payload, boundary: multipartPayload.boundary, userAgent: request.userAgent, sdfAction: request.command, timeoutMs: request.timeoutMs, }); } function buildProjectRequestPath(params: Record, flags: string[]): string { const queryParams = new URLSearchParams(); queryParams.set( QUERY_PARAM_APPLY_INSTALLATION_PREFERENCES, resolveApplyInstallationPreferencesValue(params, flags) ? BOOLEAN_TRUE_T : BOOLEAN_FALSE_F ); queryParams.set(QUERY_PARAM_ACCOUNT_SPECIFIC_VALUES, resolveAccountSpecificValuesValue(params)); return `${PROJECT_API_PATH}?${queryParams.toString()}`; } function resolveApplyInstallationPreferencesValue(params: Record, flags: string[]): boolean { return flags.includes(QUERY_PARAM_APPLY_INSTALLATION_PREFERENCES) ? true : asBoolean(params[QUERY_PARAM_APPLY_INSTALLATION_PREFERENCES]); } function resolveAccountSpecificValuesValue(params: Record): string { const value = params[QUERY_PARAM_ACCOUNT_SPECIFIC_VALUES]; return typeof value === 'string' && value.trim() ? value : ACCOUNT_SPECIFIC_VALUES_DEFAULT; } function asBoolean(value: unknown): boolean { if (typeof value === 'boolean') { return value; } if (typeof value === 'string') { const normalizedValue = value.trim().toUpperCase(); return normalizedValue === 'TRUE' || normalizedValue === BOOLEAN_TRUE_T; } return false; } async function buildMultipartPayload( command: ProjectCommandType, projectArchivePath: string ): Promise<{ payload: Buffer; boundary: string }> { const archiveBuffer = await readFile(projectArchivePath); const boundary = `suitecloudboundary${randomBytes(10).toString('hex')}`; const chunks: Buffer[] = []; appendFilePart(chunks, boundary, PROJECT_FILE_FIELD_NAME, basename(projectArchivePath), archiveBuffer); appendTextPart(chunks, boundary, PROJECT_ACTION_FIELD_NAME, command); chunks.push(Buffer.from(`--${boundary}--${MULTIPART_EOL}`)); return { payload: Buffer.concat(chunks), boundary }; } function appendTextPart(chunks: Buffer[], boundary: string, fieldName: string, value: string): void { chunks.push(Buffer.from(`--${boundary}${MULTIPART_EOL}`)); chunks.push(Buffer.from(`Content-Disposition: form-data; name="${fieldName}"${MULTIPART_EOL}${MULTIPART_EOL}`)); chunks.push(Buffer.from(`${value}${MULTIPART_EOL}`)); } function appendFilePart( chunks: Buffer[], boundary: string, fieldName: string, filename: string, data: Buffer ): void { chunks.push(Buffer.from(`--${boundary}${MULTIPART_EOL}`)); chunks.push( Buffer.from( `Content-Disposition: form-data; name="${fieldName}"; filename="${filename}"${MULTIPART_EOL}` + `Content-Type: application/zip${MULTIPART_EOL}${MULTIPART_EOL}` ) ); chunks.push(data); chunks.push(Buffer.from(MULTIPART_EOL)); } function sendHttpsMultipartRequest(input: { hostName: string; pathname: string; accessToken: string; payload: Buffer; boundary: string; userAgent?: string; sdfAction: string; timeoutMs: number; }): Promise { return sendSuiteCloudRequest({ hostName: input.hostName, accessToken: input.accessToken, method: 'POST', path: input.pathname, headers: { 'Content-Type': `multipart/form-data; boundary=${input.boundary}`, 'Content-Length': String(input.payload.length), Accept: 'application/json', [HEADER_SDF_ACTION]: input.sdfAction, ...(input.userAgent ? { 'User-Agent': input.userAgent } : {}), }, body: input.payload, timeoutMs: input.timeoutMs, timeoutMessage: translationService.getMessage(PROJECT_API.ERROR.REQUEST_TIMED_OUT), }).then((response) => ({ statusCode: response.statusCode, body: response.body.toString('utf8'), serverTimestamp: asHeaderString(response.headers.date), })); } function asHeaderString(value: string | string[] | undefined): string | undefined { if (typeof value === 'string' && value.trim()) { return value.trim(); } if (Array.isArray(value)) { return value.find((headerValue) => headerValue.trim())?.trim(); } return undefined; }