c8y-nitro 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bootstrap-CGOe2HxK.mjs +61 -0
- package/dist/{cli/utils/c8y-api.mjs → c8y-api-BBSKRwKs.mjs} +73 -3
- package/dist/cli/index.mjs +5 -7
- package/dist/{cli/utils/config.mjs → config-Dqi-ttQi.mjs} +1 -3
- package/dist/{cli/utils/env-file.mjs → env-file-B0BK-uZW.mjs} +1 -3
- package/dist/{types/manifest.d.mts → index-B6HtYHU0.d.mts} +94 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +542 -11
- package/dist/{cli/commands/options.mjs → options-CuGdGP4l.mjs} +27 -30
- package/dist/{package.mjs → package-BAjMvZYS.mjs} +2 -3
- package/dist/{cli/commands/roles.mjs → roles-DrJsxUG-.mjs} +11 -14
- package/dist/runtime/handlers/liveness-readiness.d.mts +8 -0
- package/dist/runtime/handlers/liveness-readiness.mjs +7 -0
- package/dist/runtime/middlewares/dev-user.d.mts +6 -0
- package/dist/runtime/middlewares/dev-user.mjs +23 -0
- package/dist/runtime/plugins/c8y-variables.d.mts +6 -0
- package/dist/runtime/plugins/c8y-variables.mjs +17 -0
- package/dist/types.d.mts +2 -25
- package/dist/types.mjs +1 -1
- package/dist/utils.d.mts +292 -6
- package/dist/utils.mjs +444 -8
- package/package.json +10 -10
- package/dist/cli/commands/bootstrap.mjs +0 -64
- package/dist/module/apiClient.mjs +0 -207
- package/dist/module/autoBootstrap.mjs +0 -54
- package/dist/module/c8yzip.mjs +0 -66
- package/dist/module/constants.mjs +0 -6
- package/dist/module/docker.mjs +0 -101
- package/dist/module/manifest.mjs +0 -72
- package/dist/module/probeCheck.mjs +0 -30
- package/dist/module/register.mjs +0 -58
- package/dist/module/runtime/handlers/liveness-readiness.ts +0 -7
- package/dist/module/runtime/middlewares/dev-user.ts +0 -25
- package/dist/module/runtime/plugins/c8y-variables.ts +0 -24
- package/dist/module/runtime.mjs +0 -38
- package/dist/module/runtimeConfig.mjs +0 -20
- package/dist/types/apiClient.d.mts +0 -16
- package/dist/types/cache.d.mts +0 -28
- package/dist/types/roles.d.mts +0 -4
- package/dist/types/tenantOptions.d.mts +0 -13
- package/dist/types/zip.d.mts +0 -22
- package/dist/utils/client.d.mts +0 -52
- package/dist/utils/client.mjs +0 -90
- package/dist/utils/credentials.d.mts +0 -71
- package/dist/utils/credentials.mjs +0 -120
- package/dist/utils/internal/common.mjs +0 -26
- package/dist/utils/logging.d.mts +0 -3
- package/dist/utils/logging.mjs +0 -4
- package/dist/utils/middleware.d.mts +0 -89
- package/dist/utils/middleware.mjs +0 -62
- package/dist/utils/resources.d.mts +0 -30
- package/dist/utils/resources.mjs +0 -49
- package/dist/utils/tenantOptions.d.mts +0 -65
- package/dist/utils/tenantOptions.mjs +0 -127
package/dist/index.mjs
CHANGED
|
@@ -1,14 +1,546 @@
|
|
|
1
|
-
import { createC8yManifestFromNitro } from "./
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import
|
|
1
|
+
import { a as findMicroserviceByName, g as GENERATED_READINESS_ROUTE, h as GENERATED_LIVENESS_ROUTE, l as subscribeToApplication, m as createC8yManifestFromNitro, n as createBasicAuthHeader, o as getBootstrapCredentials, p as createC8yManifest, r as createMicroservice } from "./c8y-api-BBSKRwKs.mjs";
|
|
2
|
+
import { t as writeBootstrapCredentials } from "./env-file-B0BK-uZW.mjs";
|
|
3
|
+
import { n as name } from "./package-BAjMvZYS.mjs";
|
|
4
|
+
import { basename, dirname, join, relative } from "node:path";
|
|
5
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
6
|
+
import { x } from "tinyexec";
|
|
7
|
+
import { join as join$1 } from "pathe";
|
|
8
|
+
import { mkdir as mkdir$1, readFile as readFile$1, stat, writeFile as writeFile$1 } from "fs/promises";
|
|
9
|
+
import JSZip from "jszip";
|
|
10
|
+
import Spinnies from "spinnies";
|
|
11
|
+
import { colors } from "consola/utils";
|
|
12
|
+
import { mkdirSync, writeFileSync } from "fs";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
import process from "node:process";
|
|
10
15
|
import evlog from "evlog/nitro/v3";
|
|
16
|
+
//#region src/module/apiClient.ts
|
|
17
|
+
/**
|
|
18
|
+
* Converts route path to PascalCase function name.
|
|
19
|
+
* Examples:
|
|
20
|
+
* - /health + get -> GetHealth
|
|
21
|
+
* - /health + post -> PostHealth
|
|
22
|
+
* - /someRoute -> SomeRoute (default)
|
|
23
|
+
* - /[id] or /:id + get -> GetById
|
|
24
|
+
* - /api/[multiple]/[params] -> GetApiByMultipleByParams
|
|
25
|
+
* @param path - The route path (e.g., "/api/[id]" or "/api/:id")
|
|
26
|
+
* @param method - HTTP method (get, post, put, delete, etc.)
|
|
27
|
+
*/
|
|
28
|
+
function generateFunctionName(path, method) {
|
|
29
|
+
return `${method}${path.replace(/^\//, "").replaceAll(".", "_").replaceAll("*", "").split("/").map((seg) => {
|
|
30
|
+
if (seg.startsWith("[") && seg.endsWith("]")) return `By${capitalize(seg.slice(1, -1))}`;
|
|
31
|
+
if (seg.startsWith(":")) return `By${capitalize(seg.slice(1))}`;
|
|
32
|
+
return capitalize(seg);
|
|
33
|
+
}).join("") || "Index"}`;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Extracts route parameters from path.
|
|
37
|
+
* Example: "/api/[id]/items/[itemId]" or "/api/:id/items/:itemId" -> [{name: "id", type: "string"}, {name: "itemId", type: "string"}]
|
|
38
|
+
* @param path - The route path to extract parameters from
|
|
39
|
+
*/
|
|
40
|
+
function extractParams(path) {
|
|
41
|
+
const params = [];
|
|
42
|
+
const segments = path.split("/");
|
|
43
|
+
for (const seg of segments) if (seg.startsWith("[") && seg.endsWith("]")) {
|
|
44
|
+
const name = seg.slice(1, -1);
|
|
45
|
+
params.push(name);
|
|
46
|
+
} else if (seg.startsWith(":")) {
|
|
47
|
+
const name = seg.slice(1);
|
|
48
|
+
params.push(name);
|
|
49
|
+
}
|
|
50
|
+
return params;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Capitalizes first letter of a string.
|
|
54
|
+
* @param str - The string to capitalize
|
|
55
|
+
*/
|
|
56
|
+
function capitalize(str) {
|
|
57
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Converts a file name to a valid JavaScript class name.
|
|
61
|
+
* Only allows letters, numbers (not at start), $ and _.
|
|
62
|
+
* Removes or replaces invalid characters and ensures PascalCase.
|
|
63
|
+
* Always prefixed with "Generated" for clarity.
|
|
64
|
+
* @param fileName - The file name to convert
|
|
65
|
+
* @example "my-service-api" -> "GeneratedMyServiceApi"
|
|
66
|
+
* @example "playgroundAPIClient" -> "GeneratedPlaygroundAPIClient"
|
|
67
|
+
* @example "special@chars!" -> "GeneratedSpecialchars"
|
|
68
|
+
*/
|
|
69
|
+
function toValidClassName(fileName) {
|
|
70
|
+
let cleaned = fileName.replace(/\.(ts|js|mjs|cjs|tsx|jsx)$/, "").replace(/[-_.]/g, " ");
|
|
71
|
+
cleaned = cleaned.replace(/[^a-zA-Z0-9\s$]/g, "");
|
|
72
|
+
return `Generated${cleaned.split(/\s+/).filter((word) => word.length > 0).map((word) => capitalize(word)).join("")}`;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Generates TypeScript method code for a route in an Angular service.
|
|
76
|
+
* @param route - Parsed route information including path, method, params, and return type
|
|
77
|
+
*/
|
|
78
|
+
function generateMethod(route) {
|
|
79
|
+
const hasParams = route.params.length > 0;
|
|
80
|
+
let inlineParamsType = "";
|
|
81
|
+
if (hasParams) inlineParamsType = `{ ${route.params.map((name) => `${name}: string | number`).join("; ")} }`;
|
|
82
|
+
const methodParam = hasParams ? `params: ${inlineParamsType}` : "";
|
|
83
|
+
const returnTypeAnnotation = `Promise<${route.returnType}>`;
|
|
84
|
+
let pathExpression = `\`\${this.BASE_PATH}${route.path}\``;
|
|
85
|
+
if (hasParams) pathExpression = `\`\${this.BASE_PATH}${route.path.replace(/\[([^\]]+)\]/g, (_, paramName) => `\${params.${paramName}}`)}\``;
|
|
86
|
+
const fetchOptions = `{ method: '${route.method}', headers: { 'Content-Type': 'application/json' } }`;
|
|
87
|
+
return ` async ${route.functionName}(${methodParam}): ${returnTypeAnnotation} {
|
|
88
|
+
const response = await this.fetchClient.fetch(${pathExpression}, ${fetchOptions});
|
|
89
|
+
return this.serialize(response);
|
|
90
|
+
}`;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Helper types for proper type serialization from Nitro.
|
|
94
|
+
* https://github.com/nitrojs/nitro/blob/67b43f2692a41728a2759462b6982c6872ed3a81/src/types/fetch/_serialize.ts
|
|
95
|
+
*/
|
|
96
|
+
const serializationTypes = `type JsonPrimitive = string | number | boolean | string | number | boolean | null;
|
|
97
|
+
type NonJsonPrimitive = undefined | Function | symbol;
|
|
98
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
99
|
+
type FilterKeys<TObj extends object, TFilter> = { [TKey in keyof TObj]: TObj[TKey] extends TFilter ? TKey : never }[keyof TObj];
|
|
100
|
+
type Serialize<T> = IsAny<T> extends true ? any : T extends JsonPrimitive | undefined ? T : T extends Map<any, any> | Set<any> ? Record<string, never> : T extends NonJsonPrimitive ? never : T extends {
|
|
101
|
+
toJSON: () => infer U;
|
|
102
|
+
} ? U : T extends [] ? [] : T extends [unknown, ...unknown[]] ? SerializeTuple<T> : T extends ReadonlyArray<infer U> ? (U extends NonJsonPrimitive ? null : Serialize<U>)[] : T extends object ? SerializeObject<T> : never;
|
|
103
|
+
type SerializeTuple<T extends [unknown, ...unknown[]]> = { [k in keyof T]: T[k] extends NonJsonPrimitive ? null : Serialize<T[k]> };
|
|
104
|
+
type SerializeObject<T extends object> = { [k in keyof Omit<T, FilterKeys<T, NonJsonPrimitive>>]: Serialize<T[k]> };
|
|
105
|
+
type Simplify<TType> = TType extends any[] | Date ? TType : { [K in keyof TType]: Simplify<TType[K]> };
|
|
106
|
+
type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T;
|
|
107
|
+
type C8ySerialize<T> = T extends void | undefined | null ? undefined : T extends string ? string : Simplify<Serialize<T>>;
|
|
108
|
+
`;
|
|
109
|
+
/**
|
|
110
|
+
* Generates complete Angular API client service.
|
|
111
|
+
* @param routes - Array of parsed routes to generate methods for
|
|
112
|
+
* @param contextPath - The microservice context path (e.g., "my-service")
|
|
113
|
+
* @param className - The class name for the generated service (e.g., "PlaygroundAPIClient")
|
|
114
|
+
*/
|
|
115
|
+
function generateAPIClient(routes, contextPath, className) {
|
|
116
|
+
return `/* eslint-disable eslint-comments/no-unlimited-disable */
|
|
117
|
+
/* eslint-disable */
|
|
118
|
+
/**
|
|
119
|
+
* Auto-generated Cumulocity API Client
|
|
120
|
+
* Generated by c8y-nitro
|
|
121
|
+
*
|
|
122
|
+
* This Angular service provides typed methods for all Nitro routes.
|
|
123
|
+
* Each method corresponds to a route handler and returns properly typed responses.
|
|
124
|
+
*/
|
|
125
|
+
import { Injectable, inject } from '@angular/core'
|
|
126
|
+
import { FetchClient } from '@c8y/client'
|
|
127
|
+
|
|
128
|
+
// Type helpers for proper serialization
|
|
129
|
+
${serializationTypes}
|
|
11
130
|
|
|
131
|
+
@Injectable({ providedIn: 'root' })
|
|
132
|
+
export class ${className} {
|
|
133
|
+
private readonly BASE_PATH = '/service/${contextPath}';
|
|
134
|
+
private readonly fetchClient: FetchClient = inject(FetchClient)
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Serializes the response based on content type and body.
|
|
138
|
+
* - Empty body (null, undefined, void) -> undefined
|
|
139
|
+
* - text/plain (string) -> raw text
|
|
140
|
+
* - application/json (number, boolean, object, array) -> JSON parsed
|
|
141
|
+
*/
|
|
142
|
+
private async serialize(response: Response): Promise<any> {
|
|
143
|
+
const contentType = response.headers.get('content-type');
|
|
144
|
+
const text = await response.text();
|
|
145
|
+
|
|
146
|
+
// Handle empty responses (null, undefined, empty return)
|
|
147
|
+
if (!text || text.length === 0) {
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Handle plain text responses (strings)
|
|
152
|
+
if (contentType?.includes('text/plain')) {
|
|
153
|
+
return text;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Handle JSON responses (numbers, booleans, objects, arrays)
|
|
157
|
+
return JSON.parse(text);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
${routes.map((route) => generateMethod(route)).join("\n\n")}
|
|
161
|
+
}`;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Generates the TypeScript return type for a route handler.
|
|
165
|
+
* @param handlerPath - Absolute path to the route handler file
|
|
166
|
+
* @param outputFile - Absolute path to the output API client file
|
|
167
|
+
* @returns TypeScript return type string with proper serialization wrappers
|
|
168
|
+
*/
|
|
169
|
+
function getReturnType(handlerPath, outputFile) {
|
|
170
|
+
const relativeHandlerPath = relative(dirname(outputFile), handlerPath);
|
|
171
|
+
return `C8ySerialize<Awaited<ReturnType<typeof import('${(relativeHandlerPath.startsWith(".") ? relativeHandlerPath : `./${relativeHandlerPath}`).replace(/\.ts$/, "")}').default>>>`;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Writes the generated API client to disk.
|
|
175
|
+
* @param nitro - Nitro instance
|
|
176
|
+
* @param options - Complete module options including apiClient and manifest
|
|
177
|
+
*/
|
|
178
|
+
async function writeAPIClient(nitro, options) {
|
|
179
|
+
const { apiClient: apiClientOptions } = options;
|
|
180
|
+
if (!apiClientOptions) {
|
|
181
|
+
nitro.logger.debug("API client generation skipped: no apiClient options provided");
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const manifest = await createC8yManifestFromNitro(nitro);
|
|
185
|
+
const serviceName = manifest.name;
|
|
186
|
+
const serviceContextPath = apiClientOptions.contextPath ?? manifest.contextPath ?? serviceName;
|
|
187
|
+
const name = `${serviceName}APIClient`;
|
|
188
|
+
const rootDir = nitro.options.rootDir;
|
|
189
|
+
const outputDir = join(rootDir, apiClientOptions.dir);
|
|
190
|
+
const outputFile = join(outputDir, `${name}.ts`);
|
|
191
|
+
const routes = (nitro.routing.routes._routes ?? []).filter((route) => {
|
|
192
|
+
return !route.handler.includes("nitro/dist/runtime/internal");
|
|
193
|
+
}).map((route) => {
|
|
194
|
+
const path = route.route;
|
|
195
|
+
const method = (!route.method ? "GET" : route.method).toUpperCase();
|
|
196
|
+
const params = extractParams(path);
|
|
197
|
+
const functionName = generateFunctionName(path, method);
|
|
198
|
+
const returnType = getReturnType(route.handler, outputFile);
|
|
199
|
+
return {
|
|
200
|
+
path: path.replace(/:([^/]+)/g, "[$1]"),
|
|
201
|
+
method,
|
|
202
|
+
functionName,
|
|
203
|
+
params,
|
|
204
|
+
returnType
|
|
205
|
+
};
|
|
206
|
+
});
|
|
207
|
+
if (routes.length === 0) {
|
|
208
|
+
nitro.logger.warn("No routes found to generate API client");
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const code = generateAPIClient(routes, serviceContextPath, toValidClassName(name));
|
|
212
|
+
await mkdir(outputDir, { recursive: true });
|
|
213
|
+
await writeFile(outputFile, code, "utf-8");
|
|
214
|
+
nitro.logger.success(`Generated API client with ${routes.length} routes at: ${relative(rootDir, outputFile)}`);
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
//#region src/module/docker.ts
|
|
218
|
+
/**
|
|
219
|
+
* Generate the Dockerfile content for a Nitro build
|
|
220
|
+
* @param outputDirName - Name of the output directory (e.g., '.output')
|
|
221
|
+
* @returns Dockerfile content as a string
|
|
222
|
+
*/
|
|
223
|
+
function getDockerfileContent(outputDirName) {
|
|
224
|
+
return `FROM node:24-slim AS runtime
|
|
225
|
+
|
|
226
|
+
WORKDIR /app
|
|
227
|
+
|
|
228
|
+
# Copy the Nitro build output
|
|
229
|
+
COPY ${outputDirName}/ ${outputDirName}/
|
|
230
|
+
|
|
231
|
+
ENV NODE_ENV=production
|
|
232
|
+
ENV PORT=80
|
|
233
|
+
|
|
234
|
+
EXPOSE 80
|
|
235
|
+
|
|
236
|
+
# Run the Nitro server entrypoint. Use source maps to aid debugging if present.
|
|
237
|
+
CMD ["node", "--enable-source-maps", "${outputDirName}/server/index.mjs"]`;
|
|
238
|
+
}
|
|
239
|
+
async function checkDockerInstalled() {
|
|
240
|
+
try {
|
|
241
|
+
const result = await x("docker", ["--version"]);
|
|
242
|
+
if (result.exitCode !== 0) return false;
|
|
243
|
+
if (result.stderr) return false;
|
|
244
|
+
return true;
|
|
245
|
+
} catch {
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async function writeDockerfile(outputDir) {
|
|
250
|
+
const outputDirName = basename(outputDir);
|
|
251
|
+
const c8yDir = join(outputDir, "../.c8y");
|
|
252
|
+
const dockerfilePath = join(c8yDir, "Dockerfile");
|
|
253
|
+
await mkdir(c8yDir, { recursive: true });
|
|
254
|
+
await writeFile(dockerfilePath, getDockerfileContent(outputDirName), "utf-8");
|
|
255
|
+
return c8yDir;
|
|
256
|
+
}
|
|
257
|
+
async function buildDockerImage(nitro, c8yDir) {
|
|
258
|
+
const imageName = `${nitro.options.rootDir.split("/").pop() || "c8y-app"}:latest`;
|
|
259
|
+
const buildContext = join(c8yDir, "..");
|
|
260
|
+
nitro.logger.debug(`Building Docker image: ${imageName}`);
|
|
261
|
+
nitro.logger.debug(`Build context: ${buildContext}`);
|
|
262
|
+
try {
|
|
263
|
+
const result = await x("docker", [
|
|
264
|
+
"build",
|
|
265
|
+
"-t",
|
|
266
|
+
imageName,
|
|
267
|
+
"-f",
|
|
268
|
+
join(c8yDir, "Dockerfile"),
|
|
269
|
+
buildContext
|
|
270
|
+
]);
|
|
271
|
+
if (result.stdout) nitro.logger.debug(result.stdout);
|
|
272
|
+
if (result.stderr) nitro.logger.debug(result.stderr);
|
|
273
|
+
if (result.exitCode !== 0) throw new Error(`Docker build failed with exit code ${result.exitCode}`, { cause: result.stderr });
|
|
274
|
+
nitro.logger.debug(`Docker image built successfully: ${imageName}`);
|
|
275
|
+
return imageName;
|
|
276
|
+
} catch (error) {
|
|
277
|
+
throw new Error("Failed to build Docker image", { cause: error });
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
async function saveDockerImageToTar(nitro, c8yDir, imageName) {
|
|
281
|
+
const imageTarPath = join(c8yDir, "image.tar");
|
|
282
|
+
nitro.logger.debug(`Saving Docker image to ${imageTarPath}`);
|
|
283
|
+
try {
|
|
284
|
+
const result = await x("docker", [
|
|
285
|
+
"save",
|
|
286
|
+
"-o",
|
|
287
|
+
imageTarPath,
|
|
288
|
+
imageName
|
|
289
|
+
]);
|
|
290
|
+
if (result.stderr) nitro.logger.debug(result.stderr);
|
|
291
|
+
if (result.exitCode !== 0) throw new Error(`Docker save failed with exit code ${result.exitCode}`, { cause: result.stderr });
|
|
292
|
+
nitro.logger.debug(`Docker image saved to ${imageTarPath}`);
|
|
293
|
+
return imageTarPath;
|
|
294
|
+
} catch (error) {
|
|
295
|
+
throw new Error("Failed to save Docker image to tar file", { cause: error });
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Create a Docker image from the Nitro build output
|
|
300
|
+
* @param nitro Nitro instance
|
|
301
|
+
* @returns Path to the saved Docker image tar file
|
|
302
|
+
*/
|
|
303
|
+
async function createDockerImage(nitro) {
|
|
304
|
+
if (!await checkDockerInstalled()) throw new Error("Docker is not installed or not available in PATH. Please install Docker to build images.");
|
|
305
|
+
nitro.logger.debug("Creating Docker image...");
|
|
306
|
+
const c8yDir = await writeDockerfile(nitro.options.output.dir);
|
|
307
|
+
const imageTarPath = await saveDockerImageToTar(nitro, c8yDir, await buildDockerImage(nitro, c8yDir));
|
|
308
|
+
nitro.logger.debug("Docker image creation complete.");
|
|
309
|
+
return imageTarPath;
|
|
310
|
+
}
|
|
311
|
+
//#endregion
|
|
312
|
+
//#region src/module/c8yzip.ts
|
|
313
|
+
const spinnies = new Spinnies();
|
|
314
|
+
function formatBytes(bytes) {
|
|
315
|
+
if (bytes === 0) return "0 B";
|
|
316
|
+
const k = 1024;
|
|
317
|
+
const sizes = [
|
|
318
|
+
"B",
|
|
319
|
+
"kB",
|
|
320
|
+
"MB",
|
|
321
|
+
"GB"
|
|
322
|
+
];
|
|
323
|
+
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
324
|
+
return `${(bytes / k ** i).toFixed(1)} ${sizes[i]}`;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Resolve the output path for the zip file based on options and manifest
|
|
328
|
+
* @param rootDir - Root directory of the project
|
|
329
|
+
* @param options - Zip options with optional name and outputDir
|
|
330
|
+
* @param manifest - Cumulocity manifest containing name and version
|
|
331
|
+
* @returns Absolute path to the output zip file
|
|
332
|
+
*/
|
|
333
|
+
function resolveZipOutputPath(rootDir, options, manifest) {
|
|
334
|
+
return join$1(join$1(rootDir, options.outputDir ?? "./"), typeof options.name === "function" ? options.name(manifest.name, manifest.version) : options.name ?? `${manifest.name}-${manifest.version}.zip`);
|
|
335
|
+
}
|
|
336
|
+
async function createC8yZip(nitro, options = {}) {
|
|
337
|
+
const startTime = Date.now();
|
|
338
|
+
const spinnerName = "c8y-zip";
|
|
339
|
+
spinnies.add(spinnerName, { text: "Creating Dockerfile..." });
|
|
340
|
+
spinnies.update(spinnerName, { text: "Building Docker image..." });
|
|
341
|
+
const imageTarPath = await createDockerImage(nitro);
|
|
342
|
+
spinnies.update(spinnerName, { text: "Creating manifest..." });
|
|
343
|
+
const manifest = await createC8yManifestFromNitro(nitro);
|
|
344
|
+
spinnies.update(spinnerName, { text: "Reading image.tar..." });
|
|
345
|
+
const imageTarBuffer = await readFile$1(imageTarPath);
|
|
346
|
+
spinnies.update(spinnerName, { text: "Building zip file..." });
|
|
347
|
+
const zip = new JSZip();
|
|
348
|
+
zip.file("image.tar", imageTarBuffer);
|
|
349
|
+
zip.file("cumulocity.json", JSON.stringify(manifest, null, 2));
|
|
350
|
+
const zipBuffer = await zip.generateAsync({
|
|
351
|
+
type: "nodebuffer",
|
|
352
|
+
compression: "STORE"
|
|
353
|
+
});
|
|
354
|
+
const outputFile = resolveZipOutputPath(nitro.options.rootDir, options, manifest);
|
|
355
|
+
const outputDir = join$1(outputFile, "..");
|
|
356
|
+
spinnies.update(spinnerName, { text: "Writing zip file..." });
|
|
357
|
+
await mkdir$1(outputDir, { recursive: true });
|
|
358
|
+
await writeFile$1(outputFile, zipBuffer);
|
|
359
|
+
const zipSize = formatBytes((await stat(outputFile)).size);
|
|
360
|
+
const duration = Date.now() - startTime;
|
|
361
|
+
spinnies.remove(spinnerName);
|
|
362
|
+
spinnies.stopAll();
|
|
363
|
+
nitro.logger.success(`Cumulocity zip built in ${duration}ms`);
|
|
364
|
+
nitro.logger.log(colors.gray(` └─ ${outputFile} (${zipSize})`));
|
|
365
|
+
nitro.logger.info("Zip file can be uploaded to Cumulocity IoT platform");
|
|
366
|
+
}
|
|
367
|
+
//#endregion
|
|
368
|
+
//#region src/module/runtime.ts
|
|
369
|
+
function setupRuntime(nitro, manifestOptions = {}) {
|
|
370
|
+
nitro.logger.debug("Setting up C8Y nitro runtime");
|
|
371
|
+
const roles = manifestOptions.roles ?? [];
|
|
372
|
+
const settingKeys = (manifestOptions.settings ?? []).map((s) => s.key);
|
|
373
|
+
const completeTypesDir = join$1(nitro.options.rootDir, nitro.options.typescript.generatedTypesDir ?? "node_modules/.nitro/types");
|
|
374
|
+
const typesFile = join$1(completeTypesDir, "c8y-nitro.d.ts");
|
|
375
|
+
const typesContent = `// generated by c8y-nitro
|
|
376
|
+
declare module 'c8y-nitro/types' {
|
|
377
|
+
interface C8YRoles {
|
|
378
|
+
${roles.map((role) => ` '${role}': '${role}';`).join("\n")}
|
|
379
|
+
}
|
|
380
|
+
type C8YTenantOptionKey = ${settingKeys.length > 0 ? `${settingKeys.map((k) => `'${k}'`).join(" | ")}` : "never"}
|
|
381
|
+
type C8YTenantOptionKeysCacheConfig = Partial<Record<C8YTenantOptionKey, number>>;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
declare module 'c8y-nitro/runtime' {
|
|
385
|
+
import type { C8YRoles } from 'c8y-nitro/types';
|
|
386
|
+
export const c8yRoles: C8YRoles;
|
|
387
|
+
export const c8yTenantOptionKeys: readonly [${settingKeys.map((key) => `'${key}'`).join(", ")}];
|
|
388
|
+
}`;
|
|
389
|
+
nitro.options.virtual["c8y-nitro/runtime"] = `
|
|
390
|
+
export const c8yRoles = {
|
|
391
|
+
${roles.map((role) => ` '${role}': '${role}',`).join("\n")}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export const c8yTenantOptionKeys = [${settingKeys.map((key) => `'${key}'`).join(", ")}]
|
|
395
|
+
`;
|
|
396
|
+
mkdirSync(completeTypesDir, { recursive: true });
|
|
397
|
+
writeFileSync(typesFile, typesContent, { encoding: "utf-8" });
|
|
398
|
+
nitro.logger.debug(`Written C8Y types to ${typesFile}`);
|
|
399
|
+
}
|
|
400
|
+
//#endregion
|
|
401
|
+
//#region src/module/runtimeConfig.ts
|
|
402
|
+
/**
|
|
403
|
+
* Sets up runtime configuration values from module options.
|
|
404
|
+
* These can be overridden by environment variables.
|
|
405
|
+
* @param nitro - The Nitro instance
|
|
406
|
+
* @param options - The c8y-nitro module options
|
|
407
|
+
*/
|
|
408
|
+
async function setupRuntimeConfig(nitro, options) {
|
|
409
|
+
nitro.logger.debug("Setting up C8Y runtime config");
|
|
410
|
+
nitro.options.runtimeConfig.c8yCredentialsCacheTTL = options.cache?.credentialsTTL ?? 600;
|
|
411
|
+
nitro.options.runtimeConfig.c8yDefaultTenantOptionsTTL = options.cache?.defaultTenantOptionsTTL ?? 600;
|
|
412
|
+
nitro.options.runtimeConfig.c8yTenantOptionsPerKeyTTL = options.cache?.tenantOptions ?? {};
|
|
413
|
+
const manifest = await createC8yManifest(nitro.options.rootDir, options.manifest, nitro.logger);
|
|
414
|
+
nitro.options.runtimeConfig.c8ySettingsCategory = options.manifest?.settingsCategory ?? manifest.contextPath ?? manifest.name;
|
|
415
|
+
}
|
|
416
|
+
//#endregion
|
|
417
|
+
//#region src/module/register.ts
|
|
418
|
+
/**
|
|
419
|
+
* Links runtime middleware, handlers, and plugins to the nitro instance.
|
|
420
|
+
* Works by having the handlers in a relative path to this file.
|
|
421
|
+
* Needs to be the same when built.
|
|
422
|
+
* @param nitro - Nitro instance
|
|
423
|
+
* @param options - C8yNitroModuleOptions
|
|
424
|
+
*/
|
|
425
|
+
function registerRuntime(nitro, options = {}) {
|
|
426
|
+
const thisFilePath = fileURLToPath(new URL(".", import.meta.url));
|
|
427
|
+
/**
|
|
428
|
+
* Plugins
|
|
429
|
+
*/
|
|
430
|
+
const plugins = [];
|
|
431
|
+
const c8yVariablesPluginPath = join$1(thisFilePath, "./runtime/plugins/c8y-variables");
|
|
432
|
+
plugins.push(c8yVariablesPluginPath);
|
|
433
|
+
nitro.options.plugins.push(...plugins);
|
|
434
|
+
/**
|
|
435
|
+
* Middlewares (global)
|
|
436
|
+
*/
|
|
437
|
+
const middlewares = [];
|
|
438
|
+
const devUserMiddlewarePath = join$1(thisFilePath, "./runtime/middlewares/dev-user");
|
|
439
|
+
middlewares.push(devUserMiddlewarePath);
|
|
440
|
+
nitro.options.handlers.push(...middlewares.map((handler) => ({
|
|
441
|
+
route: "/**",
|
|
442
|
+
handler,
|
|
443
|
+
middleware: true
|
|
444
|
+
})));
|
|
445
|
+
/**
|
|
446
|
+
* Handlers
|
|
447
|
+
*/
|
|
448
|
+
const handlers = [];
|
|
449
|
+
const probeHandlerPath = join$1(thisFilePath, "./runtime/handlers/liveness-readiness");
|
|
450
|
+
if (!options.manifest?.livenessProbe?.httpGet) {
|
|
451
|
+
handlers.push({
|
|
452
|
+
route: GENERATED_LIVENESS_ROUTE,
|
|
453
|
+
handler: probeHandlerPath,
|
|
454
|
+
method: "GET"
|
|
455
|
+
});
|
|
456
|
+
nitro.logger.debug(`Generated liveness probe at ${GENERATED_LIVENESS_ROUTE}`);
|
|
457
|
+
} else nitro.logger.debug("Liveness probe httpGet defined by user; skipping generation");
|
|
458
|
+
if (!options.manifest?.readinessProbe?.httpGet) {
|
|
459
|
+
handlers.push({
|
|
460
|
+
route: GENERATED_READINESS_ROUTE,
|
|
461
|
+
handler: probeHandlerPath,
|
|
462
|
+
method: "GET"
|
|
463
|
+
});
|
|
464
|
+
nitro.logger.debug(`Generated readiness probe at ${GENERATED_READINESS_ROUTE}`);
|
|
465
|
+
} else nitro.logger.debug("Readiness probe httpGet defined by user; skipping generation");
|
|
466
|
+
nitro.options.handlers.push(...handlers);
|
|
467
|
+
}
|
|
468
|
+
//#endregion
|
|
469
|
+
//#region src/module/probeCheck.ts
|
|
470
|
+
function checkProbes(nitro, manifestOptions = {}) {
|
|
471
|
+
if (manifestOptions.livenessProbe?.httpGet) {
|
|
472
|
+
const probe = manifestOptions.livenessProbe.httpGet;
|
|
473
|
+
checkProbeEndpoint(nitro, probe, "livenessProbe");
|
|
474
|
+
}
|
|
475
|
+
if (manifestOptions.readinessProbe?.httpGet) {
|
|
476
|
+
const probe = manifestOptions.readinessProbe.httpGet;
|
|
477
|
+
checkProbeEndpoint(nitro, probe, "readinessProbe");
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
function checkProbeEndpoint(nitro, probe, probeType) {
|
|
481
|
+
const path = probe.path;
|
|
482
|
+
const method = "GET";
|
|
483
|
+
const matchingHandlers = nitro.scannedHandlers.filter((h) => h.route === path);
|
|
484
|
+
if (matchingHandlers.length === 0) {
|
|
485
|
+
nitro.logger.warn(`${probeType} route "${path}" not found in scanned handlers. The probe will fail at runtime.`);
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
if (!matchingHandlers.some((h) => {
|
|
489
|
+
if (!h.method) return true;
|
|
490
|
+
return h.method.toUpperCase() === method.toUpperCase();
|
|
491
|
+
})) {
|
|
492
|
+
const availableMethods = matchingHandlers.filter((h) => h.method).map((h) => h.method?.toUpperCase()).join(", ");
|
|
493
|
+
nitro.logger.warn(`${probeType} route "${path}" exists but does not accept ${method} requests. Available methods: ${availableMethods || "none specified"}. The probe will fail at runtime.`);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
//#endregion
|
|
497
|
+
//#region src/module/autoBootstrap.ts
|
|
498
|
+
/**
|
|
499
|
+
* Automatically bootstraps the microservice to the development tenant if needed.
|
|
500
|
+
* Runs silently - only logs if bootstrap was performed or if errors occur.
|
|
501
|
+
* @param nitro - Nitro instance
|
|
502
|
+
*/
|
|
503
|
+
async function autoBootstrap(nitro) {
|
|
504
|
+
try {
|
|
505
|
+
if ([
|
|
506
|
+
"C8Y_BOOTSTRAP_TENANT",
|
|
507
|
+
"C8Y_BOOTSTRAP_USER",
|
|
508
|
+
"C8Y_BOOTSTRAP_PASSWORD"
|
|
509
|
+
].every((v) => process.env[v])) return;
|
|
510
|
+
if ([
|
|
511
|
+
"C8Y_BASEURL",
|
|
512
|
+
"C8Y_DEVELOPMENT_TENANT",
|
|
513
|
+
"C8Y_DEVELOPMENT_USER",
|
|
514
|
+
"C8Y_DEVELOPMENT_PASSWORD"
|
|
515
|
+
].filter((v) => !process.env[v]).length > 0) return;
|
|
516
|
+
const baseUrl = process.env.C8Y_BASEURL.endsWith("/") ? process.env.C8Y_BASEURL.slice(0, -1) : process.env.C8Y_BASEURL;
|
|
517
|
+
const authHeader = createBasicAuthHeader(process.env.C8Y_DEVELOPMENT_TENANT, process.env.C8Y_DEVELOPMENT_USER, process.env.C8Y_DEVELOPMENT_PASSWORD);
|
|
518
|
+
const manifest = await createC8yManifest(nitro.options.rootDir, nitro.options.c8y?.manifest, nitro.logger);
|
|
519
|
+
const existingApp = await findMicroserviceByName(baseUrl, manifest.name, authHeader);
|
|
520
|
+
let appId;
|
|
521
|
+
if (existingApp) {
|
|
522
|
+
appId = existingApp.id;
|
|
523
|
+
nitro.logger.debug(`Microservice "${manifest.name}" already exists (ID: ${appId}), retrieving bootstrap credentials...`);
|
|
524
|
+
} else {
|
|
525
|
+
appId = (await createMicroservice(baseUrl, manifest, authHeader)).id;
|
|
526
|
+
nitro.logger.debug(`Microservice "${manifest.name}" created (ID: ${appId})`);
|
|
527
|
+
}
|
|
528
|
+
await subscribeToApplication(baseUrl, process.env.C8Y_DEVELOPMENT_TENANT, appId, authHeader);
|
|
529
|
+
const credentials = await getBootstrapCredentials(baseUrl, appId, authHeader);
|
|
530
|
+
const envFileName = await writeBootstrapCredentials(nitro.options.rootDir, {
|
|
531
|
+
C8Y_BOOTSTRAP_TENANT: credentials.tenant,
|
|
532
|
+
C8Y_BOOTSTRAP_USER: credentials.name,
|
|
533
|
+
C8Y_BOOTSTRAP_PASSWORD: credentials.password
|
|
534
|
+
});
|
|
535
|
+
process.env.C8Y_BOOTSTRAP_TENANT = credentials.tenant;
|
|
536
|
+
process.env.C8Y_BOOTSTRAP_USER = credentials.name;
|
|
537
|
+
process.env.C8Y_BOOTSTRAP_PASSWORD = credentials.password;
|
|
538
|
+
nitro.logger.success(`Auto-bootstrap complete! Bootstrap credentials written to ${envFileName}`);
|
|
539
|
+
} catch (error) {
|
|
540
|
+
nitro.logger.warn("Auto-bootstrap failed:", error instanceof Error ? error.message : String(error));
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
//#endregion
|
|
12
544
|
//#region src/index.ts
|
|
13
545
|
function c8y() {
|
|
14
546
|
return {
|
|
@@ -56,6 +588,5 @@ function c8y() {
|
|
|
56
588
|
}
|
|
57
589
|
};
|
|
58
590
|
}
|
|
59
|
-
|
|
60
591
|
//#endregion
|
|
61
|
-
export { c8y, c8y as default };
|
|
592
|
+
export { c8y, c8y as default };
|