keycloakify 11.7.4 → 11.8.1

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.
Files changed (38) hide show
  1. package/bin/{33.index.js → 226.index.js} +2 -19
  2. package/bin/{911.index.js → 297.index.js} +18918 -11359
  3. package/bin/355.index.js +41 -703
  4. package/bin/363.index.js +115 -93
  5. package/bin/369.index.js +968 -0
  6. package/bin/{288.index.js → 502.index.js} +123 -227
  7. package/bin/656.index.js +111 -0
  8. package/bin/{880.index.js → 712.index.js} +227 -216
  9. package/bin/780.index.js +9 -7
  10. package/bin/932.index.js +965 -0
  11. package/bin/97.index.js +2099 -769
  12. package/bin/main.js +66 -49
  13. package/bin/shared/buildContext.d.ts +11 -3
  14. package/bin/start-keycloak/realmConfig/prepareRealmConfig.d.ts +5 -6
  15. package/bin/start-keycloak/realmConfig/realmConfig.d.ts +6 -2
  16. package/package.json +12 -17
  17. package/src/bin/initialize-account-theme/initialize-account-theme.ts +29 -27
  18. package/src/bin/initialize-email-theme.ts +103 -53
  19. package/src/bin/keycloakify/buildJars/buildJar.ts +45 -20
  20. package/src/bin/keycloakify/generateResources/generateResources.ts +263 -217
  21. package/src/bin/shared/{initializeSpa/addSyncExtensionsToPostinstallScript.ts → addSyncExtensionsToPostinstallScript.ts} +1 -1
  22. package/src/bin/shared/buildContext.ts +69 -24
  23. package/src/bin/shared/{initializeSpa/initializeSpa.ts → initializeSpa.ts} +3 -3
  24. package/src/bin/start-keycloak/realmConfig/prepareRealmConfig.ts +12 -23
  25. package/src/bin/start-keycloak/realmConfig/realmConfig.ts +14 -12
  26. package/src/bin/start-keycloak/start-keycloak.ts +55 -28
  27. package/src/bin/sync-extensions/getExtensionModuleFileSourceCodeReadyToBeCopied.ts +6 -0
  28. package/vite-plugin/index.js +48 -20
  29. package/bin/313.index.js +0 -377
  30. package/bin/678.index.js +0 -7565
  31. package/bin/9.index.js +0 -850
  32. package/bin/947.index.js +0 -1565
  33. package/bin/shared/initializeSpa/index.d.ts +0 -1
  34. package/bin/shared/metaInfKeycloakThemes.d.ts +0 -13
  35. package/src/bin/shared/initializeSpa/index.ts +0 -1
  36. package/src/bin/shared/metaInfKeycloakThemes.ts +0 -40
  37. /package/bin/shared/{initializeSpa/addSyncExtensionsToPostinstallScript.d.ts → addSyncExtensionsToPostinstallScript.d.ts} +0 -0
  38. /package/bin/shared/{initializeSpa/initializeSpa.d.ts → initializeSpa.d.ts} +0 -0
package/bin/97.index.js CHANGED
@@ -3,30 +3,162 @@ exports.id = 97;
3
3
  exports.ids = [97];
4
4
  exports.modules = {
5
5
 
6
- /***/ 98097:
6
+ /***/ 64097:
7
7
  /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
8
8
 
9
+ // ESM COMPAT FLAG
9
10
  __webpack_require__.r(__webpack_exports__);
10
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
11
- /* harmony export */ "command": () => (/* binding */ command)
12
- /* harmony export */ });
13
- /* harmony import */ var _tools_getThisCodebaseRootDirPath__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(58822);
14
- /* harmony import */ var cli_select__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(99398);
15
- /* harmony import */ var cli_select__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(cli_select__WEBPACK_IMPORTED_MODULE_1__);
16
- /* harmony import */ var _shared_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(173);
17
- /* harmony import */ var tsafe_capitalize__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(14899);
18
- /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(57147);
19
- /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_3__);
20
- /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(71017);
21
- /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_4__);
22
- /* harmony import */ var _tools_kebabCaseToSnakeCase__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(17192);
23
- /* harmony import */ var tsafe_assert__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(29041);
24
- /* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(78818);
25
- /* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(chalk__WEBPACK_IMPORTED_MODULE_6__);
26
- /* harmony import */ var _tools_runPrettier__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(48433);
27
- /* harmony import */ var _shared_customHandler_delegate__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(72138);
28
11
 
12
+ // EXPORTS
13
+ __webpack_require__.d(__webpack_exports__, {
14
+ "command": () => (/* reexport */ command)
15
+ });
29
16
 
17
+ // EXTERNAL MODULE: ./node_modules/tsafe/esm/exclude.mjs
18
+ var exclude = __webpack_require__(83101);
19
+ // EXTERNAL MODULE: ./dist/bin/shared/constants.js
20
+ var constants = __webpack_require__(173);
21
+ // EXTERNAL MODULE: ./dist/bin/tools/SemVer.js
22
+ var SemVer = __webpack_require__(12171);
23
+ // EXTERNAL MODULE: ./node_modules/tsafe/esm/assert.mjs + 1 modules
24
+ var assert = __webpack_require__(29041);
25
+ // EXTERNAL MODULE: external "fs"
26
+ var external_fs_ = __webpack_require__(57147);
27
+ var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
28
+ // EXTERNAL MODULE: external "path"
29
+ var external_path_ = __webpack_require__(71017);
30
+ // EXTERNAL MODULE: external "child_process"
31
+ var external_child_process_ = __webpack_require__(32081);
32
+ var external_child_process_default = /*#__PURE__*/__webpack_require__.n(external_child_process_);
33
+ // EXTERNAL MODULE: ./node_modules/chalk/source/index.js
34
+ var source = __webpack_require__(78818);
35
+ var source_default = /*#__PURE__*/__webpack_require__.n(source);
36
+ // EXTERNAL MODULE: ./node_modules/chokidar/index.js
37
+ var chokidar = __webpack_require__(42677);
38
+ // EXTERNAL MODULE: ./node_modules/powerhooks/tools/waitForDebounce.js
39
+ var tools_waitForDebounce = __webpack_require__(18721);
40
+ // EXTERNAL MODULE: ./dist/bin/tools/getThisCodebaseRootDirPath.js
41
+ var getThisCodebaseRootDirPath = __webpack_require__(58822);
42
+ // EXTERNAL MODULE: ./dist/bin/tools/getAbsoluteAndInOsFormatPath.js
43
+ var getAbsoluteAndInOsFormatPath = __webpack_require__(84794);
44
+ // EXTERNAL MODULE: ./node_modules/cli-select/dist/index.js
45
+ var dist = __webpack_require__(99398);
46
+ var dist_default = /*#__PURE__*/__webpack_require__.n(dist);
47
+ // EXTERNAL MODULE: ./node_modules/run-exclusive/lib/runExclusive.js
48
+ var runExclusive = __webpack_require__(81708);
49
+ // EXTERNAL MODULE: external "fs/promises"
50
+ var promises_ = __webpack_require__(73292);
51
+ var promises_default = /*#__PURE__*/__webpack_require__.n(promises_);
52
+ // EXTERNAL MODULE: ./node_modules/yauzl/index.js
53
+ var yauzl = __webpack_require__(78781);
54
+ // EXTERNAL MODULE: external "stream"
55
+ var external_stream_ = __webpack_require__(12781);
56
+ var external_stream_default = /*#__PURE__*/__webpack_require__.n(external_stream_);
57
+ // EXTERNAL MODULE: ./node_modules/evt/tools/Deferred.js
58
+ var Deferred = __webpack_require__(50689);
59
+ // EXTERNAL MODULE: ./dist/bin/tools/fs.existsAsync.js
60
+ var fs_existsAsync = __webpack_require__(43765);
61
+ ;// CONCATENATED MODULE: ./dist/bin/tools/extractArchive.js
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+ async function extractArchive(params) {
70
+ const { archiveFilePath, onArchiveFile } = params;
71
+ const zipFile = await new Promise((resolve, reject) => {
72
+ yauzl.open(archiveFilePath, { lazyEntries: true }, async (error, zipFile) => {
73
+ if (error) {
74
+ reject(error);
75
+ return;
76
+ }
77
+ resolve(zipFile);
78
+ });
79
+ });
80
+ const dDone = new Deferred.Deferred();
81
+ zipFile.once("end", () => {
82
+ zipFile.close();
83
+ dDone.resolve();
84
+ });
85
+ const writeFile = async (entry, params) => {
86
+ const { filePath, modifiedData } = params;
87
+ {
88
+ const dirPath = (0,external_path_.dirname)(filePath);
89
+ if (!(await (0,fs_existsAsync/* existsAsync */.o)(dirPath))) {
90
+ await promises_default().mkdir(dirPath, { recursive: true });
91
+ }
92
+ }
93
+ if (modifiedData !== undefined) {
94
+ await promises_default().writeFile(filePath, modifiedData);
95
+ return;
96
+ }
97
+ const readStream = await new Promise(resolve => zipFile.openReadStream(entry, async (error, readStream) => {
98
+ if (error) {
99
+ dDone.reject(error);
100
+ return;
101
+ }
102
+ resolve(readStream);
103
+ }));
104
+ const dDoneWithFile = new Deferred.Deferred();
105
+ external_stream_default().pipeline(readStream, external_fs_default().createWriteStream(filePath), error => {
106
+ if (error) {
107
+ dDone.reject(error);
108
+ return;
109
+ }
110
+ dDoneWithFile.resolve();
111
+ });
112
+ await dDoneWithFile.pr;
113
+ };
114
+ const readFile = (entry) => new Promise(resolve => zipFile.openReadStream(entry, async (error, readStream) => {
115
+ if (error) {
116
+ dDone.reject(error);
117
+ return;
118
+ }
119
+ const chunks = [];
120
+ readStream.on("data", chunk => {
121
+ chunks.push(chunk);
122
+ });
123
+ readStream.on("end", () => {
124
+ resolve(Buffer.concat(chunks));
125
+ });
126
+ readStream.on("error", error => {
127
+ dDone.reject(error);
128
+ });
129
+ }));
130
+ zipFile.on("entry", async (entry) => {
131
+ handle_file: {
132
+ // NOTE: Skip directories
133
+ if (entry.fileName.endsWith("/")) {
134
+ break handle_file;
135
+ }
136
+ let hasEarlyExitBeenCalled = false;
137
+ await onArchiveFile({
138
+ relativeFilePathInArchive: entry.fileName.split("/").join(external_path_.sep),
139
+ readFile: () => readFile(entry),
140
+ writeFile: params => writeFile(entry, params),
141
+ earlyExit: () => {
142
+ hasEarlyExitBeenCalled = true;
143
+ }
144
+ });
145
+ if (hasEarlyExitBeenCalled) {
146
+ zipFile.close();
147
+ dDone.resolve();
148
+ return;
149
+ }
150
+ }
151
+ zipFile.readEntry();
152
+ });
153
+ zipFile.readEntry();
154
+ await dDone.pr;
155
+ }
156
+ //# sourceMappingURL=extractArchive.js.map
157
+ // EXTERNAL MODULE: ./node_modules/tsafe/esm/id.mjs
158
+ var id = __webpack_require__(38469);
159
+ // EXTERNAL MODULE: ./node_modules/zod/lib/index.mjs
160
+ var lib = __webpack_require__(52300);
161
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/appBuild.js
30
162
 
31
163
 
32
164
 
@@ -36,188 +168,1990 @@ __webpack_require__.r(__webpack_exports__);
36
168
 
37
169
 
38
170
 
39
- async function command(params) {
171
+
172
+ (0,assert/* assert */.h)();
173
+ async function appBuild(params) {
174
+ var _a;
175
+ const { buildContext } = params;
176
+ const { parsedPackageJson } = (() => {
177
+ const zParsedPackageJson = (() => {
178
+ const zTargetType = lib.z.object({
179
+ scripts: lib.z.record(lib.z.string()).optional()
180
+ });
181
+ (0,assert/* assert */.h)();
182
+ return (0,id.id)(zTargetType);
183
+ })();
184
+ const parsedPackageJson = JSON.parse(external_fs_.readFileSync(buildContext.packageJsonFilePath).toString("utf8"));
185
+ zParsedPackageJson.parse(parsedPackageJson);
186
+ (0,assert/* assert */.h)((0,assert.is)(parsedPackageJson));
187
+ return { parsedPackageJson };
188
+ })();
189
+ const entries = Object.entries((_a = parsedPackageJson.scripts) !== null && _a !== void 0 ? _a : {}).filter(([, scriptCommand]) => scriptCommand.includes("keycloakify build"));
190
+ if (entries.length === 0) {
191
+ console.log(source_default().red([
192
+ `You should have a script in your package.json at ${(0,external_path_.relative)(process.cwd(), (0,external_path_.dirname)(buildContext.packageJsonFilePath))}`,
193
+ `that includes the 'keycloakify build' command`
194
+ ].join(" ")));
195
+ process.exit(-1);
196
+ }
197
+ const entry = entries.length === 1
198
+ ? entries[0]
199
+ : entries.find(([scriptName]) => scriptName === "build-keycloak-theme");
200
+ if (entry === undefined) {
201
+ console.log(source_default().red("There's multiple candidate script for building your app, name one 'build-keycloak-theme'"));
202
+ process.exit(-1);
203
+ }
204
+ const [scriptName, scriptCommand] = entry;
205
+ const { appBuildSubCommands } = (() => {
206
+ const appBuildSubCommands = [];
207
+ for (const subCmd of scriptCommand.split("&&").map(s => s.trim())) {
208
+ if (subCmd.includes("keycloakify build")) {
209
+ break;
210
+ }
211
+ appBuildSubCommands.push(subCmd);
212
+ }
213
+ return { appBuildSubCommands };
214
+ })();
215
+ if (appBuildSubCommands.length === 0) {
216
+ console.log(source_default().red(`Your ${scriptName} script should look like "... && keycloakify build ..."`));
217
+ process.exit(-1);
218
+ }
219
+ common_case: {
220
+ if (appBuildSubCommands.length !== 1) {
221
+ break common_case;
222
+ }
223
+ const [appBuildSubCommand] = appBuildSubCommands;
224
+ const isNpmRunBuild = (() => {
225
+ for (const packageManager of ["npm", "yarn", "pnpm", "bun", "deno"]) {
226
+ for (const doUseRun of [true, false]) {
227
+ if (`${packageManager}${doUseRun ? " run " : " "}build` ===
228
+ appBuildSubCommand) {
229
+ return true;
230
+ }
231
+ }
232
+ }
233
+ return false;
234
+ })();
235
+ if (!isNpmRunBuild) {
236
+ break common_case;
237
+ }
238
+ const { scripts } = parsedPackageJson;
239
+ (0,assert/* assert */.h)(scripts !== undefined);
240
+ const buildCmd = scripts.build;
241
+ if (buildCmd !== "tsc && vite build") {
242
+ break common_case;
243
+ }
244
+ if (scripts.prebuild !== undefined) {
245
+ break common_case;
246
+ }
247
+ if (scripts.postbuild !== undefined) {
248
+ break common_case;
249
+ }
250
+ const dIsSuccess = new Deferred.Deferred();
251
+ console.log(source_default().blue("$ npx vite build"));
252
+ const child = external_child_process_.spawn("npx", ["vite", "build"], {
253
+ cwd: buildContext.projectDirPath,
254
+ shell: true
255
+ });
256
+ child.stdout.on("data", data => {
257
+ if (data.toString("utf8").includes("gzip:")) {
258
+ return;
259
+ }
260
+ process.stdout.write(data);
261
+ });
262
+ child.stderr.on("data", data => process.stderr.write(data));
263
+ child.on("exit", code => dIsSuccess.resolve(code === 0));
264
+ const isSuccess = await dIsSuccess.pr;
265
+ return { isAppBuildSuccess: isSuccess };
266
+ }
267
+ let commandCwd = (0,external_path_.dirname)(buildContext.packageJsonFilePath);
268
+ for (const subCommand of appBuildSubCommands) {
269
+ const dIsSuccess = new Deferred.Deferred();
270
+ const [command, ...args] = subCommand.split(" ");
271
+ if (command === "cd") {
272
+ const [pathIsh] = args;
273
+ commandCwd = (0,getAbsoluteAndInOsFormatPath/* getAbsoluteAndInOsFormatPath */.c)({
274
+ pathIsh,
275
+ cwd: commandCwd
276
+ });
277
+ continue;
278
+ }
279
+ console.log(source_default().blue(`$ ${subCommand}`));
280
+ const child = external_child_process_.spawn(command, args, {
281
+ cwd: commandCwd,
282
+ env: Object.assign(Object.assign({}, process.env), { PATH: (() => {
283
+ var _a;
284
+ const separator = external_path_.sep === "/" ? ":" : ";";
285
+ return [
286
+ (0,external_path_.join)((0,external_path_.dirname)(buildContext.packageJsonFilePath), "node_modules", ".bin"),
287
+ ...((_a = process.env.PATH) !== null && _a !== void 0 ? _a : "").split(separator)
288
+ ].join(separator);
289
+ })() }),
290
+ shell: true
291
+ });
292
+ child.stdout.on("data", data => process.stdout.write(data));
293
+ child.stderr.on("data", data => process.stderr.write(data));
294
+ child.on("exit", code => dIsSuccess.resolve(code === 0));
295
+ const isSuccess = await dIsSuccess.pr;
296
+ if (!isSuccess) {
297
+ return { isAppBuildSuccess: false };
298
+ }
299
+ }
300
+ return { isAppBuildSuccess: true };
301
+ }
302
+ //# sourceMappingURL=appBuild.js.map
303
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/keycloakifyBuild.js
304
+
305
+
306
+
307
+
308
+
309
+ (0,assert/* assert */.h)();
310
+ async function keycloakifyBuild(params) {
311
+ const { buildForKeycloakMajorVersionNumber, buildContext } = params;
312
+ const dResult = new Deferred.Deferred();
313
+ console.log(source_default().blue("$ npx keycloakify build"));
314
+ const child = external_child_process_.spawn("npx", ["keycloakify", "build"], {
315
+ cwd: buildContext.projectDirPath,
316
+ env: Object.assign(Object.assign({}, process.env), { [constants/* BUILD_FOR_KEYCLOAK_MAJOR_VERSION_ENV_NAME */.ac]: `${buildForKeycloakMajorVersionNumber}` }),
317
+ shell: true
318
+ });
319
+ child.stdout.on("data", data => process.stdout.write(data));
320
+ child.stderr.on("data", data => process.stderr.write(data));
321
+ child.on("exit", code => dResult.resolve({ isSuccess: code === 0 }));
322
+ const { isSuccess } = await dResult.pr;
323
+ return { isKeycloakifyBuildSuccess: isSuccess };
324
+ }
325
+ //# sourceMappingURL=keycloakifyBuild.js.map
326
+ // EXTERNAL MODULE: ./dist/bin/tools/isInside.js
327
+ var isInside = __webpack_require__(90665);
328
+ ;// CONCATENATED MODULE: ./dist/bin/tools/fs.rm.js
329
+
330
+
331
+
332
+ /**
333
+ * Polyfill of fs.rm(dirPath, { "recursive": true })
334
+ * For older version of Node
335
+ */
336
+ async function rm(dirPath, options) {
337
+ if (SemVer/* SemVer.compare */.h.compare(SemVer/* SemVer.parse */.h.parse(process.version), SemVer/* SemVer.parse */.h.parse("14.14.0")) > 0) {
338
+ return promises_.rm(dirPath, options);
339
+ }
340
+ const { force = true } = options;
341
+ if (force && !(await checkDirExists(dirPath))) {
342
+ return;
343
+ }
344
+ const removeDir_rec = async (dirPath) => Promise.all((await promises_.readdir(dirPath)).map(async (basename) => {
345
+ const fileOrDirpath = (0,external_path_.join)(dirPath, basename);
346
+ if ((await promises_.lstat(fileOrDirpath)).isDirectory()) {
347
+ await removeDir_rec(fileOrDirpath);
348
+ }
349
+ else {
350
+ await promises_.unlink(fileOrDirpath);
351
+ }
352
+ }));
353
+ await removeDir_rec(dirPath);
354
+ }
355
+ async function checkDirExists(dirPath) {
356
+ try {
357
+ await promises_.access(dirPath, promises_.constants.F_OK);
358
+ return true;
359
+ }
360
+ catch (_a) {
361
+ return false;
362
+ }
363
+ }
364
+ //# sourceMappingURL=fs.rm.js.map
365
+ // EXTERNAL MODULE: ./node_modules/make-fetch-happen/lib/index.js
366
+ var make_fetch_happen_lib = __webpack_require__(9525);
367
+ var lib_default = /*#__PURE__*/__webpack_require__.n(make_fetch_happen_lib);
368
+ // EXTERNAL MODULE: external "crypto"
369
+ var external_crypto_ = __webpack_require__(6113);
370
+ ;// CONCATENATED MODULE: ./dist/bin/tools/downloadAndExtractArchive.js
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+ async function downloadAndExtractArchive(params) {
380
+ var _a;
381
+ const { url, uniqueIdOfOnArchiveFile, onArchiveFile, cacheDirPath, fetchOptions } = params;
382
+ const archiveFileBasename = url.split("?")[0].split("/").reverse()[0];
383
+ const archiveFilePath = (0,external_path_.join)(cacheDirPath, archiveFileBasename);
384
+ download: {
385
+ await (0,promises_.mkdir)((0,external_path_.dirname)(archiveFilePath), { recursive: true });
386
+ if (await (0,fs_existsAsync/* existsAsync */.o)(archiveFilePath)) {
387
+ const isDownloaded = await SuccessTracker.getIsDownloaded({
388
+ cacheDirPath,
389
+ archiveFileBasename
390
+ });
391
+ if (isDownloaded) {
392
+ break download;
393
+ }
394
+ await (0,promises_.unlink)(archiveFilePath);
395
+ await SuccessTracker.removeFromDownloaded({
396
+ cacheDirPath,
397
+ archiveFileBasename
398
+ });
399
+ }
400
+ const response = await lib_default()(url, fetchOptions);
401
+ (_a = response.body) === null || _a === void 0 ? void 0 : _a.setMaxListeners(Number.MAX_VALUE);
402
+ (0,assert/* assert */.h)(typeof response.body !== "undefined" && response.body != null);
403
+ await (0,promises_.writeFile)(archiveFilePath, response.body);
404
+ await SuccessTracker.markAsDownloaded({
405
+ cacheDirPath,
406
+ archiveFileBasename
407
+ });
408
+ }
409
+ const extractDirBasename = `${archiveFileBasename.replace(/\.([^.]+)$/, (...[, ext]) => `_${ext}`)}_${uniqueIdOfOnArchiveFile}_${external_crypto_.createHash("sha256")
410
+ .update(onArchiveFile.toString())
411
+ .digest("hex")
412
+ .substring(0, 5)}`;
413
+ await Promise.all((await (0,promises_.readdir)(cacheDirPath))
414
+ .filter((() => {
415
+ const prefix = extractDirBasename
416
+ .split("_")
417
+ .reverse()
418
+ .slice(1)
419
+ .reverse()
420
+ .join("_");
421
+ return basename => basename !== extractDirBasename && basename.startsWith(prefix);
422
+ })())
423
+ .map(async (extractDirBasename) => {
424
+ await rm((0,external_path_.join)(cacheDirPath, extractDirBasename), {
425
+ recursive: true
426
+ });
427
+ await SuccessTracker.removeFromExtracted({
428
+ cacheDirPath,
429
+ extractDirBasename
430
+ });
431
+ }));
432
+ const extractedDirPath = (0,external_path_.join)(cacheDirPath, extractDirBasename);
433
+ extract_and_transform: {
434
+ if (await (0,fs_existsAsync/* existsAsync */.o)(extractedDirPath)) {
435
+ const isExtracted = await SuccessTracker.getIsExtracted({
436
+ cacheDirPath,
437
+ extractDirBasename
438
+ });
439
+ if (isExtracted) {
440
+ break extract_and_transform;
441
+ }
442
+ await rm(extractedDirPath, { recursive: true });
443
+ await SuccessTracker.removeFromExtracted({
444
+ cacheDirPath,
445
+ extractDirBasename
446
+ });
447
+ }
448
+ await extractArchive({
449
+ archiveFilePath,
450
+ onArchiveFile: async ({ relativeFilePathInArchive, readFile, writeFile }) => onArchiveFile({
451
+ fileRelativePath: relativeFilePathInArchive,
452
+ readFile,
453
+ writeFile: ({ fileRelativePath, modifiedData }) => writeFile({
454
+ filePath: (0,external_path_.join)(extractedDirPath, fileRelativePath),
455
+ modifiedData
456
+ })
457
+ })
458
+ });
459
+ await SuccessTracker.markAsExtracted({
460
+ cacheDirPath,
461
+ extractDirBasename
462
+ });
463
+ }
464
+ return { extractedDirPath, archiveFilePath };
465
+ }
466
+ var SuccessTracker;
467
+ (function (SuccessTracker) {
468
+ async function read(params) {
469
+ const { cacheDirPath } = params;
470
+ const filePath = (0,external_path_.join)(cacheDirPath, "downloadAndExtractArchive.json");
471
+ if (!(await (0,fs_existsAsync/* existsAsync */.o)(filePath))) {
472
+ return { archiveFileBasenames: [], extractDirBasenames: [] };
473
+ }
474
+ return JSON.parse((await (0,promises_.readFile)(filePath)).toString("utf8"));
475
+ }
476
+ async function write(params) {
477
+ const { cacheDirPath, successTracker } = params;
478
+ const filePath = (0,external_path_.join)(cacheDirPath, "downloadAndExtractArchive.json");
479
+ {
480
+ const dirPath = (0,external_path_.dirname)(filePath);
481
+ if (!(await (0,fs_existsAsync/* existsAsync */.o)(dirPath))) {
482
+ await (0,promises_.mkdir)(dirPath, { recursive: true });
483
+ }
484
+ }
485
+ await (0,promises_.writeFile)(filePath, JSON.stringify(successTracker));
486
+ }
487
+ async function markAsDownloaded(params) {
488
+ const { cacheDirPath, archiveFileBasename } = params;
489
+ const successTracker = await read({ cacheDirPath });
490
+ successTracker.archiveFileBasenames.push(archiveFileBasename);
491
+ await write({ cacheDirPath, successTracker });
492
+ }
493
+ SuccessTracker.markAsDownloaded = markAsDownloaded;
494
+ async function getIsDownloaded(params) {
495
+ const { cacheDirPath, archiveFileBasename } = params;
496
+ const successTracker = await read({ cacheDirPath });
497
+ return successTracker.archiveFileBasenames.includes(archiveFileBasename);
498
+ }
499
+ SuccessTracker.getIsDownloaded = getIsDownloaded;
500
+ async function removeFromDownloaded(params) {
501
+ const { cacheDirPath, archiveFileBasename } = params;
502
+ const successTracker = await read({ cacheDirPath });
503
+ successTracker.archiveFileBasenames = successTracker.archiveFileBasenames.filter(basename => basename !== archiveFileBasename);
504
+ await write({ cacheDirPath, successTracker });
505
+ }
506
+ SuccessTracker.removeFromDownloaded = removeFromDownloaded;
507
+ async function markAsExtracted(params) {
508
+ const { cacheDirPath, extractDirBasename } = params;
509
+ const successTracker = await read({ cacheDirPath });
510
+ successTracker.extractDirBasenames.push(extractDirBasename);
511
+ await write({ cacheDirPath, successTracker });
512
+ }
513
+ SuccessTracker.markAsExtracted = markAsExtracted;
514
+ async function getIsExtracted(params) {
515
+ const { cacheDirPath, extractDirBasename } = params;
516
+ const successTracker = await read({ cacheDirPath });
517
+ return successTracker.extractDirBasenames.includes(extractDirBasename);
518
+ }
519
+ SuccessTracker.getIsExtracted = getIsExtracted;
520
+ async function removeFromExtracted(params) {
521
+ const { cacheDirPath, extractDirBasename } = params;
522
+ const successTracker = await read({ cacheDirPath });
523
+ successTracker.extractDirBasenames = successTracker.extractDirBasenames.filter(basename => basename !== extractDirBasename);
524
+ await write({ cacheDirPath, successTracker });
525
+ }
526
+ SuccessTracker.removeFromExtracted = removeFromExtracted;
527
+ })(SuccessTracker || (SuccessTracker = {}));
528
+ //# sourceMappingURL=downloadAndExtractArchive.js.map
529
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/startViteDevServer.js
530
+
531
+
532
+
533
+
534
+
535
+ (0,assert/* assert */.h)();
536
+ function startViteDevServer(params) {
40
537
  const { buildContext } = params;
41
- const { hasBeenHandled } = (0,_shared_customHandler_delegate__WEBPACK_IMPORTED_MODULE_8__/* .maybeDelegateCommandToCustomHandler */ .q)({
42
- commandName: "add-story",
538
+ console.log(source_default().blue(`$ npx vite dev`));
539
+ const child = external_child_process_.spawn("npx", ["vite", "dev"], {
540
+ cwd: buildContext.projectDirPath,
541
+ env: Object.assign(Object.assign({}, process.env), { [constants/* VITE_PLUGIN_SUB_SCRIPTS_ENV_NAMES.READ_KC_CONTEXT_FROM_URL */.TE.READ_KC_CONTEXT_FROM_URL]: "true" }),
542
+ shell: true
543
+ });
544
+ child.stdout.on("data", data => {
545
+ if (!data.toString("utf8").includes("[vite] hmr")) {
546
+ return;
547
+ }
548
+ process.stdout.write(data);
549
+ });
550
+ child.stderr.on("data", data => process.stderr.write(data));
551
+ const dPort = new Deferred.Deferred();
552
+ {
553
+ const onData = (data) => {
554
+ //Local: http://localhost:8083/
555
+ const match = data
556
+ .toString("utf8")
557
+ .replace(/\x1b[[0-9;]*m/g, "")
558
+ .match(/Local:\s*http:\/\/(?:localhost|127\.0\.0\.1):(\d+)\//);
559
+ if (match === null) {
560
+ return;
561
+ }
562
+ child.stdout.off("data", onData);
563
+ const port = parseInt(match[1]);
564
+ (0,assert/* assert */.h)(!isNaN(port));
565
+ dPort.resolve(port);
566
+ };
567
+ child.stdout.on("data", onData);
568
+ }
569
+ return dPort.pr.then(port => ({ port }));
570
+ }
571
+ //# sourceMappingURL=startViteDevServer.js.map
572
+ // EXTERNAL MODULE: ./node_modules/tsafe/esm/is.mjs
573
+ var is = __webpack_require__(16453);
574
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/realmConfig/ParsedRealmJson/ParsedRealmJson.js
575
+
576
+
577
+
578
+ const zParsedRealmJson = (() => {
579
+ const zTargetType = lib.z.object({
580
+ realm: lib.z.string(),
581
+ loginTheme: lib.z.string().optional(),
582
+ accountTheme: lib.z.string().optional(),
583
+ adminTheme: lib.z.string().optional(),
584
+ emailTheme: lib.z.string().optional(),
585
+ eventsListeners: lib.z.array(lib.z.string()),
586
+ users: lib.z.array(lib.z.object({
587
+ id: lib.z.string(),
588
+ email: lib.z.string(),
589
+ username: lib.z.string(),
590
+ credentials: lib.z.array(lib.z.object({
591
+ type: lib.z.string()
592
+ })),
593
+ clientRoles: lib.z.record(lib.z.array(lib.z.string())).optional()
594
+ })),
595
+ roles: lib.z.object({
596
+ client: lib.z.record(lib.z.array(lib.z.object({
597
+ name: lib.z.string(),
598
+ containerId: lib.z.string()
599
+ })))
600
+ }),
601
+ clients: lib.z.array(lib.z.object({
602
+ id: lib.z.string(),
603
+ clientId: lib.z.string(),
604
+ baseUrl: lib.z.string().optional(),
605
+ redirectUris: lib.z.array(lib.z.string()).optional(),
606
+ webOrigins: lib.z.array(lib.z.string()).optional(),
607
+ attributes: lib.z.object({
608
+ "post.logout.redirect.uris": lib.z.string().optional()
609
+ })
610
+ .optional(),
611
+ protocol: lib.z.string().optional(),
612
+ protocolMappers: lib.z.array(lib.z.object({
613
+ id: lib.z.string(),
614
+ name: lib.z.string(),
615
+ protocol: lib.z.string(),
616
+ protocolMapper: lib.z.string(),
617
+ consentRequired: lib.z.boolean(),
618
+ config: lib.z.record(lib.z.string()).optional()
619
+ }))
620
+ .optional()
621
+ }))
622
+ });
623
+ assert/* assert */.h;
624
+ return (0,id.id)(zTargetType);
625
+ })();
626
+ //# sourceMappingURL=ParsedRealmJson.js.map
627
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/realmConfig/ParsedRealmJson/readRealmJsonFile.js
628
+
629
+
630
+
631
+
632
+ function readRealmJsonFile(params) {
633
+ const { realmJsonFilePath } = params;
634
+ const parsedRealmJson = JSON.parse(external_fs_.readFileSync(realmJsonFilePath).toString("utf8"));
635
+ zParsedRealmJson.parse(parsedRealmJson);
636
+ (0,assert/* assert */.h)((0,is.is)(parsedRealmJson));
637
+ return parsedRealmJson;
638
+ }
639
+ //# sourceMappingURL=readRealmJsonFile.js.map
640
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/realmConfig/defaultConfig/defaultConfig.js
641
+
642
+
643
+
644
+
645
+
646
+
647
+ function getDefaultRealmJsonFilePath(params) {
648
+ const { keycloakMajorVersionNumber } = params;
649
+ return (0,external_path_.join)((0,getThisCodebaseRootDirPath/* getThisCodebaseRootDirPath */.e)(), "src", "bin", "start-keycloak", "realmConfig", "defaultConfig", `realm-kc-${keycloakMajorVersionNumber}.json`);
650
+ }
651
+ const { getSupportedKeycloakMajorVersions } = (() => {
652
+ let cache = undefined;
653
+ function getSupportedKeycloakMajorVersions() {
654
+ if (cache !== undefined) {
655
+ return cache;
656
+ }
657
+ cache = external_fs_.readdirSync((0,external_path_.dirname)(getDefaultRealmJsonFilePath({ keycloakMajorVersionNumber: 0 })))
658
+ .map(fileBasename => {
659
+ const match = fileBasename.match(/^realm-kc-(\d+)\.json$/);
660
+ if (match === null) {
661
+ return undefined;
662
+ }
663
+ const n = parseInt(match[1]);
664
+ (0,assert/* assert */.h)(!isNaN(n));
665
+ return n;
666
+ })
667
+ .filter((0,exclude/* exclude */.D)(undefined))
668
+ .sort((a, b) => b - a);
669
+ return cache;
670
+ }
671
+ return { getSupportedKeycloakMajorVersions };
672
+ })();
673
+ function getDefaultConfig(params) {
674
+ const { keycloakMajorVersionNumber } = params;
675
+ (0,assert/* assert */.h)(getSupportedKeycloakMajorVersions().includes(keycloakMajorVersionNumber), `We do not have a default config for Keycloak ${keycloakMajorVersionNumber}`);
676
+ return readRealmJsonFile({
677
+ realmJsonFilePath: getDefaultRealmJsonFilePath({
678
+ keycloakMajorVersionNumber
679
+ })
680
+ });
681
+ }
682
+ //# sourceMappingURL=defaultConfig.js.map
683
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/realmConfig/defaultConfig/index.js
684
+
685
+ //# sourceMappingURL=index.js.map
686
+ // EXTERNAL MODULE: ./dist/bin/tools/readThisNpmPackageVersion.js
687
+ var readThisNpmPackageVersion = __webpack_require__(64795);
688
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/getSupportedDockerImageTags.js
689
+
690
+
691
+
692
+
693
+
694
+
695
+
696
+
697
+
698
+
699
+
700
+ assert/* assert */.h;
701
+ async function getSupportedDockerImageTags(params) {
702
+ const { buildContext } = params;
703
+ {
704
+ const result = await getCachedValue({ cacheDirPath: buildContext.cacheDirPath });
705
+ if (result !== undefined) {
706
+ return result;
707
+ }
708
+ }
709
+ const tags_queryResponse = [];
710
+ await (async function callee(url) {
711
+ const r = await lib_default()(url, buildContext.fetchOptions);
712
+ await Promise.all([
713
+ (async () => {
714
+ tags_queryResponse.push(...lib.z.object({
715
+ tags: lib.z.array(lib.z.string())
716
+ })
717
+ .parse(await r.json()).tags);
718
+ })(),
719
+ (async () => {
720
+ const link = r.headers.get("link");
721
+ if (link === null) {
722
+ return;
723
+ }
724
+ const split = link.split(";").map(s => s.trim());
725
+ (0,assert/* assert */.h)(split.length === 2);
726
+ (0,assert/* assert */.h)(split[1] === 'rel="next"');
727
+ const match = split[0].match(/^<(.+)>$/);
728
+ (0,assert/* assert */.h)(match !== null);
729
+ const nextUrl = new URL(url).origin + match[1];
730
+ await callee(nextUrl);
731
+ })()
732
+ ]);
733
+ })("https://quay.io/v2/keycloak/keycloak/tags/list");
734
+ const supportedKeycloakMajorVersions = getSupportedKeycloakMajorVersions();
735
+ const allSupportedTags_withVersion = tags_queryResponse
736
+ .map(tag => ({
737
+ tag,
738
+ version: (() => {
739
+ if (tag.includes("-")) {
740
+ return undefined;
741
+ }
742
+ let version;
743
+ try {
744
+ version = SemVer/* SemVer.parse */.h.parse(tag);
745
+ }
746
+ catch (_a) {
747
+ return undefined;
748
+ }
749
+ if (tag.split(".").length !== 3) {
750
+ return undefined;
751
+ }
752
+ if (!supportedKeycloakMajorVersions.includes(version.major)) {
753
+ return undefined;
754
+ }
755
+ return version;
756
+ })()
757
+ }))
758
+ .map(({ tag, version }) => (version === undefined ? undefined : { tag, version }))
759
+ .filter((0,exclude/* exclude */.D)(undefined))
760
+ .sort(({ version: a }, { version: b }) => SemVer/* SemVer.compare */.h.compare(b, a));
761
+ const latestTagByMajor = {};
762
+ for (const { version } of allSupportedTags_withVersion) {
763
+ const version_current = latestTagByMajor[version.major];
764
+ if (version_current === undefined ||
765
+ SemVer/* SemVer.compare */.h.compare(version_current, version) === -1) {
766
+ latestTagByMajor[version.major] = version;
767
+ }
768
+ }
769
+ const latestMajorTags = Object.entries(latestTagByMajor)
770
+ .sort(([a], [b]) => parseInt(b) - parseInt(a))
771
+ .map(([, version]) => version)
772
+ .map(version => {
773
+ (0,assert/* assert */.h)(version !== undefined);
774
+ if (!supportedKeycloakMajorVersions.includes(version.major)) {
775
+ return undefined;
776
+ }
777
+ return SemVer/* SemVer.stringify */.h.stringify(version);
778
+ })
779
+ .filter((0,exclude/* exclude */.D)(undefined));
780
+ const allSupportedTags = allSupportedTags_withVersion.map(({ tag }) => tag);
781
+ const result = {
782
+ latestMajorTags,
783
+ allSupportedTags
784
+ };
785
+ await setCachedValue({ cacheDirPath: buildContext.cacheDirPath, result });
786
+ return result;
787
+ }
788
+ const { getCachedValue, setCachedValue } = (() => {
789
+ const zResult = (() => {
790
+ const zTargetType = lib.z.object({
791
+ allSupportedTags: lib.z.array(lib.z.string()),
792
+ latestMajorTags: lib.z.array(lib.z.string())
793
+ });
794
+ assert/* assert */.h;
795
+ return (0,id.id)(zTargetType);
796
+ })();
797
+ const zCache = (() => {
798
+ const zTargetType = lib.z.object({
799
+ keycloakifyVersion: lib.z.string(),
800
+ time: lib.z.number(),
801
+ result: zResult
802
+ });
803
+ assert/* assert */.h;
804
+ return (0,id.id)(zTargetType);
805
+ })();
806
+ let inMemoryCachedResult = undefined;
807
+ function getCacheFilePath(params) {
808
+ const { cacheDirPath } = params;
809
+ return (0,external_path_.join)(cacheDirPath, "supportedDockerImageTags.json");
810
+ }
811
+ async function getCachedValue(params) {
812
+ const { cacheDirPath } = params;
813
+ if (inMemoryCachedResult !== undefined) {
814
+ return inMemoryCachedResult;
815
+ }
816
+ const cacheFilePath = getCacheFilePath({ cacheDirPath });
817
+ if (!(await (0,fs_existsAsync/* existsAsync */.o)(cacheFilePath))) {
818
+ return undefined;
819
+ }
820
+ let cache;
821
+ try {
822
+ cache = zCache.parse(JSON.parse(await promises_.readFile(cacheFilePath, "utf8")));
823
+ }
824
+ catch (_a) {
825
+ return undefined;
826
+ }
827
+ if (cache.keycloakifyVersion !== (0,readThisNpmPackageVersion/* readThisNpmPackageVersion */.K)()) {
828
+ return undefined;
829
+ }
830
+ if (Date.now() - cache.time > 3600 * 24) {
831
+ return undefined;
832
+ }
833
+ inMemoryCachedResult = cache.result;
834
+ return cache.result;
835
+ }
836
+ async function setCachedValue(params) {
837
+ const { cacheDirPath, result } = params;
838
+ inMemoryCachedResult = result;
839
+ const cacheFilePath = getCacheFilePath({ cacheDirPath });
840
+ {
841
+ const dirPath = (0,external_path_.dirname)(cacheFilePath);
842
+ if (!(await (0,fs_existsAsync/* existsAsync */.o)(dirPath))) {
843
+ await promises_.mkdir(dirPath, { recursive: true });
844
+ }
845
+ }
846
+ await promises_.writeFile(cacheFilePath, JSON.stringify(zCache.parse({
847
+ keycloakifyVersion: (0,readThisNpmPackageVersion/* readThisNpmPackageVersion */.K)(),
848
+ time: Date.now(),
849
+ result
850
+ }), null, 2));
851
+ }
852
+ return {
853
+ getCachedValue,
854
+ setCachedValue
855
+ };
856
+ })();
857
+ //# sourceMappingURL=getSupportedDockerImageTags.js.map
858
+ // EXTERNAL MODULE: ./node_modules/evt/tools/inDepth/same.js
859
+ var same = __webpack_require__(33805);
860
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/realmConfig/prepareRealmConfig.js
861
+
862
+
863
+
864
+
865
+ function prepareRealmConfig(params) {
866
+ const { parsedRealmJson, keycloakMajorVersionNumber, parsedKeycloakThemesJsonEntry } = params;
867
+ const { username } = addOrEditTestUser({
868
+ parsedRealmJson,
869
+ keycloakMajorVersionNumber
870
+ });
871
+ const { clientId } = addOrEditClient({
872
+ parsedRealmJson,
873
+ keycloakMajorVersionNumber
874
+ });
875
+ editAccountConsoleAndSecurityAdminConsole({ parsedRealmJson });
876
+ enableCustomThemes({
877
+ parsedRealmJson,
878
+ parsedKeycloakThemesJsonEntry
879
+ });
880
+ enable_custom_events_listeners: {
881
+ const name = "keycloakify-logging";
882
+ if (parsedRealmJson.eventsListeners.includes(name)) {
883
+ break enable_custom_events_listeners;
884
+ }
885
+ parsedRealmJson.eventsListeners.push(name);
886
+ parsedRealmJson.eventsListeners.sort();
887
+ }
888
+ return {
889
+ realmName: parsedRealmJson.realm,
890
+ clientName: clientId,
891
+ username
892
+ };
893
+ }
894
+ function enableCustomThemes(params) {
895
+ const { parsedRealmJson, parsedKeycloakThemesJsonEntry } = params;
896
+ for (const themeType of [...constants/* THEME_TYPES */.Jh, "email"]) {
897
+ parsedRealmJson[`${themeType}Theme`] =
898
+ !parsedKeycloakThemesJsonEntry.types.includes(themeType)
899
+ ? ""
900
+ : parsedKeycloakThemesJsonEntry.name;
901
+ }
902
+ }
903
+ function addOrEditTestUser(params) {
904
+ var _a, _b, _c, _d;
905
+ const { parsedRealmJson, keycloakMajorVersionNumber } = params;
906
+ const parsedRealmJson_default = getDefaultConfig({ keycloakMajorVersionNumber });
907
+ const [defaultUser_default] = parsedRealmJson_default.users;
908
+ (0,assert/* assert */.h)(defaultUser_default !== undefined);
909
+ const defaultUser_preexisting = parsedRealmJson.users.find(user => user.username === defaultUser_default.username);
910
+ const newUser = structuredClone((_a = defaultUser_preexisting !== null && defaultUser_preexisting !== void 0 ? defaultUser_preexisting : (() => {
911
+ const firstUser = parsedRealmJson.users[0];
912
+ if (firstUser === undefined) {
913
+ return undefined;
914
+ }
915
+ const firstUserCopy = structuredClone(firstUser);
916
+ firstUserCopy.id = defaultUser_default.id;
917
+ return firstUserCopy;
918
+ })()) !== null && _a !== void 0 ? _a : defaultUser_default);
919
+ newUser.username = defaultUser_default.username;
920
+ newUser.email = defaultUser_default.email;
921
+ delete_existing_password_credential_if_any: {
922
+ const i = newUser.credentials.findIndex(credential => credential.type === "password");
923
+ if (i === -1) {
924
+ break delete_existing_password_credential_if_any;
925
+ }
926
+ newUser.credentials.splice(i, 1);
927
+ }
928
+ {
929
+ const credential = defaultUser_default.credentials.find(credential => credential.type === "password");
930
+ (0,assert/* assert */.h)(credential !== undefined);
931
+ newUser.credentials.push(credential);
932
+ }
933
+ {
934
+ const nameByClientId = Object.fromEntries(parsedRealmJson.clients.map(client => [client.id, client.clientId]));
935
+ const newClientRoles = {};
936
+ for (const clientRole of Object.values(parsedRealmJson.roles.client).flat()) {
937
+ const clientName = nameByClientId[clientRole.containerId];
938
+ (0,assert/* assert */.h)(clientName !== undefined);
939
+ ((_b = newClientRoles[clientName]) !== null && _b !== void 0 ? _b : (newClientRoles[clientName] = [])).push(clientRole.name);
940
+ }
941
+ const { same: sameSet } = (0,same.sameFactory)({
942
+ takeIntoAccountArraysOrdering: false
943
+ });
944
+ for (const [clientName, roles] of Object.entries(newClientRoles)) {
945
+ keep_previous_ordering_if_possible: {
946
+ const roles_previous = (_c = newUser.clientRoles) === null || _c === void 0 ? void 0 : _c[clientName];
947
+ if (roles_previous === undefined) {
948
+ break keep_previous_ordering_if_possible;
949
+ }
950
+ if (!sameSet(roles_previous, roles)) {
951
+ break keep_previous_ordering_if_possible;
952
+ }
953
+ continue;
954
+ }
955
+ ((_d = newUser.clientRoles) !== null && _d !== void 0 ? _d : (newUser.clientRoles = {}))[clientName] = roles;
956
+ }
957
+ }
958
+ if (defaultUser_preexisting === undefined) {
959
+ parsedRealmJson.users.push(newUser);
960
+ }
961
+ else {
962
+ const i = parsedRealmJson.users.indexOf(defaultUser_preexisting);
963
+ (0,assert/* assert */.h)(i !== -1);
964
+ parsedRealmJson.users[i] = newUser;
965
+ }
966
+ return { username: newUser.username };
967
+ }
968
+ function addOrEditClient(params) {
969
+ var _a;
970
+ const { parsedRealmJson, keycloakMajorVersionNumber } = params;
971
+ const parsedRealmJson_default = getDefaultConfig({ keycloakMajorVersionNumber });
972
+ const testClient_default = (() => {
973
+ const clients = parsedRealmJson_default.clients.filter(client => {
974
+ return JSON.stringify(client).includes(constants/* TEST_APP_URL */.jp);
975
+ });
976
+ (0,assert/* assert */.h)(clients.length === 1);
977
+ return clients[0];
978
+ })();
979
+ const clientIds_builtIn = parsedRealmJson_default.clients
980
+ .map(client => client.clientId)
981
+ .filter(clientId => clientId !== testClient_default.clientId);
982
+ const testClient_preexisting = (() => {
983
+ const clients = parsedRealmJson.clients
984
+ .filter(client => !clientIds_builtIn.includes(client.clientId))
985
+ .filter(client => client.protocol === "openid-connect");
986
+ {
987
+ const client = clients.find(client => client.clientId === testClient_default.clientId);
988
+ if (client !== undefined) {
989
+ return client;
990
+ }
991
+ }
992
+ {
993
+ const client = clients.find(client => {
994
+ var _a;
995
+ return ((_a = client.redirectUris) === null || _a === void 0 ? void 0 : _a.find(redirectUri => redirectUri.startsWith(constants/* TEST_APP_URL */.jp))) !== undefined;
996
+ });
997
+ if (client !== undefined) {
998
+ return client;
999
+ }
1000
+ }
1001
+ const [client] = clients;
1002
+ if (client === undefined) {
1003
+ return undefined;
1004
+ }
1005
+ return client;
1006
+ })();
1007
+ let testClient;
1008
+ if (testClient_preexisting !== undefined) {
1009
+ testClient = testClient_preexisting;
1010
+ }
1011
+ else {
1012
+ testClient = structuredClone(testClient_default);
1013
+ delete testClient.protocolMappers;
1014
+ parsedRealmJson.clients.push(testClient);
1015
+ }
1016
+ testClient.redirectUris = [
1017
+ `${constants/* TEST_APP_URL */.jp}/*`,
1018
+ "http://localhost*",
1019
+ "http://127.0.0.1*"
1020
+ ]
1021
+ .sort()
1022
+ .reverse();
1023
+ ((_a = testClient.attributes) !== null && _a !== void 0 ? _a : (testClient.attributes = {}))["post.logout.redirect.uris"] = "+";
1024
+ testClient.webOrigins = ["*"];
1025
+ return { clientId: testClient.clientId };
1026
+ }
1027
+ function editAccountConsoleAndSecurityAdminConsole(params) {
1028
+ var _a, _b, _c, _d, _e;
1029
+ const { parsedRealmJson } = params;
1030
+ for (const clientId of ["account-console", "security-admin-console"]) {
1031
+ const client = parsedRealmJson.clients.find(client => client.clientId === clientId);
1032
+ (0,assert/* assert */.h)(client !== undefined);
1033
+ {
1034
+ const arr = ((_a = client.redirectUris) !== null && _a !== void 0 ? _a : (client.redirectUris = []));
1035
+ for (const value of ["http://localhost*", "http://127.0.0.1*"]) {
1036
+ if (!arr.includes(value)) {
1037
+ arr.push(value);
1038
+ }
1039
+ }
1040
+ (_b = client.redirectUris) === null || _b === void 0 ? void 0 : _b.sort().reverse();
1041
+ }
1042
+ ((_c = client.attributes) !== null && _c !== void 0 ? _c : (client.attributes = {}))["post.logout.redirect.uris"] = "+";
1043
+ client.webOrigins = ["*"];
1044
+ admin_specific: {
1045
+ if (clientId !== "security-admin-console") {
1046
+ break admin_specific;
1047
+ }
1048
+ const protocolMapper_preexisting = (_d = client.protocolMappers) === null || _d === void 0 ? void 0 : _d.find(protocolMapper => {
1049
+ if (protocolMapper.protocolMapper !== "oidc-hardcoded-claim-mapper") {
1050
+ return false;
1051
+ }
1052
+ if (protocolMapper.protocol !== "openid-connect") {
1053
+ return false;
1054
+ }
1055
+ if (protocolMapper.config === undefined) {
1056
+ return false;
1057
+ }
1058
+ if (protocolMapper.config["claim.name"] !== "allowed-origins") {
1059
+ return false;
1060
+ }
1061
+ return true;
1062
+ });
1063
+ let protocolMapper;
1064
+ const config = {
1065
+ "introspection.token.claim": "true",
1066
+ "claim.value": '["*"]',
1067
+ "userinfo.token.claim": "true",
1068
+ "id.token.claim": "false",
1069
+ "lightweight.claim": "true",
1070
+ "access.token.claim": "true",
1071
+ "claim.name": "allowed-origins",
1072
+ "jsonType.label": "JSON",
1073
+ "access.tokenResponse.claim": "false"
1074
+ };
1075
+ if (protocolMapper_preexisting !== undefined) {
1076
+ protocolMapper = protocolMapper_preexisting;
1077
+ }
1078
+ else {
1079
+ protocolMapper = {
1080
+ id: "8fd0d584-7052-4d04-a615-d18a71050873",
1081
+ name: "allowed-origins",
1082
+ protocol: "openid-connect",
1083
+ protocolMapper: "oidc-hardcoded-claim-mapper",
1084
+ consentRequired: false,
1085
+ config
1086
+ };
1087
+ ((_e = client.protocolMappers) !== null && _e !== void 0 ? _e : (client.protocolMappers = [])).push(protocolMapper);
1088
+ }
1089
+ (0,assert/* assert */.h)(protocolMapper.config !== undefined);
1090
+ if (config !== protocolMapper.config) {
1091
+ Object.assign(protocolMapper.config, config);
1092
+ }
1093
+ }
1094
+ }
1095
+ }
1096
+ //# sourceMappingURL=prepareRealmConfig.js.map
1097
+ // EXTERNAL MODULE: ./dist/bin/tools/runPrettier.js
1098
+ var runPrettier = __webpack_require__(48433);
1099
+ ;// CONCATENATED MODULE: ./dist/bin/tools/Stringifyable.js
1100
+
1101
+
1102
+
1103
+
1104
+ const zStringifyableAtomic = (() => {
1105
+ const zTargetType = lib.z.union([lib.z.string(), lib.z.number(), lib.z.boolean(), lib.z["null"]()]);
1106
+ (0,assert/* assert */.h)();
1107
+ return (0,id.id)(zTargetType);
1108
+ })();
1109
+ const zStringifyable = lib.z.any()
1110
+ .superRefine((val, ctx) => {
1111
+ const isStringifyable = (0,same.same)(JSON.parse(JSON.stringify(val)), val);
1112
+ if (!isStringifyable) {
1113
+ ctx.addIssue({
1114
+ code: lib.z.ZodIssueCode.custom,
1115
+ message: "Not stringifyable"
1116
+ });
1117
+ }
1118
+ });
1119
+ function getIsAtomic(stringifyable) {
1120
+ return (["string", "number", "boolean"].includes(typeof stringifyable) ||
1121
+ stringifyable === null);
1122
+ }
1123
+ const { getValueAtPath } = (() => {
1124
+ function getValueAtPath_rec(stringifyable, path) {
1125
+ if (path.length === 0) {
1126
+ return stringifyable;
1127
+ }
1128
+ if (getIsAtomic(stringifyable)) {
1129
+ return undefined;
1130
+ }
1131
+ const [first, ...rest] = path;
1132
+ let dereferenced;
1133
+ if (stringifyable instanceof Array) {
1134
+ if (typeof first !== "number") {
1135
+ return undefined;
1136
+ }
1137
+ dereferenced = stringifyable[first];
1138
+ }
1139
+ else {
1140
+ if (typeof first !== "string") {
1141
+ return undefined;
1142
+ }
1143
+ dereferenced = stringifyable[first];
1144
+ }
1145
+ if (dereferenced === undefined) {
1146
+ return undefined;
1147
+ }
1148
+ return getValueAtPath_rec(dereferenced, rest);
1149
+ }
1150
+ function getValueAtPath(stringifyableObjectOrArray, path) {
1151
+ return getValueAtPath_rec(stringifyableObjectOrArray, path);
1152
+ }
1153
+ return { getValueAtPath };
1154
+ })();
1155
+ //# sourceMappingURL=Stringifyable.js.map
1156
+ ;// CONCATENATED MODULE: ./dist/bin/tools/canonicalStringify.js
1157
+
1158
+ function canonicalStringify(params) {
1159
+ const { data, referenceData } = params;
1160
+ return JSON.stringify(makeDeterministicCopy({
1161
+ path: [],
1162
+ data,
1163
+ getCanonicalKeys: path => {
1164
+ const referenceValue = (() => {
1165
+ const path_patched = [];
1166
+ for (let i = 0; i < path.length; i++) {
1167
+ let value_i = getValueAtPath(referenceData, [
1168
+ ...path_patched,
1169
+ path[i]
1170
+ ]);
1171
+ if (value_i !== undefined) {
1172
+ path_patched.push(path[i]);
1173
+ continue;
1174
+ }
1175
+ if (typeof path[i] !== "number") {
1176
+ return undefined;
1177
+ }
1178
+ value_i = getValueAtPath(referenceData, [...path_patched, 0]);
1179
+ if (value_i !== undefined) {
1180
+ path_patched.push(0);
1181
+ continue;
1182
+ }
1183
+ return undefined;
1184
+ }
1185
+ return getValueAtPath(referenceData, path_patched);
1186
+ })();
1187
+ if (referenceValue === undefined) {
1188
+ return undefined;
1189
+ }
1190
+ if (getIsAtomic(referenceValue)) {
1191
+ return undefined;
1192
+ }
1193
+ if (referenceValue instanceof Array) {
1194
+ return undefined;
1195
+ }
1196
+ return Object.keys(referenceValue);
1197
+ }
1198
+ }), null, 2);
1199
+ }
1200
+ function makeDeterministicCopy(params) {
1201
+ const { path, data, getCanonicalKeys } = params;
1202
+ if (getIsAtomic(data)) {
1203
+ return data;
1204
+ }
1205
+ if (data instanceof Array) {
1206
+ return makeDeterministicCopy_array({
1207
+ path,
1208
+ data,
1209
+ getCanonicalKeys
1210
+ });
1211
+ }
1212
+ return makeDeterministicCopy_record({
1213
+ path,
1214
+ data,
1215
+ getCanonicalKeys
1216
+ });
1217
+ }
1218
+ function makeDeterministicCopy_record(params) {
1219
+ const { path, data, getCanonicalKeys } = params;
1220
+ const keysOfAtomicValues = [];
1221
+ const keysOfNonAtomicValues = [];
1222
+ for (const [key, value] of Object.entries(data)) {
1223
+ if (getIsAtomic(value)) {
1224
+ keysOfAtomicValues.push(key);
1225
+ }
1226
+ else {
1227
+ keysOfNonAtomicValues.push(key);
1228
+ }
1229
+ }
1230
+ keysOfAtomicValues.sort();
1231
+ keysOfNonAtomicValues.sort();
1232
+ const keys = [...keysOfAtomicValues, ...keysOfNonAtomicValues];
1233
+ reorder_according_to_canonical: {
1234
+ const canonicalKeys = getCanonicalKeys(path);
1235
+ if (canonicalKeys === undefined) {
1236
+ break reorder_according_to_canonical;
1237
+ }
1238
+ const keys_toPrepend = [];
1239
+ for (const key of canonicalKeys) {
1240
+ const indexOfKey = keys.indexOf(key);
1241
+ if (indexOfKey === -1) {
1242
+ continue;
1243
+ }
1244
+ keys.splice(indexOfKey, 1);
1245
+ keys_toPrepend.push(key);
1246
+ }
1247
+ keys.unshift(...keys_toPrepend);
1248
+ }
1249
+ const result = {};
1250
+ for (const key of keys) {
1251
+ result[key] = makeDeterministicCopy({
1252
+ path: [...path, key],
1253
+ data: data[key],
1254
+ getCanonicalKeys
1255
+ });
1256
+ }
1257
+ return result;
1258
+ }
1259
+ function makeDeterministicCopy_array(params) {
1260
+ const { path, data, getCanonicalKeys } = params;
1261
+ return [...data].map((entry, i) => makeDeterministicCopy({
1262
+ path: [...path, i],
1263
+ data: entry,
1264
+ getCanonicalKeys
1265
+ }));
1266
+ }
1267
+ //# sourceMappingURL=canonicalStringify.js.map
1268
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/realmConfig/ParsedRealmJson/writeRealmJsonFile.js
1269
+
1270
+
1271
+
1272
+
1273
+ async function writeRealmJsonFile(params) {
1274
+ const { realmJsonFilePath, parsedRealmJson, keycloakMajorVersionNumber } = params;
1275
+ let sourceCode = canonicalStringify({
1276
+ data: parsedRealmJson,
1277
+ referenceData: getDefaultConfig({
1278
+ keycloakMajorVersionNumber
1279
+ })
1280
+ });
1281
+ if (await (0,runPrettier/* getIsPrettierAvailable */.MT)()) {
1282
+ sourceCode = await (0,runPrettier/* runPrettier */.eY)({
1283
+ sourceCode: sourceCode,
1284
+ filePath: realmJsonFilePath
1285
+ });
1286
+ }
1287
+ await promises_.writeFile(realmJsonFilePath, Buffer.from(sourceCode, "utf8"));
1288
+ }
1289
+ //# sourceMappingURL=writeRealmJsonFile.js.map
1290
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/realmConfig/ParsedRealmJson/index.js
1291
+
1292
+
1293
+ //# sourceMappingURL=index.js.map
1294
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/realmConfig/dumpContainerConfig.js
1295
+
1296
+
1297
+
1298
+
1299
+
1300
+
1301
+
1302
+ (0,assert/* assert */.h)();
1303
+ async function dumpContainerConfig(params) {
1304
+ const { realmName, keycloakMajorVersionNumber, buildContext } = params;
1305
+ // https://github.com/keycloak/keycloak/issues/33800
1306
+ const doesUseLockedH2Database = keycloakMajorVersionNumber >= 25;
1307
+ if (doesUseLockedH2Database) {
1308
+ const dCompleted = new Deferred.Deferred();
1309
+ const cmd = `docker exec ${constants/* CONTAINER_NAME */.sv} sh -c "cp -rp /opt/keycloak/data/h2 /tmp"`;
1310
+ external_child_process_default().exec(cmd, error => {
1311
+ if (error !== null) {
1312
+ dCompleted.reject(error);
1313
+ return;
1314
+ }
1315
+ dCompleted.resolve();
1316
+ });
1317
+ try {
1318
+ await dCompleted.pr;
1319
+ }
1320
+ catch (error) {
1321
+ (0,assert/* assert */.h)((0,assert.is)(error));
1322
+ console.log(source_default().red(`Docker command failed: ${cmd}`));
1323
+ console.log(source_default().red(error.message));
1324
+ throw error;
1325
+ }
1326
+ }
1327
+ {
1328
+ const dCompleted = new Deferred.Deferred();
1329
+ const child = external_child_process_default().spawn("docker", [
1330
+ ...["exec", constants/* CONTAINER_NAME */.sv],
1331
+ ...["/opt/keycloak/bin/kc.sh", "export"],
1332
+ ...["--dir", "/tmp"],
1333
+ ...["--realm", realmName],
1334
+ ...["--users", "realm_file"],
1335
+ ...(!doesUseLockedH2Database
1336
+ ? []
1337
+ : [
1338
+ ...["--db", "dev-file"],
1339
+ ...[
1340
+ "--db-url",
1341
+ '"jdbc:h2:file:/tmp/h2/keycloakdb;NON_KEYWORDS=VALUE"'
1342
+ ]
1343
+ ])
1344
+ ], { shell: true });
1345
+ let output = "";
1346
+ const onExit = (code) => {
1347
+ dCompleted.reject(new Error(`docker exec kc.sh export command failed with code ${code}`));
1348
+ };
1349
+ child.once("exit", onExit);
1350
+ child.stdout.on("data", data => {
1351
+ const outputStr = data.toString("utf8");
1352
+ if (outputStr.includes("Export finished successfully")) {
1353
+ child.removeListener("exit", onExit);
1354
+ // NOTE: On older Keycloak versions the process keeps running after the export is done.
1355
+ const timer = setTimeout(() => {
1356
+ child.removeListener("exit", onExit2);
1357
+ child.kill();
1358
+ dCompleted.resolve();
1359
+ }, 1500);
1360
+ const onExit2 = () => {
1361
+ clearTimeout(timer);
1362
+ dCompleted.resolve();
1363
+ };
1364
+ child.once("exit", onExit2);
1365
+ }
1366
+ output += outputStr;
1367
+ });
1368
+ child.stderr.on("data", data => (output += source_default().red(data.toString("utf8"))));
1369
+ try {
1370
+ await dCompleted.pr;
1371
+ }
1372
+ catch (error) {
1373
+ (0,assert/* assert */.h)((0,assert.is)(error));
1374
+ console.log(source_default().red(error.message));
1375
+ console.log(output);
1376
+ throw error;
1377
+ }
1378
+ }
1379
+ if (doesUseLockedH2Database) {
1380
+ const dCompleted = new Deferred.Deferred();
1381
+ const cmd = `docker exec ${constants/* CONTAINER_NAME */.sv} sh -c "rm -rf /tmp/h2"`;
1382
+ external_child_process_default().exec(cmd, error => {
1383
+ if (error !== null) {
1384
+ dCompleted.reject(error);
1385
+ return;
1386
+ }
1387
+ dCompleted.resolve();
1388
+ });
1389
+ try {
1390
+ await dCompleted.pr;
1391
+ }
1392
+ catch (error) {
1393
+ (0,assert/* assert */.h)((0,assert.is)(error));
1394
+ console.log(source_default().red(`Docker command failed: ${cmd}`));
1395
+ console.log(source_default().red(error.message));
1396
+ throw error;
1397
+ }
1398
+ }
1399
+ const targetRealmConfigJsonFilePath_tmp = (0,external_path_.join)(buildContext.cacheDirPath, "realm.json");
1400
+ {
1401
+ const dCompleted = new Deferred.Deferred();
1402
+ const cmd = `docker cp ${constants/* CONTAINER_NAME */.sv}:/tmp/${realmName}-realm.json ${(0,external_path_.basename)(targetRealmConfigJsonFilePath_tmp)}`;
1403
+ external_child_process_default().exec(cmd, {
1404
+ cwd: (0,external_path_.dirname)(targetRealmConfigJsonFilePath_tmp)
1405
+ }, error => {
1406
+ if (error !== null) {
1407
+ dCompleted.reject(error);
1408
+ return;
1409
+ }
1410
+ dCompleted.resolve();
1411
+ });
1412
+ try {
1413
+ await dCompleted.pr;
1414
+ }
1415
+ catch (error) {
1416
+ (0,assert/* assert */.h)((0,assert.is)(error));
1417
+ console.log(source_default().red(`Docker command failed: ${cmd}`));
1418
+ console.log(source_default().red(error.message));
1419
+ throw error;
1420
+ }
1421
+ }
1422
+ return readRealmJsonFile({
1423
+ realmJsonFilePath: targetRealmConfigJsonFilePath_tmp
1424
+ });
1425
+ }
1426
+ //# sourceMappingURL=dumpContainerConfig.js.map
1427
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/realmConfig/realmConfig.js
1428
+
1429
+
1430
+
1431
+
1432
+
1433
+
1434
+
1435
+
1436
+
1437
+
1438
+
1439
+ assert/* assert */.h;
1440
+ async function getRealmConfig(params) {
1441
+ const { keycloakMajorVersionNumber, realmJsonFilePath_userProvided, parsedKeycloakThemesJsonEntry, buildContext } = params;
1442
+ const realmJsonFilePath = (0,external_path_.join)(buildContext.projectDirPath, ".keycloakify", `realm-kc-${keycloakMajorVersionNumber}.json`);
1443
+ const parsedRealmJson = await (async () => {
1444
+ if (realmJsonFilePath_userProvided !== undefined) {
1445
+ return readRealmJsonFile({
1446
+ realmJsonFilePath: realmJsonFilePath_userProvided
1447
+ });
1448
+ }
1449
+ if (await (0,fs_existsAsync/* existsAsync */.o)(realmJsonFilePath)) {
1450
+ return readRealmJsonFile({
1451
+ realmJsonFilePath
1452
+ });
1453
+ }
1454
+ return getDefaultConfig({ keycloakMajorVersionNumber });
1455
+ })();
1456
+ const { clientName, realmName, username } = prepareRealmConfig({
1457
+ parsedRealmJson,
1458
+ keycloakMajorVersionNumber,
1459
+ parsedKeycloakThemesJsonEntry
1460
+ });
1461
+ {
1462
+ const dirPath = (0,external_path_.dirname)(realmJsonFilePath);
1463
+ if (!(await (0,fs_existsAsync/* existsAsync */.o)(dirPath))) {
1464
+ external_fs_.mkdirSync(dirPath, { recursive: true });
1465
+ }
1466
+ }
1467
+ await writeRealmJsonFile({
1468
+ realmJsonFilePath,
1469
+ parsedRealmJson,
1470
+ keycloakMajorVersionNumber
1471
+ });
1472
+ const { onRealmConfigChange } = (() => {
1473
+ const run = runExclusive.build(async () => {
1474
+ const start = Date.now();
1475
+ console.log(source_default().grey(`Changes detected to the '${realmName}' config, backing up...`));
1476
+ let parsedRealmJson;
1477
+ try {
1478
+ parsedRealmJson = await dumpContainerConfig({
1479
+ buildContext,
1480
+ realmName,
1481
+ keycloakMajorVersionNumber
1482
+ });
1483
+ }
1484
+ catch (error) {
1485
+ console.log(source_default().red(`Failed to backup '${realmName}' config:`));
1486
+ return;
1487
+ }
1488
+ await writeRealmJsonFile({
1489
+ realmJsonFilePath,
1490
+ parsedRealmJson,
1491
+ keycloakMajorVersionNumber
1492
+ });
1493
+ console.log([
1494
+ source_default().grey(`Save changed to \`.${external_path_.sep}${(0,external_path_.relative)(buildContext.projectDirPath, realmJsonFilePath)}\``),
1495
+ source_default().grey(`Next time you'll be running \`keycloakify start-keycloak\`, the realm '${realmName}' will be restored to this state.`),
1496
+ source_default().green(`✓ '${realmName}' config backed up completed in ${Date.now() - start}ms`)
1497
+ ].join("\n"));
1498
+ });
1499
+ const { waitForDebounce } = (0,tools_waitForDebounce/* waitForDebounceFactory */.z)({
1500
+ delay: 1000
1501
+ });
1502
+ async function onRealmConfigChange() {
1503
+ await waitForDebounce();
1504
+ run();
1505
+ }
1506
+ return { onRealmConfigChange };
1507
+ })();
1508
+ return {
1509
+ realmJsonFilePath,
1510
+ clientName,
1511
+ realmName,
1512
+ username,
1513
+ onRealmConfigChange
1514
+ };
1515
+ }
1516
+ //# sourceMappingURL=realmConfig.js.map
1517
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/realmConfig/index.js
1518
+
1519
+ //# sourceMappingURL=index.js.map
1520
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/start-keycloak.js
1521
+
1522
+
1523
+
1524
+
1525
+
1526
+
1527
+
1528
+
1529
+
1530
+
1531
+
1532
+
1533
+
1534
+
1535
+
1536
+
1537
+
1538
+
1539
+
1540
+
1541
+
1542
+
1543
+
1544
+
1545
+
1546
+
1547
+ async function command(params) {
1548
+ var _a, _b, _c, _d, _e;
1549
+ exit_if_docker_not_installed: {
1550
+ let commandOutput = undefined;
1551
+ try {
1552
+ commandOutput = (_a = external_child_process_.execSync("docker --version", {
1553
+ stdio: ["ignore", "pipe", "ignore"]
1554
+ })) === null || _a === void 0 ? void 0 : _a.toString("utf8");
1555
+ }
1556
+ catch (_f) { }
1557
+ if ((commandOutput === null || commandOutput === void 0 ? void 0 : commandOutput.includes("Docker")) || (commandOutput === null || commandOutput === void 0 ? void 0 : commandOutput.includes("podman"))) {
1558
+ break exit_if_docker_not_installed;
1559
+ }
1560
+ console.log([
1561
+ `${source_default().red("Docker required.")}`,
1562
+ `Install it with Docker Desktop: ${source_default().bold.underline("https://www.docker.com/products/docker-desktop/")}`,
1563
+ `(or any other way)`
1564
+ ].join(" "));
1565
+ process.exit(1);
1566
+ }
1567
+ exit_if_docker_not_running: {
1568
+ let isDockerRunning;
1569
+ try {
1570
+ external_child_process_.execSync("docker info", { stdio: "ignore" });
1571
+ isDockerRunning = true;
1572
+ }
1573
+ catch (_g) {
1574
+ isDockerRunning = false;
1575
+ }
1576
+ if (isDockerRunning) {
1577
+ break exit_if_docker_not_running;
1578
+ }
1579
+ console.log([
1580
+ `${source_default().red("Docker daemon is not running.")}`,
1581
+ `Please start Docker Desktop and try again.`
1582
+ ].join(" "));
1583
+ process.exit(1);
1584
+ }
1585
+ const { cliCommandOptions, buildContext } = params;
1586
+ const { allSupportedTags, latestMajorTags } = await getSupportedDockerImageTags({
43
1587
  buildContext
44
1588
  });
45
- if (hasBeenHandled) {
46
- return;
47
- }
48
- console.log(chalk__WEBPACK_IMPORTED_MODULE_6___default().cyan("Theme type:"));
49
- const themeType = await (async () => {
50
- const values = _shared_constants__WEBPACK_IMPORTED_MODULE_2__/* .THEME_TYPES.filter */ .Jh.filter(themeType => {
51
- switch (themeType) {
52
- case "account":
53
- return buildContext.implementedThemeTypes.account.isImplemented;
54
- case "login":
55
- return buildContext.implementedThemeTypes.login.isImplemented;
56
- case "admin":
57
- return buildContext.implementedThemeTypes.admin.isImplemented;
58
- }
59
- (0,tsafe_assert__WEBPACK_IMPORTED_MODULE_5__/* .assert */ .h)(false);
60
- });
61
- (0,tsafe_assert__WEBPACK_IMPORTED_MODULE_5__/* .assert */ .h)(values.length > 0, "No theme is implemented in this project");
62
- if (values.length === 1) {
63
- return values[0];
64
- }
65
- const { value } = await cli_select__WEBPACK_IMPORTED_MODULE_1___default()({
66
- values
67
- }).catch(() => {
68
- process.exit(-1);
69
- });
70
- return value;
1589
+ const { dockerImageTag } = await (async () => {
1590
+ if (cliCommandOptions.keycloakVersion !== undefined) {
1591
+ const cliCommandOptions_keycloakVersion = cliCommandOptions.keycloakVersion;
1592
+ const tag = allSupportedTags.find(tag => tag.startsWith(cliCommandOptions_keycloakVersion));
1593
+ if (tag === undefined) {
1594
+ console.log(source_default().red([
1595
+ `We could not find a Keycloak Docker image for ${cliCommandOptions_keycloakVersion}`,
1596
+ `Example of valid values: --keycloak-version 26, --keycloak-version 26.0.7`
1597
+ ].join("\n")));
1598
+ process.exit(1);
1599
+ }
1600
+ return { dockerImageTag: tag };
1601
+ }
1602
+ if (buildContext.startKeycloakOptions.dockerImage !== undefined) {
1603
+ return {
1604
+ dockerImageTag: buildContext.startKeycloakOptions.dockerImage.tag
1605
+ };
1606
+ }
1607
+ console.log([
1608
+ source_default().cyan("On which version of Keycloak do you want to test your theme?"),
1609
+ source_default().gray("You can also explicitly provide the version with `npx keycloakify start-keycloak --keycloak-version 26` (or any other version)")
1610
+ ].join("\n"));
1611
+ const tag_userSelected = await (async () => {
1612
+ let tag;
1613
+ let latestMajorTags_copy = [...latestMajorTags];
1614
+ while (true) {
1615
+ const { value } = await dist_default()({
1616
+ values: latestMajorTags_copy
1617
+ }).catch(() => {
1618
+ process.exit(-1);
1619
+ });
1620
+ tag = value;
1621
+ {
1622
+ const doImplementAccountMpa = buildContext.implementedThemeTypes.account.isImplemented &&
1623
+ buildContext.implementedThemeTypes.account.type === "Multi-Page";
1624
+ if (doImplementAccountMpa && tag.startsWith("22.")) {
1625
+ console.log(source_default().yellow(`You are implementing a Multi-Page Account theme. Keycloak 22 is not supported, select another version`));
1626
+ latestMajorTags_copy = latestMajorTags_copy.filter(tag => !tag.startsWith("22."));
1627
+ continue;
1628
+ }
1629
+ }
1630
+ const readMajor = (tag) => {
1631
+ const major = parseInt(tag.split(".")[0]);
1632
+ (0,assert/* assert */.h)(!isNaN(major));
1633
+ return major;
1634
+ };
1635
+ {
1636
+ const major = readMajor(tag);
1637
+ const doImplementAdminTheme = buildContext.implementedThemeTypes.admin.isImplemented;
1638
+ const getIsSupported = (major) => major >= 23;
1639
+ if (doImplementAdminTheme && !getIsSupported(major)) {
1640
+ console.log(source_default().yellow(`You are implementing an Admin theme. Only Keycloak 23 and later are supported, select another version`));
1641
+ latestMajorTags_copy = latestMajorTags_copy.filter(tag => getIsSupported(readMajor(tag)));
1642
+ continue;
1643
+ }
1644
+ }
1645
+ {
1646
+ const doImplementAccountSpa = buildContext.implementedThemeTypes.account.isImplemented &&
1647
+ buildContext.implementedThemeTypes.account.type === "Single-Page";
1648
+ const major = readMajor(tag);
1649
+ const getIsSupported = (major) => major >= 19;
1650
+ if (doImplementAccountSpa && !getIsSupported(major)) {
1651
+ console.log(source_default().yellow(`You are implementing a Single-Page Account theme. Only Keycloak 19 and later are supported, select another version`));
1652
+ latestMajorTags_copy = latestMajorTags_copy.filter(tag => getIsSupported(readMajor(tag)));
1653
+ continue;
1654
+ }
1655
+ }
1656
+ break;
1657
+ }
1658
+ return tag;
1659
+ })();
1660
+ console.log(`→ ${tag_userSelected}`);
1661
+ return { dockerImageTag: tag_userSelected };
71
1662
  })();
72
- if (themeType === "account" &&
73
- ((0,tsafe_assert__WEBPACK_IMPORTED_MODULE_5__/* .assert */ .h)(buildContext.implementedThemeTypes.account.isImplemented),
74
- buildContext.implementedThemeTypes.account.type === "Single-Page")) {
75
- console.log(`${chalk__WEBPACK_IMPORTED_MODULE_6___default().red("✗")} Sorry, there is no Storybook support for Single-Page Account themes.`);
76
- process.exit(0);
77
- return;
1663
+ const keycloakMajorVersionNumber = (() => {
1664
+ const [wrap] = getSupportedKeycloakMajorVersions()
1665
+ .map(majorVersionNumber => ({
1666
+ majorVersionNumber,
1667
+ index: dockerImageTag.indexOf(`${majorVersionNumber}`)
1668
+ }))
1669
+ .filter(({ index }) => index !== -1)
1670
+ .sort((a, b) => a.index - b.index);
1671
+ if (wrap === undefined) {
1672
+ try {
1673
+ const version = SemVer/* SemVer.parse */.h.parse(dockerImageTag);
1674
+ console.error(source_default().yellow(`Keycloak version ${version.major} is not supported, supported versions are ${getSupportedKeycloakMajorVersions().join(", ")}`));
1675
+ process.exit(1);
1676
+ }
1677
+ catch (_a) {
1678
+ // NOTE: Latest version
1679
+ const [n] = getSupportedKeycloakMajorVersions();
1680
+ console.warn(source_default().yellow(`Could not determine the major Keycloak version number from the docker image tag ${dockerImageTag}. Assuming ${n}`));
1681
+ return n;
1682
+ }
1683
+ }
1684
+ return wrap.majorVersionNumber;
1685
+ })();
1686
+ {
1687
+ const { isAppBuildSuccess } = await appBuild({
1688
+ buildContext
1689
+ });
1690
+ if (!isAppBuildSuccess) {
1691
+ console.log(source_default().red(`App build failed, exiting. Try building your app (e.g 'npm run build') and see what's wrong.`));
1692
+ process.exit(1);
1693
+ }
1694
+ const { isKeycloakifyBuildSuccess } = await keycloakifyBuild({
1695
+ buildForKeycloakMajorVersionNumber: keycloakMajorVersionNumber,
1696
+ buildContext
1697
+ });
1698
+ if (!isKeycloakifyBuildSuccess) {
1699
+ console.log(source_default().red(`Keycloakify build failed, exiting. Try running 'npx keycloakify build' and see what's wrong.`));
1700
+ process.exit(1);
1701
+ }
78
1702
  }
79
- if (themeType === "admin") {
80
- console.log(`${chalk__WEBPACK_IMPORTED_MODULE_6___default().red("")} Sorry, there is no Storybook support for the Account UI.`);
81
- process.exit(0);
82
- return;
1703
+ const jarFilePath = external_fs_.readdirSync(buildContext.keycloakifyBuildDirPath)
1704
+ .filter(fileBasename => fileBasename.endsWith(".jar"))
1705
+ .map(fileBasename => (0,external_path_.join)(buildContext.keycloakifyBuildDirPath, fileBasename))
1706
+ .sort((a, b) => external_fs_.statSync(b).mtimeMs - external_fs_.statSync(a).mtimeMs)[0];
1707
+ (0,assert/* assert */.h)(jarFilePath !== undefined);
1708
+ const extensionJarFilePaths = [
1709
+ ...(keycloakMajorVersionNumber <= 20
1710
+ ? (console.log(source_default().yellow("WARNING: With older version of keycloak your changes to the realm configuration are not persisted")),
1711
+ [])
1712
+ : [
1713
+ (0,external_path_.join)((0,getThisCodebaseRootDirPath/* getThisCodebaseRootDirPath */.e)(), "src", "bin", "start-keycloak", constants/* KEYCLOAKIFY_LOGIN_JAR_BASENAME */.Tr)
1714
+ ]),
1715
+ ...(await Promise.all(buildContext.startKeycloakOptions.extensionJars.map(async (extensionJar) => {
1716
+ switch (extensionJar.type) {
1717
+ case "path": {
1718
+ (0,assert/* assert */.h)(await (0,fs_existsAsync/* existsAsync */.o)(extensionJar.path), `${extensionJar.path} does not exist`);
1719
+ return extensionJar.path;
1720
+ }
1721
+ case "url": {
1722
+ const { archiveFilePath } = await downloadAndExtractArchive({
1723
+ cacheDirPath: buildContext.cacheDirPath,
1724
+ fetchOptions: buildContext.fetchOptions,
1725
+ url: extensionJar.url,
1726
+ uniqueIdOfOnArchiveFile: "no extraction",
1727
+ onArchiveFile: async () => { }
1728
+ });
1729
+ return archiveFilePath;
1730
+ }
1731
+ }
1732
+ (0,assert/* assert */.h)(false);
1733
+ })))
1734
+ ];
1735
+ let parsedKeycloakThemesJson = (0,id.id)(undefined);
1736
+ async function extractThemeResourcesFromJar() {
1737
+ await extractArchive({
1738
+ archiveFilePath: jarFilePath,
1739
+ onArchiveFile: async ({ relativeFilePathInArchive, writeFile, readFile }) => {
1740
+ if (relativeFilePathInArchive ===
1741
+ (0,external_path_.join)("META-INF", "keycloak-themes.json") &&
1742
+ parsedKeycloakThemesJson === undefined) {
1743
+ parsedKeycloakThemesJson = JSON.parse((await readFile()).toString("utf8"));
1744
+ }
1745
+ if ((0,isInside/* isInside */.V)({ dirPath: "theme", filePath: relativeFilePathInArchive })) {
1746
+ await writeFile({
1747
+ filePath: (0,external_path_.join)(buildContext.keycloakifyBuildDirPath, relativeFilePathInArchive)
1748
+ });
1749
+ }
1750
+ }
1751
+ });
83
1752
  }
84
- console.log(`→ ${themeType}`);
85
- console.log(chalk__WEBPACK_IMPORTED_MODULE_6___default().cyan("Select the page you want to create a Storybook for:"));
86
- const { value: pageId } = await cli_select__WEBPACK_IMPORTED_MODULE_1___default()({
87
- values: (() => {
88
- switch (themeType) {
89
- case "login":
90
- return [..._shared_constants__WEBPACK_IMPORTED_MODULE_2__/* .LOGIN_THEME_PAGE_IDS */ .XV];
91
- case "account":
92
- return [..._shared_constants__WEBPACK_IMPORTED_MODULE_2__/* .ACCOUNT_THEME_PAGE_IDS */ .yV];
93
- }
94
- (0,tsafe_assert__WEBPACK_IMPORTED_MODULE_5__/* .assert */ .h)(false);
95
- })()
96
- }).catch(() => {
97
- process.exit(-1);
1753
+ {
1754
+ const destDirPath = (0,external_path_.join)(buildContext.keycloakifyBuildDirPath, "theme");
1755
+ if (await (0,fs_existsAsync/* existsAsync */.o)(destDirPath)) {
1756
+ await rm(destDirPath, { recursive: true });
1757
+ }
1758
+ }
1759
+ await extractThemeResourcesFromJar();
1760
+ (0,assert/* assert */.h)(parsedKeycloakThemesJson !== undefined);
1761
+ const { clientName, onRealmConfigChange, realmJsonFilePath, realmName, username } = await getRealmConfig({
1762
+ keycloakMajorVersionNumber,
1763
+ parsedKeycloakThemesJsonEntry: (() => {
1764
+ const entry = parsedKeycloakThemesJson.themes.find(({ name }) => name === buildContext.themeNames[0]);
1765
+ (0,assert/* assert */.h)(entry !== undefined);
1766
+ return entry;
1767
+ })(),
1768
+ realmJsonFilePath_userProvided: await (async () => {
1769
+ if (cliCommandOptions.realmJsonFilePath !== undefined) {
1770
+ return (0,getAbsoluteAndInOsFormatPath/* getAbsoluteAndInOsFormatPath */.c)({
1771
+ pathIsh: cliCommandOptions.realmJsonFilePath,
1772
+ cwd: process.cwd()
1773
+ });
1774
+ }
1775
+ if (buildContext.startKeycloakOptions.realmJsonFilePath !== undefined) {
1776
+ (0,assert/* assert */.h)(await (0,fs_existsAsync/* existsAsync */.o)(buildContext.startKeycloakOptions.realmJsonFilePath), `${(0,external_path_.relative)(process.cwd(), buildContext.startKeycloakOptions.realmJsonFilePath)} does not exist`);
1777
+ return buildContext.startKeycloakOptions.realmJsonFilePath;
1778
+ }
1779
+ return undefined;
1780
+ })(),
1781
+ buildContext
98
1782
  });
99
- console.log(`→ ${pageId}`);
100
- const componentBasename = (0,tsafe_capitalize__WEBPACK_IMPORTED_MODULE_9__/* .capitalize */ .k)((0,_tools_kebabCaseToSnakeCase__WEBPACK_IMPORTED_MODULE_10__/* .kebabCaseToCamelCase */ .A)(pageId)).replace(/ftl$/, "stories.tsx");
101
- const targetFilePath = (0,path__WEBPACK_IMPORTED_MODULE_4__.join)(buildContext.themeSrcDirPath, themeType, "pages", componentBasename);
102
- if (fs__WEBPACK_IMPORTED_MODULE_3__.existsSync(targetFilePath)) {
103
- console.log(`${(0,path__WEBPACK_IMPORTED_MODULE_4__.relative)(process.cwd(), targetFilePath)} already exists`);
104
- process.exit(-1);
1783
+ const jarFilePath_cacheDir = (0,external_path_.join)(buildContext.cacheDirPath, (0,external_path_.basename)(jarFilePath));
1784
+ external_fs_.copyFileSync(jarFilePath, jarFilePath_cacheDir);
1785
+ try {
1786
+ external_child_process_.execSync(`docker rm --force ${constants/* CONTAINER_NAME */.sv}`, {
1787
+ stdio: "ignore"
1788
+ });
105
1789
  }
106
- let sourceCode = fs__WEBPACK_IMPORTED_MODULE_3__.readFileSync((0,path__WEBPACK_IMPORTED_MODULE_4__.join)((0,_tools_getThisCodebaseRootDirPath__WEBPACK_IMPORTED_MODULE_0__/* .getThisCodebaseRootDirPath */ .e)(), "stories", themeType, "pages", componentBasename))
107
- .toString("utf8")
108
- .replace('import React from "react";\n', "")
109
- .replace(/from "[./]+dist\//, 'from "keycloakify/');
110
- run_prettier: {
111
- if (!(await (0,_tools_runPrettier__WEBPACK_IMPORTED_MODULE_7__/* .getIsPrettierAvailable */ .MT)())) {
112
- break run_prettier;
1790
+ catch (_h) { }
1791
+ const port = (_c = (_b = cliCommandOptions.port) !== null && _b !== void 0 ? _b : buildContext.startKeycloakOptions.port) !== null && _c !== void 0 ? _c : 8080;
1792
+ const doStartDevServer = (() => {
1793
+ const hasSpaUi = buildContext.implementedThemeTypes.admin.isImplemented ||
1794
+ (buildContext.implementedThemeTypes.account.isImplemented &&
1795
+ buildContext.implementedThemeTypes.account.type === "Single-Page");
1796
+ if (!hasSpaUi) {
1797
+ return false;
113
1798
  }
114
- sourceCode = await (0,_tools_runPrettier__WEBPACK_IMPORTED_MODULE_7__/* .runPrettier */ .eY)({
115
- filePath: targetFilePath,
116
- sourceCode: sourceCode
117
- });
1799
+ if (buildContext.bundler !== "vite") {
1800
+ console.log(source_default().yellow([
1801
+ `WARNING: Since you are using ${buildContext.bundler} instead of Vite,`,
1802
+ `you'll have to wait serval seconds for the changes you made on your account or admin theme to be reflected in the browser.\n`,
1803
+ `For a better development experience, consider migrating to Vite.`
1804
+ ].join(" ")));
1805
+ return false;
1806
+ }
1807
+ if (keycloakMajorVersionNumber < 25) {
1808
+ console.log(source_default().yellow([
1809
+ `WARNING: Your account or admin theme can't be tested with hot module replacement on Keycloak ${keycloakMajorVersionNumber}.`,
1810
+ `This mean that you'll have to wait serval seconds for the changes to be reflected in the browser.`,
1811
+ `For a better development experience, select a more recent version of Keycloak.`
1812
+ ].join("\n")));
1813
+ return false;
1814
+ }
1815
+ return true;
1816
+ })();
1817
+ let devServerPort = undefined;
1818
+ if (doStartDevServer) {
1819
+ const { port } = await startViteDevServer({ buildContext });
1820
+ devServerPort = port;
118
1821
  }
119
- {
120
- const targetDirPath = (0,path__WEBPACK_IMPORTED_MODULE_4__.dirname)(targetFilePath);
121
- if (!fs__WEBPACK_IMPORTED_MODULE_3__.existsSync(targetDirPath)) {
122
- fs__WEBPACK_IMPORTED_MODULE_3__.mkdirSync(targetDirPath, { recursive: true });
1822
+ const SPACE_PLACEHOLDER = "SPACE_PLACEHOLDER_xKLmdPd";
1823
+ const dockerRunArgs = [
1824
+ `-p${SPACE_PLACEHOLDER}${port}:8080`,
1825
+ `--name${SPACE_PLACEHOLDER}${constants/* CONTAINER_NAME */.sv}`,
1826
+ ...(keycloakMajorVersionNumber >= 26
1827
+ ? [
1828
+ `-e${SPACE_PLACEHOLDER}KC_BOOTSTRAP_ADMIN_USERNAME=admin`,
1829
+ `-e${SPACE_PLACEHOLDER}KC_BOOTSTRAP_ADMIN_PASSWORD=admin`
1830
+ ]
1831
+ : [
1832
+ `-e${SPACE_PLACEHOLDER}KEYCLOAK_ADMIN=admin`,
1833
+ `-e${SPACE_PLACEHOLDER}KEYCLOAK_ADMIN_PASSWORD=admin`
1834
+ ]),
1835
+ ...(devServerPort === undefined
1836
+ ? []
1837
+ : [
1838
+ `-e${SPACE_PLACEHOLDER}${constants/* KEYCLOAKIFY_SPA_DEV_SERVER_PORT */.Sz}=${devServerPort}`
1839
+ ]),
1840
+ ...(buildContext.startKeycloakOptions.dockerExtraArgs.length === 0
1841
+ ? []
1842
+ : [
1843
+ buildContext.startKeycloakOptions.dockerExtraArgs.join(SPACE_PLACEHOLDER)
1844
+ ]),
1845
+ ...(realmJsonFilePath === undefined
1846
+ ? []
1847
+ : [
1848
+ `-v${SPACE_PLACEHOLDER}"${realmJsonFilePath}":/opt/keycloak/data/import/${realmName}-realm.json`
1849
+ ]),
1850
+ `-v${SPACE_PLACEHOLDER}"${jarFilePath_cacheDir}":/opt/keycloak/providers/keycloak-theme.jar`,
1851
+ ...extensionJarFilePaths.map(jarFilePath => `-v${SPACE_PLACEHOLDER}"${jarFilePath}":/opt/keycloak/providers/${(0,external_path_.basename)(jarFilePath)}`),
1852
+ ...(keycloakMajorVersionNumber <= 20
1853
+ ? [`-e${SPACE_PLACEHOLDER}JAVA_OPTS=-Dkeycloak.profile=preview`]
1854
+ : []),
1855
+ ...[
1856
+ ...buildContext.themeNames,
1857
+ ...(external_fs_.existsSync((0,external_path_.join)(buildContext.keycloakifyBuildDirPath, "theme", "account-v1"))
1858
+ ? ["account-v1"]
1859
+ : [])
1860
+ ]
1861
+ .map(themeName => ({
1862
+ localDirPath: (0,external_path_.join)(buildContext.keycloakifyBuildDirPath, "theme", themeName),
1863
+ containerDirPath: `/opt/keycloak/themes/${themeName}`
1864
+ }))
1865
+ .map(({ localDirPath, containerDirPath }) => `-v${SPACE_PLACEHOLDER}"${localDirPath}":${containerDirPath}:rw`),
1866
+ ...buildContext.environmentVariables
1867
+ .map(({ name }) => ({ name, envValue: process.env[name] }))
1868
+ .map(({ name, envValue }) => envValue === undefined ? undefined : { name, envValue })
1869
+ .filter((0,exclude/* exclude */.D)(undefined))
1870
+ .map(({ name, envValue }) => `--env${SPACE_PLACEHOLDER}${name}='${envValue.replace(/'/g, "'\\''")}'`),
1871
+ `${(_e = (_d = buildContext.startKeycloakOptions.dockerImage) === null || _d === void 0 ? void 0 : _d.reference) !== null && _e !== void 0 ? _e : "quay.io/keycloak/keycloak"}:${dockerImageTag}`,
1872
+ "start-dev",
1873
+ ...(21 <= keycloakMajorVersionNumber && keycloakMajorVersionNumber < 24
1874
+ ? ["--features=declarative-user-profile"]
1875
+ : []),
1876
+ ...(realmJsonFilePath === undefined ? [] : ["--import-realm"]),
1877
+ ...(buildContext.startKeycloakOptions.keycloakExtraArgs.length === 0
1878
+ ? []
1879
+ : [
1880
+ buildContext.startKeycloakOptions.keycloakExtraArgs.join(SPACE_PLACEHOLDER)
1881
+ ])
1882
+ ];
1883
+ console.log(source_default().blue([
1884
+ `$ docker run \\`,
1885
+ ...dockerRunArgs
1886
+ .map(arg => arg.replace(new RegExp(SPACE_PLACEHOLDER, "g"), " "))
1887
+ .map((line, i, arr) => ` ${line}${arr.length - 1 === i ? "" : " \\"}`)
1888
+ ].join("\n")));
1889
+ const child = external_child_process_.spawn("docker", ["run", ...dockerRunArgs.map(line => line.split(SPACE_PLACEHOLDER)).flat()], { shell: true });
1890
+ child.stdout.on("data", async (data) => {
1891
+ if (data.toString("utf8").includes("keycloakify-logging: REALM_CONFIG_CHANGED")) {
1892
+ await onRealmConfigChange();
1893
+ return;
123
1894
  }
1895
+ process.stdout.write(data);
1896
+ });
1897
+ child.stderr.on("data", data => process.stderr.write(data));
1898
+ child.on("exit", process.exit);
1899
+ const srcDirPath = (0,external_path_.join)(buildContext.projectDirPath, "src");
1900
+ {
1901
+ const kcHttpRelativePath = (() => {
1902
+ const match = buildContext.startKeycloakOptions.dockerExtraArgs
1903
+ .join(" ")
1904
+ .match(/KC_HTTP_RELATIVE_PATH=([^ ]+)/);
1905
+ if (match === null) {
1906
+ return undefined;
1907
+ }
1908
+ return match[1];
1909
+ })();
1910
+ const handler = async (data) => {
1911
+ if (!data.toString("utf8").includes("Listening on: http://0.0.0.0:8080")) {
1912
+ return;
1913
+ }
1914
+ child.stdout.off("data", handler);
1915
+ await new Promise(resolve => setTimeout(resolve, 1000));
1916
+ console.log([
1917
+ "",
1918
+ `The ftl files from ${source_default().bold(`.${external_path_.sep}${(0,external_path_.relative)(process.cwd(), (0,external_path_.join)(buildContext.keycloakifyBuildDirPath, "theme"))}`)} are mounted in the Keycloak container.`,
1919
+ "",
1920
+ `Keycloak Admin console: ${source_default().cyan.bold(`http://localhost:${port}${kcHttpRelativePath !== null && kcHttpRelativePath !== void 0 ? kcHttpRelativePath : ""}`)}`,
1921
+ `- user: ${source_default().cyan.bold("admin")}`,
1922
+ `- password: ${source_default().cyan.bold("admin")}`,
1923
+ "",
1924
+ "",
1925
+ `${source_default().green("Your theme is accessible at:")}`,
1926
+ `${source_default().green("➜")} ${source_default().cyan.bold((() => {
1927
+ const url = new URL(constants/* TEST_APP_URL */.jp);
1928
+ if (port !== 8080) {
1929
+ url.searchParams.set("port", `${port}`);
1930
+ }
1931
+ if (kcHttpRelativePath !== undefined) {
1932
+ url.searchParams.set("kcHttpRelativePath", kcHttpRelativePath);
1933
+ }
1934
+ if (realmName !== "myrealm") {
1935
+ url.searchParams.set("realm", realmName);
1936
+ }
1937
+ if (clientName !== "myclient") {
1938
+ url.searchParams.set("client", clientName);
1939
+ }
1940
+ return url.href;
1941
+ })())}`,
1942
+ "",
1943
+ "You can login with the following credentials:",
1944
+ `- username: ${source_default().cyan.bold(username)}`,
1945
+ `- password: ${source_default().cyan.bold("password123")}`,
1946
+ "",
1947
+ `Watching for changes in ${source_default().bold(`.${external_path_.sep}${(0,external_path_.relative)(process.cwd(), buildContext.projectDirPath)}`)}`
1948
+ ].join("\n"));
1949
+ };
1950
+ child.stdout.on("data", handler);
1951
+ }
1952
+ {
1953
+ const runFullBuild = runExclusive.build(async () => {
1954
+ console.log(source_default().cyan("Detected changes in the theme. Rebuilding ..."));
1955
+ const { isAppBuildSuccess } = await appBuild({
1956
+ buildContext
1957
+ });
1958
+ if (!isAppBuildSuccess) {
1959
+ return;
1960
+ }
1961
+ const { isKeycloakifyBuildSuccess } = await keycloakifyBuild({
1962
+ buildForKeycloakMajorVersionNumber: keycloakMajorVersionNumber,
1963
+ buildContext
1964
+ });
1965
+ if (!isKeycloakifyBuildSuccess) {
1966
+ return;
1967
+ }
1968
+ await extractThemeResourcesFromJar();
1969
+ console.log(source_default().green("Theme rebuilt and updated in Keycloak."));
1970
+ });
1971
+ const { waitForDebounce } = (0,tools_waitForDebounce/* waitForDebounceFactory */.z)({ delay: 400 });
1972
+ chokidar.watch([
1973
+ srcDirPath,
1974
+ buildContext.publicDirPath,
1975
+ (0,external_path_.join)(buildContext.projectDirPath, "package.json"),
1976
+ (0,external_path_.join)(buildContext.projectDirPath, "vite.config.ts"),
1977
+ (0,external_path_.join)(buildContext.projectDirPath, "vite.config.js"),
1978
+ (0,external_path_.join)(buildContext.projectDirPath, "index.html"),
1979
+ (0,external_path_.join)((0,getThisCodebaseRootDirPath/* getThisCodebaseRootDirPath */.e)(), "src")
1980
+ ], {
1981
+ ignoreInitial: true
1982
+ })
1983
+ .on("all", async (...[, filePath]) => {
1984
+ ignore_path_covered_by_hmr: {
1985
+ if (filePath.endsWith(".properties")) {
1986
+ break ignore_path_covered_by_hmr;
1987
+ }
1988
+ if (!doStartDevServer) {
1989
+ break ignore_path_covered_by_hmr;
1990
+ }
1991
+ ignore_account_spa: {
1992
+ const doImplementAccountSpa = buildContext.implementedThemeTypes.account.isImplemented &&
1993
+ buildContext.implementedThemeTypes.account.type ===
1994
+ "Single-Page";
1995
+ if (!doImplementAccountSpa) {
1996
+ break ignore_account_spa;
1997
+ }
1998
+ if (!(0,isInside/* isInside */.V)({
1999
+ dirPath: (0,external_path_.join)(buildContext.themeSrcDirPath, "account"),
2000
+ filePath
2001
+ })) {
2002
+ break ignore_account_spa;
2003
+ }
2004
+ return;
2005
+ }
2006
+ ignore_admin: {
2007
+ if (!buildContext.implementedThemeTypes.admin.isImplemented) {
2008
+ break ignore_admin;
2009
+ }
2010
+ if (!(0,isInside/* isInside */.V)({
2011
+ dirPath: (0,external_path_.join)(buildContext.themeSrcDirPath, "admin"),
2012
+ filePath
2013
+ })) {
2014
+ break ignore_admin;
2015
+ }
2016
+ return;
2017
+ }
2018
+ }
2019
+ console.log(`Detected changes in ${filePath}`);
2020
+ await waitForDebounce();
2021
+ runFullBuild();
2022
+ });
124
2023
  }
125
- fs__WEBPACK_IMPORTED_MODULE_3__.writeFileSync(targetFilePath, Buffer.from(sourceCode, "utf8"));
126
- console.log([
127
- `${chalk__WEBPACK_IMPORTED_MODULE_6___default().green("✓")} ${chalk__WEBPACK_IMPORTED_MODULE_6___default().bold((0,path__WEBPACK_IMPORTED_MODULE_4__.join)(".", (0,path__WEBPACK_IMPORTED_MODULE_4__.relative)(process.cwd(), targetFilePath)))} copy pasted from the Keycloakify source code into your project`,
128
- `You can start storybook with ${chalk__WEBPACK_IMPORTED_MODULE_6___default().bold("npm run storybook")}`
129
- ].join("\n"));
130
2024
  }
131
- //# sourceMappingURL=add-story.js.map
2025
+ //# sourceMappingURL=start-keycloak.js.map
2026
+ ;// CONCATENATED MODULE: ./dist/bin/start-keycloak/index.js
2027
+
2028
+ //# sourceMappingURL=index.js.map
132
2029
 
133
2030
  /***/ }),
134
2031
 
135
- /***/ 72138:
2032
+ /***/ 12171:
136
2033
  /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
137
2034
 
2035
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2036
+ /* harmony export */ "h": () => (/* binding */ SemVer)
2037
+ /* harmony export */ });
2038
+ var SemVer;
2039
+ (function (SemVer) {
2040
+ const bumpTypes = ["major", "minor", "patch", "rc", "no bump"];
2041
+ function parse(versionStr) {
2042
+ const match = versionStr.match(/^v?([0-9]+)\.([0-9]+)(?:\.([0-9]+))?(?:-rc.([0-9]+))?$/);
2043
+ if (!match) {
2044
+ throw new Error(`${versionStr} is not a valid semantic version`);
2045
+ }
2046
+ const semVer = Object.assign({ major: parseInt(match[1]), minor: parseInt(match[2]), patch: (() => {
2047
+ const str = match[3];
2048
+ return str === undefined ? 0 : parseInt(str);
2049
+ })() }, (() => {
2050
+ const str = match[4];
2051
+ return str === undefined ? {} : { rc: parseInt(str) };
2052
+ })());
2053
+ const initialStr = stringify(semVer);
2054
+ Object.defineProperty(semVer, "parsedFrom", {
2055
+ enumerable: true,
2056
+ get: function () {
2057
+ const currentStr = stringify(this);
2058
+ if (currentStr !== initialStr) {
2059
+ throw new Error(`SemVer.parsedFrom can't be read anymore, the version have been modified from ${initialStr} to ${currentStr}`);
2060
+ }
2061
+ return versionStr;
2062
+ }
2063
+ });
2064
+ return semVer;
2065
+ }
2066
+ SemVer.parse = parse;
2067
+ function stringify(v) {
2068
+ return `${v.major}.${v.minor}.${v.patch}${v.rc === undefined ? "" : `-rc.${v.rc}`}`;
2069
+ }
2070
+ SemVer.stringify = stringify;
2071
+ /**
2072
+ *
2073
+ * v1 < v2 => -1
2074
+ * v1 === v2 => 0
2075
+ * v1 > v2 => 1
2076
+ *
2077
+ */
2078
+ function compare(v1, v2) {
2079
+ const sign = (diff) => (diff === 0 ? 0 : diff < 0 ? -1 : 1);
2080
+ const noUndefined = (n) => n !== null && n !== void 0 ? n : Infinity;
2081
+ for (const level of ["major", "minor", "patch", "rc"]) {
2082
+ if (noUndefined(v1[level]) !== noUndefined(v2[level])) {
2083
+ return sign(noUndefined(v1[level]) - noUndefined(v2[level]));
2084
+ }
2085
+ }
2086
+ return 0;
2087
+ }
2088
+ SemVer.compare = compare;
2089
+ /*
2090
+ console.log(compare(parse("3.0.0-rc.3"), parse("3.0.0")) === -1 )
2091
+ console.log(compare(parse("3.0.0-rc.3"), parse("3.0.0-rc.4")) === -1 )
2092
+ console.log(compare(parse("3.0.0-rc.3"), parse("4.0.0")) === -1 )
2093
+ */
2094
+ function bumpType(params) {
2095
+ const versionAhead = typeof params.versionAhead === "string"
2096
+ ? parse(params.versionAhead)
2097
+ : params.versionAhead;
2098
+ const versionBehind = typeof params.versionBehind === "string"
2099
+ ? parse(params.versionBehind)
2100
+ : params.versionBehind;
2101
+ if (compare(versionBehind, versionAhead) === 1) {
2102
+ throw new Error(`Version regression ${stringify(versionBehind)} -> ${stringify(versionAhead)}`);
2103
+ }
2104
+ for (const level of ["major", "minor", "patch", "rc"]) {
2105
+ if (versionBehind[level] !== versionAhead[level]) {
2106
+ return level;
2107
+ }
2108
+ }
2109
+ return "no bump";
2110
+ }
2111
+ SemVer.bumpType = bumpType;
2112
+ })(SemVer || (SemVer = {}));
2113
+ //# sourceMappingURL=SemVer.js.map
138
2114
 
139
- // EXPORTS
140
- __webpack_require__.d(__webpack_exports__, {
141
- "q": () => (/* binding */ maybeDelegateCommandToCustomHandler)
142
- });
143
-
144
- // EXTERNAL MODULE: ./node_modules/tsafe/esm/assert.mjs + 1 modules
145
- var esm_assert = __webpack_require__(29041);
146
- // EXTERNAL MODULE: ./dist/bin/shared/constants.js
147
- var constants = __webpack_require__(173);
148
- ;// CONCATENATED MODULE: ./dist/bin/shared/customHandler.js
149
-
150
-
151
- const BIN_NAME = "_keycloakify-custom-handler";
152
- const NOT_IMPLEMENTED_EXIT_CODE = 78;
153
- function readParams(params) {
154
- const { apiVersion } = params;
155
- assert(apiVersion === "v1");
156
- const commandName = (() => {
157
- const envValue = process.env[CUSTOM_HANDLER_ENV_NAMES.COMMAND_NAME];
158
- assert(envValue !== undefined);
159
- return envValue;
160
- })();
161
- const buildContext = (() => {
162
- const envValue = process.env[CUSTOM_HANDLER_ENV_NAMES.BUILD_CONTEXT];
163
- assert(envValue !== undefined);
164
- return JSON.parse(envValue);
165
- })();
166
- return { commandName, buildContext };
167
- }
168
- //# sourceMappingURL=customHandler.js.map
169
- // EXTERNAL MODULE: external "child_process"
170
- var external_child_process_ = __webpack_require__(32081);
171
- // EXTERNAL MODULE: ./dist/bin/tools/nodeModulesBinDirPath.js
172
- var tools_nodeModulesBinDirPath = __webpack_require__(73776);
173
- // EXTERNAL MODULE: external "fs"
174
- var external_fs_ = __webpack_require__(57147);
175
- ;// CONCATENATED MODULE: ./dist/bin/shared/customHandler_delegate.js
176
-
177
-
178
-
2115
+ /***/ }),
179
2116
 
2117
+ /***/ 43765:
2118
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
180
2119
 
2120
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2121
+ /* harmony export */ "o": () => (/* binding */ existsAsync)
2122
+ /* harmony export */ });
2123
+ /* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73292);
2124
+ /* harmony import */ var fs_promises__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs_promises__WEBPACK_IMPORTED_MODULE_0__);
181
2125
 
182
- (0,esm_assert/* assert */.h)();
183
- function maybeDelegateCommandToCustomHandler(params) {
184
- const { commandName, buildContext } = params;
185
- const nodeModulesBinDirPath = (0,tools_nodeModulesBinDirPath/* getNodeModulesBinDirPath */.K)();
186
- if (!external_fs_.readdirSync(nodeModulesBinDirPath).includes(BIN_NAME)) {
187
- return { hasBeenHandled: false };
188
- }
2126
+ async function existsAsync(path) {
189
2127
  try {
190
- external_child_process_.execSync(`npx ${BIN_NAME}`, {
191
- stdio: "inherit",
192
- env: Object.assign(Object.assign({}, process.env), { [constants/* CUSTOM_HANDLER_ENV_NAMES.COMMAND_NAME */._S.COMMAND_NAME]: commandName, [constants/* CUSTOM_HANDLER_ENV_NAMES.BUILD_CONTEXT */._S.BUILD_CONTEXT]: JSON.stringify(buildContext) })
193
- });
2128
+ await fs_promises__WEBPACK_IMPORTED_MODULE_0__.stat(path);
2129
+ return true;
194
2130
  }
195
2131
  catch (error) {
196
- const status = error.status;
197
- if (status === NOT_IMPLEMENTED_EXIT_CODE) {
198
- return { hasBeenHandled: false };
199
- }
200
- process.exit(status);
2132
+ if (error.code === "ENOENT")
2133
+ return false;
2134
+ throw error;
201
2135
  }
202
- return { hasBeenHandled: true };
203
2136
  }
204
- //# sourceMappingURL=customHandler_delegate.js.map
2137
+ //# sourceMappingURL=fs.existsAsync.js.map
205
2138
 
206
2139
  /***/ }),
207
2140
 
208
- /***/ 17192:
2141
+ /***/ 90665:
209
2142
  /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
210
2143
 
211
2144
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
212
- /* harmony export */ "A": () => (/* binding */ kebabCaseToCamelCase)
2145
+ /* harmony export */ "V": () => (/* binding */ isInside)
213
2146
  /* harmony export */ });
214
- /* harmony import */ var tsafe_capitalize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14899);
2147
+ /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(71017);
2148
+ /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__);
215
2149
 
216
- function kebabCaseToCamelCase(kebabCaseString) {
217
- const [first, ...rest] = kebabCaseString.split("-");
218
- return [first, ...rest.map(tsafe_capitalize__WEBPACK_IMPORTED_MODULE_0__/* .capitalize */ .k)].join("");
2150
+ function isInside(params) {
2151
+ const { dirPath, filePath } = params;
2152
+ return !(0,path__WEBPACK_IMPORTED_MODULE_0__.relative)(dirPath, filePath).startsWith("..");
219
2153
  }
220
- //# sourceMappingURL=kebabCaseToSnakeCase.js.map
2154
+ //# sourceMappingURL=isInside.js.map
221
2155
 
222
2156
  /***/ }),
223
2157
 
@@ -358,610 +2292,6 @@ async function runPrettier(params) {
358
2292
  }
359
2293
  //# sourceMappingURL=runPrettier.js.map
360
2294
 
361
- /***/ }),
362
-
363
- /***/ 18512:
364
- /***/ ((module) => {
365
-
366
-
367
- const x = module.exports;
368
- const ESC = '\u001B[';
369
- const OSC = '\u001B]';
370
- const BEL = '\u0007';
371
- const SEP = ';';
372
- const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';
373
-
374
- x.cursorTo = (x, y) => {
375
- if (typeof x !== 'number') {
376
- throw new TypeError('The `x` argument is required');
377
- }
378
-
379
- if (typeof y !== 'number') {
380
- return ESC + (x + 1) + 'G';
381
- }
382
-
383
- return ESC + (y + 1) + ';' + (x + 1) + 'H';
384
- };
385
-
386
- x.cursorMove = (x, y) => {
387
- if (typeof x !== 'number') {
388
- throw new TypeError('The `x` argument is required');
389
- }
390
-
391
- let ret = '';
392
-
393
- if (x < 0) {
394
- ret += ESC + (-x) + 'D';
395
- } else if (x > 0) {
396
- ret += ESC + x + 'C';
397
- }
398
-
399
- if (y < 0) {
400
- ret += ESC + (-y) + 'A';
401
- } else if (y > 0) {
402
- ret += ESC + y + 'B';
403
- }
404
-
405
- return ret;
406
- };
407
-
408
- x.cursorUp = count => ESC + (typeof count === 'number' ? count : 1) + 'A';
409
- x.cursorDown = count => ESC + (typeof count === 'number' ? count : 1) + 'B';
410
- x.cursorForward = count => ESC + (typeof count === 'number' ? count : 1) + 'C';
411
- x.cursorBackward = count => ESC + (typeof count === 'number' ? count : 1) + 'D';
412
-
413
- x.cursorLeft = ESC + 'G';
414
- x.cursorSavePosition = ESC + (isTerminalApp ? '7' : 's');
415
- x.cursorRestorePosition = ESC + (isTerminalApp ? '8' : 'u');
416
- x.cursorGetPosition = ESC + '6n';
417
- x.cursorNextLine = ESC + 'E';
418
- x.cursorPrevLine = ESC + 'F';
419
- x.cursorHide = ESC + '?25l';
420
- x.cursorShow = ESC + '?25h';
421
-
422
- x.eraseLines = count => {
423
- let clear = '';
424
-
425
- for (let i = 0; i < count; i++) {
426
- clear += x.eraseLine + (i < count - 1 ? x.cursorUp() : '');
427
- }
428
-
429
- if (count) {
430
- clear += x.cursorLeft;
431
- }
432
-
433
- return clear;
434
- };
435
-
436
- x.eraseEndLine = ESC + 'K';
437
- x.eraseStartLine = ESC + '1K';
438
- x.eraseLine = ESC + '2K';
439
- x.eraseDown = ESC + 'J';
440
- x.eraseUp = ESC + '1J';
441
- x.eraseScreen = ESC + '2J';
442
- x.scrollUp = ESC + 'S';
443
- x.scrollDown = ESC + 'T';
444
-
445
- x.clearScreen = '\u001Bc';
446
-
447
- x.clearTerminal = process.platform === 'win32' ?
448
- `${x.eraseScreen}${ESC}0f` :
449
- // 1. Erases the screen (Only done in case `2` is not supported)
450
- // 2. Erases the whole screen including scrollback buffer
451
- // 3. Moves cursor to the top-left position
452
- // More info: https://www.real-world-systems.com/docs/ANSIcode.html
453
- `${x.eraseScreen}${ESC}3J${ESC}H`;
454
-
455
- x.beep = BEL;
456
-
457
- x.link = (text, url) => {
458
- return [
459
- OSC,
460
- '8',
461
- SEP,
462
- SEP,
463
- url,
464
- BEL,
465
- text,
466
- OSC,
467
- '8',
468
- SEP,
469
- SEP,
470
- BEL
471
- ].join('');
472
- };
473
-
474
- x.image = (buf, opts) => {
475
- opts = opts || {};
476
-
477
- let ret = OSC + '1337;File=inline=1';
478
-
479
- if (opts.width) {
480
- ret += `;width=${opts.width}`;
481
- }
482
-
483
- if (opts.height) {
484
- ret += `;height=${opts.height}`;
485
- }
486
-
487
- if (opts.preserveAspectRatio === false) {
488
- ret += ';preserveAspectRatio=0';
489
- }
490
-
491
- return ret + ':' + buf.toString('base64') + BEL;
492
- };
493
-
494
- x.iTerm = {};
495
-
496
- x.iTerm.setCwd = cwd => OSC + '50;CurrentDir=' + (cwd || process.cwd()) + BEL;
497
-
498
-
499
- /***/ }),
500
-
501
- /***/ 39340:
502
- /***/ ((__unused_webpack_module, exports) => {
503
-
504
-
505
-
506
- Object.defineProperty(exports, "__esModule", ({
507
- value: true
508
- }));
509
- exports.withPromise = exports.withCallback = void 0;
510
-
511
- /**
512
- * Open the input with a normal callback function
513
- *
514
- * @param {Input} input - input object
515
- * @param {function} valueMapper - function which maps the resulting id and value back to the expected format
516
- * @param {function} callback - callback function
517
- */
518
- const withCallback = (input, valueMapper, callback) => {
519
- input.open();
520
- input.onSelect((id, value) => callback(valueMapper(id, value)));
521
- };
522
- /**
523
- * Open the input with a promise
524
- *
525
- * @param {Input} input - input object
526
- * @param {function} valueMapper - function which maps the resulting id and value back to the expected format
527
- */
528
-
529
-
530
- exports.withCallback = withCallback;
531
-
532
- const withPromise = (input, valueMapper) => {
533
- return new Promise((resolve, reject) => {
534
- input.open();
535
- input.onSelect((id, value) => {
536
- if (id === null) {
537
- reject();
538
- } else {
539
- resolve(valueMapper(id, value));
540
- }
541
- });
542
- });
543
- };
544
-
545
- exports.withPromise = withPromise;
546
-
547
- /***/ }),
548
-
549
- /***/ 99398:
550
- /***/ ((module, exports, __webpack_require__) => {
551
-
552
-
553
-
554
- Object.defineProperty(exports, "__esModule", ({
555
- value: true
556
- }));
557
- exports["default"] = void 0;
558
-
559
- var _input = _interopRequireDefault(__webpack_require__(25730));
560
-
561
- var _renderer = _interopRequireDefault(__webpack_require__(16059));
562
-
563
- var _callbackMappers = __webpack_require__(39340);
564
-
565
- var _valueMappers = __webpack_require__(26730);
566
-
567
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
568
-
569
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
570
-
571
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
572
-
573
- /**
574
- * Default options
575
- */
576
- const defaultOptions = {
577
- outputStream: process.stdout,
578
- inputStream: process.stdin,
579
- values: [],
580
- defaultValue: 0,
581
- selected: '(x)',
582
- unselected: '( )',
583
- indentation: 0,
584
- cleanup: true,
585
- valueRenderer: value => value
586
- };
587
- /**
588
- * Create an instance of cli-select with the given options
589
- *
590
- * @param {object} options - options for cli-select
591
- * @param {function} callback - if specified, a callback will be used, otherwise a promise gets returned (optional)
592
- */
593
-
594
- const creator = (options, callback) => {
595
- // merge options with default options
596
- options = _objectSpread({}, defaultOptions, options); // create renderer and input instances
597
-
598
- const renderer = new _renderer.default(options, options.outputStream);
599
- const input = new _input.default(options.inputStream);
600
- input.setDefaultValue(options.defaultValue);
601
- input.attachRenderer(renderer); // handle array and object values
602
-
603
- let valueMapper;
604
-
605
- if (Array.isArray(options.values)) {
606
- valueMapper = (0, _valueMappers.withArrayValues)(options);
607
- } else {
608
- valueMapper = (0, _valueMappers.withObjectValues)(options);
609
- } // map values
610
-
611
-
612
- options.values = valueMapper.input;
613
- input.setValues(options.values); // handle different callback methods
614
-
615
- if (typeof callback === 'function') {
616
- return (0, _callbackMappers.withCallback)(input, valueMapper.output, callback);
617
- } else {
618
- return (0, _callbackMappers.withPromise)(input, valueMapper.output);
619
- }
620
- };
621
-
622
- exports = module.exports = creator;
623
- Object.defineProperty(exports, "__esModule", ({
624
- value: true
625
- }));
626
- var _default = creator;
627
- exports["default"] = _default;
628
-
629
- /***/ }),
630
-
631
- /***/ 25730:
632
- /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
633
-
634
-
635
-
636
- Object.defineProperty(exports, "__esModule", ({
637
- value: true
638
- }));
639
- exports["default"] = void 0;
640
-
641
- var _readline = _interopRequireDefault(__webpack_require__(14521));
642
-
643
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
644
-
645
- /**
646
- * Handle cli input
647
- */
648
- class Input {
649
- /**
650
- * Input constructor
651
- *
652
- * @param {any} stream - stream to catch (optional)
653
- */
654
- constructor(stream = process.stdin) {
655
- // set default values
656
- this.stream = stream;
657
- this.values = [];
658
- this.selectedValue = 0;
659
-
660
- this.onSelectListener = () => {};
661
-
662
- this.onKeyPress = this.onKeyPress.bind(this);
663
- }
664
- /**
665
- * Set the available values
666
- *
667
- * @param {array} values - all available values
668
- */
669
-
670
-
671
- setValues(values) {
672
- this.values = values;
673
-
674
- if (this.renderer) {
675
- this.renderer.setValues(values);
676
- }
677
- }
678
- /**
679
- * Set the default value
680
- *
681
- * @param {number} defaultValue - default value id
682
- */
683
-
684
-
685
- setDefaultValue(defaultValue) {
686
- this.selectedValue = defaultValue;
687
- }
688
- /**
689
- * Attach a renderer to the input catcher
690
- *
691
- * @param {Renderer} renderer - renderer to use for rendering responses
692
- */
693
-
694
-
695
- attachRenderer(renderer) {
696
- this.renderer = renderer;
697
- this.renderer.setValues(this.values);
698
- }
699
- /**
700
- * Register an on select listener
701
- *
702
- * @param {function} listener - listener function which receives two parameters: valueId and value
703
- */
704
-
705
-
706
- onSelect(listener) {
707
- this.onSelectListener = listener;
708
- }
709
- /**
710
- * Open the stream and listen for input
711
- */
712
-
713
-
714
- open() {
715
- // register keypress event
716
- _readline.default.emitKeypressEvents(this.stream); // handle keypress
717
-
718
-
719
- this.stream.on('keypress', this.onKeyPress); // initially render the response
720
-
721
- if (this.renderer) {
722
- this.renderer.render(this.selectedValue);
723
- } // hide pressed keys and start listening on input
724
-
725
-
726
- this.stream.setRawMode(true);
727
- this.stream.resume();
728
- }
729
- /**
730
- * Close the stream
731
- *
732
- * @param {boolean} cancelled - true if no value was selected (optional)
733
- */
734
-
735
-
736
- close(cancelled = false) {
737
- // reset stream properties
738
- this.stream.setRawMode(false);
739
- this.stream.pause(); // cleanup the output
740
-
741
- if (this.renderer) {
742
- this.renderer.cleanup();
743
- } // call the on select listener
744
-
745
-
746
- if (cancelled) {
747
- this.onSelectListener(null);
748
- } else {
749
- this.onSelectListener(this.selectedValue, this.values[this.selectedValue]);
750
- }
751
-
752
- this.stream.removeListener('keypress', this.onKeyPress);
753
- }
754
- /**
755
- * Render the response
756
- */
757
-
758
-
759
- render() {
760
- if (!this.renderer) {
761
- return;
762
- }
763
-
764
- this.renderer.render(this.selectedValue);
765
- }
766
- /**
767
- * Handle key press event
768
- *
769
- * @param {string} string - input string
770
- * @param {object} key - object containing information about the pressed key
771
- */
772
-
773
-
774
- onKeyPress(string, key) {
775
- if (key) {
776
- if (key.name === 'up' && this.selectedValue > 0) {
777
- this.selectedValue--;
778
- this.render();
779
- } else if (key.name === 'down' && this.selectedValue + 1 < this.values.length) {
780
- this.selectedValue++;
781
- this.render();
782
- } else if (key.name === 'return') {
783
- this.close();
784
- } else if (key.name === 'escape' || key.name === 'c' && key.ctrl) {
785
- this.close(true);
786
- }
787
- }
788
- }
789
-
790
- }
791
-
792
- exports["default"] = Input;
793
-
794
- /***/ }),
795
-
796
- /***/ 16059:
797
- /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
798
-
799
-
800
-
801
- Object.defineProperty(exports, "__esModule", ({
802
- value: true
803
- }));
804
- exports["default"] = void 0;
805
-
806
- var _readline = _interopRequireDefault(__webpack_require__(14521));
807
-
808
- var _ansiEscapes = __webpack_require__(18512);
809
-
810
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
811
-
812
- /**
813
- * Response renderer
814
- */
815
- class Renderer {
816
- /**
817
- * Renderer constructor
818
- *
819
- * @param {object} options - renderer options
820
- * @param {any} stream - stream to write to (optional)
821
- */
822
- constructor(options, stream = process.stdout) {
823
- this.options = options;
824
- this.stream = stream;
825
- this.values = [];
826
- this.initialRender = true;
827
- }
828
- /**
829
- * Set the available values
830
- *
831
- * @param {array} values - all available values
832
- */
833
-
834
-
835
- setValues(values) {
836
- this.values = values;
837
- }
838
- /**
839
- * Render the values
840
- *
841
- * @param {number} selectedValue - selected value (optional)
842
- */
843
-
844
-
845
- render(selectedValue = 0) {
846
- if (this.initialRender) {
847
- // hide the cursor initially
848
- this.initialRender = false;
849
- this.stream.write(_ansiEscapes.cursorHide);
850
- } else {
851
- // remove previous lines and values
852
- this.stream.write((0, _ansiEscapes.eraseLines)(this.values.length));
853
- } // output the current values
854
-
855
-
856
- this.values.forEach((value, index) => {
857
- const symbol = selectedValue === index ? this.options.selected : this.options.unselected;
858
- const indentation = ' '.repeat(this.options.indentation);
859
- const renderedValue = this.options.valueRenderer(value, selectedValue === index);
860
- const end = index !== this.values.length - 1 ? '\n' : '';
861
- this.stream.write(indentation + symbol + ' ' + renderedValue + end);
862
- });
863
- }
864
- /**
865
- * Cleanup the console at the end
866
- */
867
-
868
-
869
- cleanup() {
870
- this.stream.write((0, _ansiEscapes.eraseLines)(this.values.length));
871
- this.stream.write(_ansiEscapes.cursorShow);
872
- }
873
-
874
- }
875
-
876
- exports["default"] = Renderer;
877
-
878
- /***/ }),
879
-
880
- /***/ 26730:
881
- /***/ ((__unused_webpack_module, exports) => {
882
-
883
-
884
-
885
- Object.defineProperty(exports, "__esModule", ({
886
- value: true
887
- }));
888
- exports.withObjectValues = exports.withArrayValues = void 0;
889
-
890
- /**
891
- * Map incoming and outgoing values if the initial values are an array
892
- *
893
- * @param {object} options - cli-select options
894
- */
895
- const withArrayValues = options => {
896
- return {
897
- input: options.values,
898
- output: (id, value) => {
899
- return {
900
- id,
901
- value
902
- };
903
- }
904
- };
905
- };
906
- /**
907
- * Map incoming and outgoing values if the initial values are an object
908
- *
909
- * @param {object} options - cli-select options
910
- */
911
-
912
-
913
- exports.withArrayValues = withArrayValues;
914
-
915
- const withObjectValues = options => {
916
- const originalValues = options.values;
917
- return {
918
- input: Object.values(originalValues),
919
- output: (id, value) => {
920
- return {
921
- id: Object.keys(originalValues)[id],
922
- value
923
- };
924
- }
925
- };
926
- };
927
-
928
- exports.withObjectValues = withObjectValues;
929
-
930
- /***/ }),
931
-
932
- /***/ 14899:
933
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
934
-
935
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
936
- /* harmony export */ "k": () => (/* binding */ capitalize)
937
- /* harmony export */ });
938
- /** @see <https://docs.tsafe.dev/capitalize> */
939
- function capitalize(str) {
940
- return (str.charAt(0).toUpperCase() + str.slice(1));
941
- }
942
-
943
-
944
- //# sourceMappingURL=capitalize.mjs.map
945
-
946
-
947
- /***/ }),
948
-
949
- /***/ 76030:
950
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
951
-
952
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
953
- /* harmony export */ "r": () => (/* binding */ symToStr)
954
- /* harmony export */ });
955
- /** @see <https://docs.tsafe.dev/main/symtostr> */
956
- function symToStr(wrap) {
957
- // @ts-expect-error: We know better
958
- return Object.keys(wrap)[0];
959
- }
960
-
961
-
962
- //# sourceMappingURL=symToStr.mjs.map
963
-
964
-
965
2295
  /***/ })
966
2296
 
967
2297
  };