forked from thunder-id/thunderid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.sh
More file actions
executable file
·1270 lines (1053 loc) · 45.4 KB
/
Copy pathbuild.sh
File metadata and controls
executable file
·1270 lines (1053 loc) · 45.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# Copyright 2025-2026 The ThunderID Authors
# SPDX-License-Identifier: Apache-2.0
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# --- Set Default OS and the architecture ---
# Auto-detect GO OS
DEFAULT_OS=$(go env GOOS 2>/dev/null)
if [ -z "$DEFAULT_OS" ]; then
UNAME_OS="$(uname -s)"
case "$UNAME_OS" in
Darwin) DEFAULT_OS="darwin" ;;
Linux) DEFAULT_OS="linux" ;;
MINGW*|MSYS*|CYGWIN*) DEFAULT_OS="windows" ;;
*) echo "Unsupported OS: $UNAME_OS"; exit 1 ;;
esac
fi
# Auto-detect GO ARCH
DEFAULT_ARCH=$(go env GOARCH 2>/dev/null)
if [ -z "$DEFAULT_ARCH" ]; then
UNAME_ARCH="$(uname -m)"
case "$UNAME_ARCH" in
x86_64|amd64) DEFAULT_ARCH="amd64" ;;
arm64|aarch64) DEFAULT_ARCH="arm64" ;;
*) echo "Unsupported architecture: $UNAME_ARCH"; exit 1 ;;
esac
fi
GO_OS=${2:-$DEFAULT_OS}
GO_ARCH=${3:-$DEFAULT_ARCH}
echo "Using GO OS: $GO_OS and ARCH: $GO_ARCH"
# --- Package Distribution details ---
GO_PACKAGE_OS=$GO_OS
GO_PACKAGE_ARCH=$GO_ARCH
# Normalize OS name for distribution packaging
if [ "$GO_OS" = "darwin" ]; then
GO_PACKAGE_OS=macos
elif [ "$GO_OS" = "windows" ]; then
GO_PACKAGE_OS="win"
fi
if [ "$GO_ARCH" = "amd64" ]; then
GO_PACKAGE_ARCH=x64
fi
VERSION_FILE=version.txt
VERSION=$(cat "$VERSION_FILE")
PRODUCT_VERSION=${VERSION}
if [[ $PRODUCT_VERSION == v* ]]; then
PRODUCT_VERSION="${PRODUCT_VERSION#v}"
fi
PRODUCT_NAME="ThunderID"
PRODUCT_NAME_LOWERCASE="$(echo "$PRODUCT_NAME" | tr '[:upper:]' '[:lower:]')"
BINARY_NAME="${PRODUCT_NAME_LOWERCASE}"
PRODUCT_FOLDER=${BINARY_NAME}-${PRODUCT_VERSION}-${GO_PACKAGE_OS}-${GO_PACKAGE_ARCH}
# --- Sample App Distribution details ---
# React Vanilla Sample
VANILLA_SAMPLE_APP_VERSION=$(grep -o '"version": *"[^"]*"' samples/apps/react-vanilla-sample/package.json | sed 's/"version": *"\(.*\)"/\1/')
VANILLA_SAMPLE_APP_FOLDER="sample-app-react-vanilla-${VANILLA_SAMPLE_APP_VERSION}"
# React SDK Sample
REACT_SDK_SAMPLE_APP_VERSION=$(grep -o '"version": *"[^"]*"' samples/apps/react-sdk-sample/package.json | sed 's/"version": *"\(.*\)"/\1/')
REACT_SDK_SAMPLE_APP_FOLDER="sample-app-react-sdk-${REACT_SDK_SAMPLE_APP_VERSION}"
# React API-based Sample
REACT_API_SAMPLE_APP_VERSION=$(grep -o '"version": *"[^"]*"' samples/apps/react-api-based-sample/package.json | sed 's/"version": *"\(.*\)"/\1/')
REACT_API_SAMPLE_APP_FOLDER="sample-app-react-api-based-${REACT_API_SAMPLE_APP_VERSION}"
# Wayfinder Sample
WAYFINDER_SAMPLE_APP_VERSION=$(grep -o '"version": *"[^"]*"' samples/apps/wayfinder-sample/package.json | sed 's/"version": *"\(.*\)"/\1/')
WAYFINDER_SAMPLE_APP_FOLDER="sample-app-wayfinder-${WAYFINDER_SAMPLE_APP_VERSION}"
# Directories
TARGET_DIR=target
OUTPUT_DIR=$TARGET_DIR/out
DIST_DIR=$TARGET_DIR/dist
BUILD_DIR=$OUTPUT_DIR/.build
LOCAL_CERT_DIR=$OUTPUT_DIR/.cert
BACKEND_BASE_DIR=backend
BACKEND_DIR=$BACKEND_BASE_DIR/cmd/server
REPOSITORY_DB_DIR=$BACKEND_DIR/database
SERVER_SCRIPTS_DIR=$BACKEND_BASE_DIR/scripts
SERVER_DB_SCRIPTS_DIR=$BACKEND_BASE_DIR/dbscripts
SECURITY_DIR=config/certs
FRONTEND_BASE_DIR=frontend
GATE_APP_DIST_DIR=apps/gate
CONSOLE_APP_DIST_DIR=apps/console
FRONTEND_GATE_APP_SOURCE_DIR=$FRONTEND_BASE_DIR/apps/gate
FRONTEND_CONSOLE_APP_SOURCE_DIR=$FRONTEND_BASE_DIR/apps/console
SAMPLE_BASE_DIR=samples
VANILLA_SAMPLE_APP_DIR=$SAMPLE_BASE_DIR/apps/react-vanilla-sample
VANILLA_SAMPLE_APP_SERVER_DIR=$VANILLA_SAMPLE_APP_DIR/server
REACT_SDK_SAMPLE_APP_DIR=$SAMPLE_BASE_DIR/apps/react-sdk-sample
REACT_API_SAMPLE_APP_DIR=$SAMPLE_BASE_DIR/apps/react-api-based-sample
WAYFINDER_SAMPLE_APP_DIR=$SAMPLE_BASE_DIR/apps/wayfinder-sample
# Quick start declarative bundles staged into the console's welcome feature so they're inlined
# into the console JS bundle at build time.
# Add a new bundle as a single line: "<dest-name>:<source-dir>".
# <dest-name> may include "/" for grouping (e.g. "wayfinder/redirect-based").
QUICKSTART_SAMPLE_BUNDLES=(
"wayfinder:$WAYFINDER_SAMPLE_APP_DIR/thunderid-config"
)
QUICKSTART_BUNDLE_STAGE_DIR="$FRONTEND_CONSOLE_APP_SOURCE_DIR/src/features/welcome/data/sample-bundles"
# Default ports
GATE_APP_DEFAULT_PORT=5190
CONSOLE_APP_DEFAULT_PORT=5191
DOCS_DEFAULT_PORT=3000
# Integration test filters (optional)
TEST_RUN="${4:-}"
TEST_PACKAGE="${5:-}"
# PNPM version to use for frontend builds and docs build
PNPM_VERSION=$(grep -A2 '"packageManager"' package.json | grep -o '"version": *"[^"]*"' | sed 's/"version": *"\(.*\)"/\1/')
# ============================================================================
# Read Configuration from deployment.yaml
# ============================================================================
CONFIG_FILE="./backend/cmd/server/deployment.yaml"
# Function to read config with fallback
read_config() {
local config_file="$CONFIG_FILE"
if [ ! -f "$config_file" ]; then
# Use defaults if config file not found
HOSTNAME="localhost"
PORT=8090
HTTP_ONLY="false"
PUBLIC_HOSTNAME=""
else
# Try yq first (YAML parser)
if command -v yq >/dev/null 2>&1; then
HOSTNAME=$(yq eval '.server.hostname // "localhost"' "$config_file" 2>/dev/null)
PORT=$(yq eval '.server.port // 8090' "$config_file" 2>/dev/null)
HTTP_ONLY=$(yq eval '.server.http_only // false' "$config_file" 2>/dev/null)
PUBLIC_HOSTNAME=$(yq eval '.server.public_hostname // ""' "$config_file" 2>/dev/null)
else
# Fallback: basic parsing with grep/awk
HOSTNAME=$(grep -E '^\s*hostname:' "$config_file" | awk -F':' '{gsub(/[[:space:]"'\'']/,"",$2); print $2}' | head -1)
PORT=$(grep -E '^\s*port:' "$config_file" | awk -F':' '{gsub(/[[:space:]]/,"",$2); print $2}' | head -1)
PUBLIC_HOSTNAME=$(grep -E '^\s*public_hostname:' "$config_file" | grep -o '"[^"]*"' | tr -d '"' | head -1)
# Check for http_only
if grep -q 'http_only.*true' "$config_file" 2>/dev/null; then
HTTP_ONLY="true"
else
HTTP_ONLY="false"
fi
# Use defaults if not found
HOSTNAME=${HOSTNAME:-localhost}
PORT=${PORT:-8090}
fi
fi
# Determine protocol
if [ "$HTTP_ONLY" = "true" ]; then
PROTOCOL="http"
else
PROTOCOL="https"
fi
return 0
}
# Read configuration
read_config
# Construct base URL (internal API endpoint)
BASE_URL="${PROTOCOL}://${HOSTNAME}:${PORT}"
# Construct public URL (external/redirect URLs)
if [ -n "$PUBLIC_HOSTNAME" ]; then
PUBLIC_URL="$PUBLIC_HOSTNAME"
else
PUBLIC_URL="$BASE_URL"
fi
function get_coverage_exclusion_pattern() {
# Read exclusion patterns (full package paths) from .excludecoverage file
local coverage_exclude_file
# Check if we're already in the backend directory or need to use relative path
if [ -f ".excludecoverage" ]; then
coverage_exclude_file=".excludecoverage"
elif [ -f "$SCRIPT_DIR/$BACKEND_BASE_DIR/.excludecoverage" ]; then
coverage_exclude_file="$SCRIPT_DIR/$BACKEND_BASE_DIR/.excludecoverage"
else
echo "" >&2
return
fi
# Read non-comment, non-empty lines and join with '|' for grep (exact package path matching)
local pattern=$(awk '!/^#/ && NF {if(count++)printf "|"; printf "%s", $0}' "$coverage_exclude_file")
echo "$pattern"
}
function clean() {
echo "================================================================"
echo "Cleaning build artifacts..."
rm -rf "$TARGET_DIR"
echo "Removing certificates in the $BACKEND_DIR/$SECURITY_DIR"
rm -rf "$BACKEND_DIR/$SECURITY_DIR"
echo "Removing runtime secrets in the $BACKEND_DIR/config/secrets"
rm -rf "$BACKEND_DIR/config/secrets"
echo "Removing certificates in the $VANILLA_SAMPLE_APP_DIR"
rm -f "$VANILLA_SAMPLE_APP_DIR/server.cert"
rm -f "$VANILLA_SAMPLE_APP_DIR/server.key"
echo "Removing certificates in the $VANILLA_SAMPLE_APP_SERVER_DIR"
rm -f "$VANILLA_SAMPLE_APP_SERVER_DIR/server.cert"
rm -f "$VANILLA_SAMPLE_APP_SERVER_DIR/server.key"
echo "Removing certificates in the $REACT_SDK_SAMPLE_APP_DIR"
rm -f "$REACT_SDK_SAMPLE_APP_DIR/server.cert"
rm -f "$REACT_SDK_SAMPLE_APP_DIR/server.key"
echo "Removing certificates in the $REACT_API_SAMPLE_APP_DIR"
rm -f "$REACT_API_SAMPLE_APP_DIR/server.cert"
rm -f "$REACT_API_SAMPLE_APP_DIR/server.key"
echo "================================================================"
}
function build_backend() {
echo "================================================================"
echo "Building Go backend..."
mkdir -p "$BUILD_DIR"
# Set binary name with .exe extension for Windows
local output_binary="$BINARY_NAME"
if [ "$GO_OS" = "windows" ]; then
output_binary="${BINARY_NAME}.exe"
fi
# Check if coverage build is requested via ENABLE_COVERAGE environment variable
local build_flags="-x"
if [ "$ENABLE_COVERAGE" = "true" ]; then
echo "Building with coverage instrumentation enabled..."
# Build coverage package list
cd "$BACKEND_BASE_DIR" || exit 1
local exclude_pattern=$(get_coverage_exclusion_pattern)
local coverpkg
if [ -n "$exclude_pattern" ]; then
echo "Excluding coverage for patterns: $exclude_pattern"
coverpkg=$(go list ./... | grep -v -E "$exclude_pattern" | tr '\n' ',' | sed 's/,$//')
else
coverpkg=$(go list ./... | tr '\n' ',' | sed 's/,$//')
fi
cd "$SCRIPT_DIR" || exit 1
build_flags="$build_flags -cover -coverpkg=$coverpkg"
fi
GOOS=$GO_OS GOARCH=$GO_ARCH CGO_ENABLED=0 go build -C "$BACKEND_BASE_DIR" \
$build_flags -ldflags "-X \"main.version=$VERSION\" \
-X \"main.buildDate=$$(date -u '+%Y-%m-%d %H:%M:%S UTC')\"" \
-o "../$BUILD_DIR/$output_binary" ./cmd/server
echo "Initializing databases..."
initialize_databases true
echo "================================================================"
}
function initialize_databases() {
echo "================================================================"
local override=$1
if [[ -z "$override" ]]; then
override=false
fi
echo "Initializing SQLite databases..."
mkdir -p "$REPOSITORY_DB_DIR"
db_files=("configdb.db" "runtime_transient.db" "entitydb.db" "runtime_persistent.db")
script_paths=("configdb/sqlite.sql" "runtime_transient/sqlite.sql" "entitydb/sqlite.sql" "runtime_persistent/sqlite.sql")
for ((i = 0; i < ${#db_files[@]}; i++)); do
db_file="${db_files[$i]}"
script_rel_path="${script_paths[$i]}"
db_path="$REPOSITORY_DB_DIR/$db_file"
script_path="$SERVER_DB_SCRIPTS_DIR/$script_rel_path"
if [[ -f "$script_path" ]]; then
if [[ -f "$db_path" ]]; then
if $override; then
echo " - Removing existing $db_file as override is true"
rm "$db_path"
else
echo " ! Skipping $db_file: DB already exists. Delete the existing and re-run to recreate."
continue
fi
fi
echo " - Creating $db_file using $script_path"
sqlite3 "$db_path" < "$script_path"
sqlite3 "$db_path" "PRAGMA journal_mode=WAL;"
if [ $? -ne 0 ]; then
echo "Failed to enable WAL mode for $db_file"
exit 1
fi
else
echo " ! Skipping $db_file: SQL script not found at $script_path"
fi
done
echo "SQLite database initialization complete."
echo "================================================================"
}
function ensure_pnpm() {
if ! command -v pnpm >/dev/null 2>&1; then
echo "pnpm not found, installing..."
npm install -g pnpm@$PNPM_VERSION
fi
}
function build_frontend() {
echo "================================================================"
echo "Building frontend apps..."
ensure_pnpm
sync_quickstart_bundles
# Install dependencies
echo "Installing frontend dependencies..."
pnpm install --frozen-lockfile
echo "Building frontend applications & packages..."
pnpm build:frontend
# Return to script directory
cd "$SCRIPT_DIR" || exit 1
echo "================================================================"
}
function build_cli() {
echo "Building CLI tool..."
bash "$SCRIPT_DIR/tools/cli/scripts/build.sh"
}
function test_cli() {
echo "Running CLI tool tests..."
cd "$SCRIPT_DIR/tools/cli" && go test -v -race -count=1 ./...
cd "$SCRIPT_DIR" || exit 1
}
function build_i18n_extractor() {
local tool_bin="$SCRIPT_DIR/backend/bin/tools"
mkdir -p "$tool_bin"
echo "Building i18n-extractor..."
cd "$SCRIPT_DIR/tools/i18n-extractor" && go build -o "$tool_bin/i18n-extractor" .
cd "$SCRIPT_DIR" || exit 1
}
function test_i18n_extractor() {
echo "Running i18n-extractor tests..."
cd "$SCRIPT_DIR/tools/i18n-extractor" && go test -v .
cd "$SCRIPT_DIR" || exit 1
}
function lint_cli() {
local golangci_lint="$SCRIPT_DIR/backend/bin/tools/golangci-lint"
echo "Linting CLI tool..."
cd "$SCRIPT_DIR/tools/cli" && "$golangci_lint" run ./...
cd "$SCRIPT_DIR" || exit 1
}
function lint_i18n_extractor() {
local golangci_lint="$SCRIPT_DIR/backend/bin/tools/golangci-lint"
echo "Linting i18n-extractor..."
cd "$SCRIPT_DIR/tools/i18n-extractor" && "$golangci_lint" run ./...
cd "$SCRIPT_DIR" || exit 1
}
function lint_tools() {
echo "================================================================"
echo "Linting tools..."
lint_cli
lint_i18n_extractor
echo "================================================================"
}
function build_npm_tools() {
ensure_pnpm
echo "Installing tools dependencies..."
pnpm install --frozen-lockfile
echo "Building npm-based tools..."
pnpm --filter './tools/**' build
cd "$SCRIPT_DIR" || exit 1
}
function build_tools() {
echo "================================================================"
echo "Building tools..."
build_cli
build_i18n_extractor
build_npm_tools
echo "================================================================"
}
function test_tools() {
echo "================================================================"
echo "Running tool tests..."
test_cli
test_i18n_extractor
echo "================================================================"
}
function build_docs() {
echo "================================================================"
echo "Building documentation..."
ensure_pnpm
echo "Installing frontend dependencies (required for docs build)..."
pnpm install --frozen-lockfile
echo "Building documentation..."
pnpm run build:docs
# Return to script directory
cd "$SCRIPT_DIR" || exit 1
echo "================================================================"
}
function prepare_backend_for_packaging() {
echo "================================================================"
echo "Copying backend artifacts..."
# Use appropriate binary name based on OS
local binary_name="$BINARY_NAME"
if [ "$GO_OS" = "windows" ]; then
binary_name="${BINARY_NAME}.exe"
fi
cp "$BUILD_DIR/$binary_name" "$DIST_DIR/$PRODUCT_FOLDER/"
cp "$BACKEND_DIR/deployment.yaml" "$DIST_DIR/$PRODUCT_FOLDER/"
cp -r "$BACKEND_DIR/config" "$DIST_DIR/$PRODUCT_FOLDER/"
if [ -d "$REPOSITORY_DB_DIR" ]; then
cp -r "$REPOSITORY_DB_DIR" "$DIST_DIR/$PRODUCT_FOLDER/"
fi
cp "$VERSION_FILE" "$DIST_DIR/$PRODUCT_FOLDER/"
cp -r "$SERVER_SCRIPTS_DIR" "$DIST_DIR/$PRODUCT_FOLDER/"
cp -r "$SERVER_DB_SCRIPTS_DIR" "$DIST_DIR/$PRODUCT_FOLDER/"
mkdir -p "$DIST_DIR/$PRODUCT_FOLDER/$SECURITY_DIR"
# Never ship key material: strip any dev certs/keys that "cp -r config" above may have copied in.
rm -f "$DIST_DIR/$PRODUCT_FOLDER/$SECURITY_DIR"/*.cert "$DIST_DIR/$PRODUCT_FOLDER/$SECURITY_DIR"/*.key
# Ship an empty config/secrets directory (like config/certs) so a named volume mounted there
# inherits the runtime user's ownership instead of being created as root. Never ship the dev
# Direct Auth Secret that "cp -r config" may have copied in; setup.sh generates a fresh one.
mkdir -p "$DIST_DIR/$PRODUCT_FOLDER/config/secrets"
rm -f "$DIST_DIR/$PRODUCT_FOLDER/config/secrets/direct_auth_secret"
# Copy bootstrap directory
echo "Copying bootstrap scripts..."
cp -r "$BACKEND_DIR/bootstrap" "$DIST_DIR/$PRODUCT_FOLDER/"
# Never ship the dev-only CORS seed that `run` stages into the source bootstrap dir.
rm -f "$DIST_DIR/$PRODUCT_FOLDER/bootstrap/03-dev-server-configurations.yaml"
# Key material is not generated into the distribution; setup.sh generates it per deployment.
}
function prepare_frontend_for_packaging() {
echo "================================================================"
echo "Copying frontend artifacts..."
mkdir -p "$DIST_DIR/$PRODUCT_FOLDER/$GATE_APP_DIST_DIR"
mkdir -p "$DIST_DIR/$PRODUCT_FOLDER/$CONSOLE_APP_DIST_DIR"
# Copy gate app build output
if [ -d "$FRONTEND_GATE_APP_SOURCE_DIR/dist" ]; then
echo "Copying Gate app build output..."
shopt -s dotglob
cp -r "$FRONTEND_GATE_APP_SOURCE_DIR/dist/"* "$DIST_DIR/$PRODUCT_FOLDER/$GATE_APP_DIST_DIR"
shopt -u dotglob
else
echo "Warning: Gate app build output not found at $FRONTEND_GATE_APP_SOURCE_DIR/dist"
fi
# Copy console app build output
if [ -d "$FRONTEND_CONSOLE_APP_SOURCE_DIR/dist" ]; then
echo "Copying Console app build output..."
shopt -s dotglob
cp -r "$FRONTEND_CONSOLE_APP_SOURCE_DIR/dist/"* "$DIST_DIR/$PRODUCT_FOLDER/$CONSOLE_APP_DIST_DIR"
shopt -u dotglob
else
echo "Warning: Console app build output not found at $FRONTEND_CONSOLE_APP_SOURCE_DIR/dist"
fi
echo "================================================================"
}
function sync_quickstart_bundles() {
# Stage Quick start declarative bundles into the console's public dir.
echo "Syncing quick start sample bundles to console welcome data dir..."
rm -rf "$QUICKSTART_BUNDLE_STAGE_DIR"
for entry in "${QUICKSTART_SAMPLE_BUNDLES[@]}"; do
local dest_name="${entry%%:*}"
local src_dir="${entry#*:}"
local dest_dir="$QUICKSTART_BUNDLE_STAGE_DIR/$dest_name"
if [ -d "$src_dir" ]; then
echo " Staging '$dest_name' from $src_dir"
mkdir -p "$dest_dir"
shopt -s dotglob
cp -r "$src_dir/"* "$dest_dir"
shopt -u dotglob
else
echo " Warning: quick start bundle source not found at $src_dir (dest '$dest_name')"
fi
done
}
function package() {
echo "================================================================"
echo "Packaging backend & frontend artifacts..."
mkdir -p "$DIST_DIR/$PRODUCT_FOLDER"
prepare_frontend_for_packaging
prepare_backend_for_packaging
# Copy the appropriate startup and setup scripts based on the target OS
if [ "$GO_OS" = "windows" ]; then
echo "Including Windows scripts (start.ps1, setup.ps1)..."
cp -r "start.ps1" "$DIST_DIR/$PRODUCT_FOLDER"
cp -r "setup.ps1" "$DIST_DIR/$PRODUCT_FOLDER"
else
echo "Including Unix scripts (start.sh, setup.sh)..."
cp -r "start.sh" "$DIST_DIR/$PRODUCT_FOLDER"
cp -r "setup.sh" "$DIST_DIR/$PRODUCT_FOLDER"
# Ensure execute permissions on Unix scripts
chmod +x "$DIST_DIR/$PRODUCT_FOLDER/start.sh"
chmod +x "$DIST_DIR/$PRODUCT_FOLDER/setup.sh"
fi
echo "Creating zip file..."
rm -f "$DIST_DIR/$PRODUCT_FOLDER.zip"
(cd "$DIST_DIR" && find "$PRODUCT_FOLDER" | sort | zip "$PRODUCT_FOLDER.zip" -@)
rm -rf "${DIST_DIR:?}/$PRODUCT_FOLDER" "$BUILD_DIR"
echo "================================================================"
}
function package_sample_app() {
echo "================================================================"
echo "Packaging sample apps..."
ensure_pnpm
# pnpm pack rewrites workspace: dependencies to real versions, which
# requires the workspace to be installed.
echo "Installing workspace dependencies..."
pnpm install --frozen-lockfile
# Samples are packaged from source; ship certificates for the samples that
# expect them at the package root (react-api-based ignores them via .gitignore).
echo "=== Ensuring sample app certificates exist ==="
ensure_certificates "$VANILLA_SAMPLE_APP_DIR" "server"
ensure_certificates "$REACT_SDK_SAMPLE_APP_DIR" "server"
# Package React Vanilla sample
echo "=== Packaging React Vanilla sample app ==="
package_vanilla_sample
# Package React SDK sample
echo "=== Packaging React SDK sample app ==="
package_react_sdk_sample
# Package React API-based sample
echo "=== Packaging React API-based sample app ==="
package_react_api_based_sample
# Package Wayfinder sample
echo "=== Packaging Wayfinder sample app ==="
package_wayfinder_sample
echo "================================================================"
}
function package_vanilla_sample() {
local tgz
cd "$VANILLA_SAMPLE_APP_DIR" || exit 1
pnpm pack --pack-destination "$SCRIPT_DIR/$DIST_DIR"
cd "$SCRIPT_DIR" || exit 1
tgz=$(ls "$DIST_DIR"/thunderid-react-vanilla-sample-*.tgz 2>/dev/null | head -1)
if [ -z "$tgz" ]; then
echo "Error: pnpm pack did not produce a tgz for react-vanilla-sample"
exit 1
fi
tar xzf "$tgz" -C "$DIST_DIR"
mv "$DIST_DIR/package" "$DIST_DIR/$VANILLA_SAMPLE_APP_FOLDER"
(cd "$DIST_DIR" && find "$VANILLA_SAMPLE_APP_FOLDER" | sort | zip "$VANILLA_SAMPLE_APP_FOLDER.zip" -@)
rm -rf "${DIST_DIR:?}/$VANILLA_SAMPLE_APP_FOLDER" "$tgz"
echo "✅ React Vanilla sample app packaged successfully as $DIST_DIR/$VANILLA_SAMPLE_APP_FOLDER.zip"
}
function package_react_sdk_sample() {
local tgz
cd "$REACT_SDK_SAMPLE_APP_DIR" || exit 1
pnpm pack --pack-destination "$SCRIPT_DIR/$DIST_DIR"
cd "$SCRIPT_DIR" || exit 1
tgz=$(ls "$DIST_DIR"/thunderid-react-sdk-sample-*.tgz 2>/dev/null | head -1)
if [ -z "$tgz" ]; then
echo "Error: pnpm pack did not produce a tgz for react-sdk-sample"
exit 1
fi
tar xzf "$tgz" -C "$DIST_DIR"
mv "$DIST_DIR/package" "$DIST_DIR/$REACT_SDK_SAMPLE_APP_FOLDER"
(cd "$DIST_DIR" && find "$REACT_SDK_SAMPLE_APP_FOLDER" | sort | zip "$REACT_SDK_SAMPLE_APP_FOLDER.zip" -@)
rm -rf "${DIST_DIR:?}/$REACT_SDK_SAMPLE_APP_FOLDER" "$tgz"
echo "✅ React SDK sample app packaged successfully as $DIST_DIR/$REACT_SDK_SAMPLE_APP_FOLDER.zip"
}
function package_react_api_based_sample() {
local tgz
cd "$REACT_API_SAMPLE_APP_DIR" || exit 1
pnpm pack --pack-destination "$SCRIPT_DIR/$DIST_DIR"
cd "$SCRIPT_DIR" || exit 1
tgz=$(ls "$DIST_DIR"/thunderid-react-api-based-sample-*.tgz 2>/dev/null | head -1)
if [ -z "$tgz" ]; then
echo "Error: pnpm pack did not produce a tgz for react-api-based-sample"
exit 1
fi
tar xzf "$tgz" -C "$DIST_DIR"
mv "$DIST_DIR/package" "$DIST_DIR/$REACT_API_SAMPLE_APP_FOLDER"
# Certs are gitignored in this sample so pnpm pack excludes them; inject them
# into the package root where vite.config.ts expects them.
ensure_certificates "$DIST_DIR/$REACT_API_SAMPLE_APP_FOLDER" "server"
(cd "$DIST_DIR" && find "$REACT_API_SAMPLE_APP_FOLDER" | sort | zip "$REACT_API_SAMPLE_APP_FOLDER.zip" -@)
rm -rf "${DIST_DIR:?}/$REACT_API_SAMPLE_APP_FOLDER" "$tgz"
echo "✅ React API-based sample app packaged successfully as $DIST_DIR/$REACT_API_SAMPLE_APP_FOLDER.zip"
}
function package_wayfinder_sample() {
local tgz
cd "$WAYFINDER_SAMPLE_APP_DIR" || exit 1
pnpm pack --pack-destination "$SCRIPT_DIR/$DIST_DIR"
cd "$SCRIPT_DIR" || exit 1
tgz=$(ls "$DIST_DIR"/thunderid-wayfinder-sample-*.tgz 2>/dev/null | head -1)
if [ -z "$tgz" ]; then
echo "Error: pnpm pack did not produce a tgz for wayfinder-sample"
exit 1
fi
tar xzf "$tgz" -C "$DIST_DIR"
mv "$DIST_DIR/package" "$DIST_DIR/$WAYFINDER_SAMPLE_APP_FOLDER"
for dir in frontend backend smtp-server ai-agent lounge; do
if [ -f "$DIST_DIR/$WAYFINDER_SAMPLE_APP_FOLDER/$dir/.env.example" ]; then
cp "$DIST_DIR/$WAYFINDER_SAMPLE_APP_FOLDER/$dir/.env.example" "$DIST_DIR/$WAYFINDER_SAMPLE_APP_FOLDER/$dir/.env"
fi
done
(cd "$DIST_DIR" && find "$WAYFINDER_SAMPLE_APP_FOLDER" | sort | zip "$WAYFINDER_SAMPLE_APP_FOLDER.zip" -@)
rm -rf "${DIST_DIR:?}/$WAYFINDER_SAMPLE_APP_FOLDER" "$tgz"
echo "✅ Wayfinder sample app packaged successfully as $DIST_DIR/$WAYFINDER_SAMPLE_APP_FOLDER.zip"
}
function test_unit() {
echo "================================================================"
echo "Running unit tests with coverage..."
cd "$BACKEND_BASE_DIR" || exit 1
# Build coverage package list
local exclude_pattern=$(get_coverage_exclusion_pattern)
local coverpkg
if [ -n "$exclude_pattern" ]; then
echo "Excluding coverage for patterns: $exclude_pattern"
coverpkg=$(go list ./... | grep -v -E "$exclude_pattern" | tr '\n' ',' | sed 's/,$//')
else
echo "No exclusion patterns found, including all packages"
coverpkg=$(go list ./... | tr '\n' ',' | sed 's/,$//')
fi
# Run gotestsum if available, otherwise fallback to go test
if command -v gotestsum &> /dev/null; then
echo "Running unit tests with coverage using gotestsum..."
gotestsum -- -v -count=1 -coverprofile=coverage_unit.out -covermode=atomic -coverpkg="$coverpkg" ./... || { echo "There are unit test failures."; exit 1; }
else
echo "Running unit tests with coverage using go test..."
go test -v -count=1 -coverprofile=coverage_unit.out -covermode=atomic -coverpkg="$coverpkg" ./... || { echo "There are unit test failures."; exit 1; }
fi
echo "Unit test coverage profile generated in: backend/coverage_unit.out"
# Generate HTML coverage report for unit tests
go tool cover -html=coverage_unit.out -o=coverage_unit.html
echo "Unit test coverage HTML report generated in: backend/coverage_unit.html"
# Display unit test coverage summary
echo ""
echo "================================================================"
echo "Unit Test Coverage Summary:"
go tool cover -func=coverage_unit.out | tail -n 1
echo "================================================================"
echo ""
cd "$SCRIPT_DIR" || exit 1
echo "================================================================"
}
function test_integration() {
echo "================================================================"
echo "Running integration tests..."
cd "$SCRIPT_DIR" || exit 1
# Build extra args from test filters
local extra_args=""
if [ -n "$TEST_RUN" ]; then
extra_args="$extra_args -run $TEST_RUN"
echo "Test filter: -run $TEST_RUN"
fi
if [ -n "$TEST_PACKAGE" ]; then
extra_args="$extra_args -package $TEST_PACKAGE"
echo "Test package: $TEST_PACKAGE"
fi
# Set up coverage directory for integration tests
local coverage_dir="$(pwd)/$OUTPUT_DIR/.test/integration"
mkdir -p "$coverage_dir"
# Export coverage directory for the server binary to use
export GOCOVERDIR="$coverage_dir"
echo "Coverage data will be collected in: $coverage_dir"
go run -C ./tests/integration ./main.go $extra_args
test_exit_code=$?
# Process coverage data if tests passed or failed
if [ -d "$coverage_dir" ] && [ "$(ls -A $coverage_dir 2>/dev/null)" ]; then
echo "================================================================"
echo "Processing integration test coverage..."
# Convert binary coverage data to text format
cd "$BACKEND_BASE_DIR" || exit 1
go tool covdata textfmt -i="$coverage_dir" -o="../$TARGET_DIR/coverage_integration.out"
echo "Integration test coverage report generated in: $TARGET_DIR/coverage_integration.out"
# Generate HTML coverage report
go tool cover -html="../$TARGET_DIR/coverage_integration.out" -o="../$TARGET_DIR/coverage_integration.html"
echo "Integration test coverage HTML report generated in: $TARGET_DIR/coverage_integration.html"
# Display coverage summary
echo ""
echo "================================================================"
echo "Coverage Summary:"
go tool cover -func="../$TARGET_DIR/coverage_integration.out" | tail -n 1
echo "================================================================"
echo ""
cd "$SCRIPT_DIR" || exit 1
else
echo "================================================================"
echo "No coverage data collected"
fi
# Exit with the test exit code
if [ $test_exit_code -ne 0 ]; then
echo "================================================================"
echo "Integration tests failed with exit code: $test_exit_code"
exit $test_exit_code
fi
echo "================================================================"
}
function merge_coverage() {
echo "================================================================"
echo "Merging coverage reports..."
cd "$SCRIPT_DIR" || exit 1
local unit_coverage="$BACKEND_BASE_DIR/coverage_unit.out"
local integration_coverage="$TARGET_DIR/coverage_integration.out"
local combined_coverage="$TARGET_DIR/coverage_combined.out"
# Check if both coverage files exist
if [ ! -f "$unit_coverage" ]; then
echo "Warning: Unit test coverage file not found at $unit_coverage"
echo "Skipping coverage merge."
return 0
fi
if [ ! -f "$integration_coverage" ]; then
echo "Warning: Integration test coverage file not found at $integration_coverage"
echo "Skipping coverage merge."
return 0
fi
echo "Merging unit and integration test coverage..."
# Get the mode from the first file and write to combined coverage
head -n 1 "$unit_coverage" > "$combined_coverage"
# Combine both files (skip mode lines) and merge overlapping coverage
{ tail -n +2 "$unit_coverage"; tail -n +2 "$integration_coverage"; } | \
awk '
{
key = $1 " " $2
if (!(key in lines)) {
lines[key] = $0
count[key] = $3
} else {
# For duplicate entries, take the maximum count
if ($3 > count[key]) {
count[key] = $3
lines[key] = $1 " " $2 " " $3
}
}
}
END {
for (key in lines) {
print lines[key]
}
}
' | sort >> "$combined_coverage"
echo "Combined coverage report generated in: $combined_coverage"
# Generate HTML coverage report for combined coverage
cd "$BACKEND_BASE_DIR" || exit 1
go tool cover -html="../$combined_coverage" -o="../$TARGET_DIR/coverage_combined.html"
echo "Combined coverage HTML report generated in: $TARGET_DIR/coverage_combined.html"
# Display combined coverage summary
echo ""
echo "================================================================"
echo "Combined Test Coverage Summary:"
go tool cover -func="../$combined_coverage" | tail -n 1
echo "================================================================"
echo ""
cd "$SCRIPT_DIR" || exit 1
echo "================================================================"
}
function ensure_certificates() {
local cert_dir=$1
local cert_name_prefix=${2:-"server"} # Default to "server" if not specified
local cert_file_name="${cert_name_prefix}.cert"
local key_file_name="${cert_name_prefix}.key"
# Generate certificate and key file if they don't exist in the cert directory
local local_cert_file="${LOCAL_CERT_DIR}/${cert_file_name}"
local local_key_file="${LOCAL_CERT_DIR}/${key_file_name}"
if [[ ! -f "$local_cert_file" || ! -f "$local_key_file" ]]; then
mkdir -p "$LOCAL_CERT_DIR"
echo "Generating certificates (${cert_name_prefix}) in $LOCAL_CERT_DIR..."
if [[ "$cert_name_prefix" == ecdsa* ]]; then
OPENSSL_ERR=$(
openssl ecparam -name prime256v1 -genkey -noout -param_enc named_curve \
-out "$local_key_file" && \
openssl req -new -x509 -nodes -days 3650 \
-key "$local_key_file" \
-out "$local_cert_file" \
-subj "/O=ThunderID/OU=${PRODUCT_NAME}/CN=localhost" \
-addext "subjectAltName=DNS:localhost,IP:127.0.0.1" \
2>&1 >/dev/null
)
else
OPENSSL_ERR=$(
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout "$local_key_file" \
-out "$local_cert_file" \
-subj "/O=ThunderID/OU=${PRODUCT_NAME}/CN=localhost" \
-addext "subjectAltName=DNS:localhost,IP:127.0.0.1" \
2>&1 >/dev/null
)
fi
if [[ $? -ne 0 ]]; then
echo "Error generating certificates: $OPENSSL_ERR"
exit 1
fi
echo "Certificates generated successfully in $LOCAL_CERT_DIR."
else
echo "Certificates (${cert_name_prefix}) already exist in $LOCAL_CERT_DIR."
fi
# Copy the generated certificates to the specified directory
local cert_file="$cert_dir/${cert_file_name}"
local key_file="$cert_dir/${key_file_name}"
if [[ ! -f "$cert_file" || ! -f "$key_file" ]]; then
mkdir -p "$cert_dir"
echo "Copying certificates (${cert_name_prefix}) to $cert_dir..."
cp "$local_cert_file" "$cert_file"
cp "$local_key_file" "$key_file"
echo "Certificates copied successfully to $cert_dir."
else
echo "Certificates (${cert_name_prefix}) already exist in $cert_dir."
fi
}
function ensure_crypto_file() {
local KEY_DIR="$1"
# Define the default path for the key file
local KEY_FILE="$KEY_DIR/crypto.key"
echo "=== Ensuring crypto key file exists in the distribution ==="
# Check Whether the key file exists
if [ -f "$KEY_FILE" ]; then
echo "Default crypto key file already present in $KEY_FILE. Skipping generation."
else
echo "Default crypto key file not found. Generating new key at $KEY_FILE..."
# Generate 32-byte key (64 hex characters) using openssl
local NEW_KEY
if ! NEW_KEY=$(openssl rand -hex 32); then
echo "ERROR: Failed to generate crypto key using openssl."
exit 1
fi
# Ensure the target directory exists
mkdir -p "$KEY_DIR"
# Write the key to the new file.
echo -n "$NEW_KEY" > "$KEY_FILE"
echo "Successfully generated and added new crypto key to $KEY_FILE."
fi
echo "================================================================"
}
function ensure_direct_auth_secret_file() {
local SECRET_DIR="$1"
# Path referenced by server.security.direct_auth_secret (file://config/secrets/direct_auth_secret)
# in deployment.yaml. The server reads the secret from here at load time.
local SECRET_FILE="$SECRET_DIR/direct_auth_secret"
echo "=== Ensuring Direct Auth Secret file exists ==="
if [ -f "$SECRET_FILE" ]; then
echo "Direct Auth Secret file already present in $SECRET_FILE. Skipping generation."
else
echo "Direct Auth Secret file not found. Generating new secret at $SECRET_FILE..."
# Generate 32-byte secret (64 hex characters) using openssl.
local NEW_SECRET
if ! NEW_SECRET=$(openssl rand -hex 32); then
echo "ERROR: Failed to generate Direct Auth Secret using openssl."
exit 1
fi
# Ensure the target directory exists.
mkdir -p "$SECRET_DIR"
# Write the secret without a trailing newline so it is used verbatim.
echo -n "$NEW_SECRET" > "$SECRET_FILE"
echo "Successfully generated and added new Direct Auth Secret to $SECRET_FILE."
fi
# Restrict the secret to the owner, whether newly generated or pre-existing.
chmod 600 "$SECRET_FILE"
echo "================================================================"
}
function run() {
cleanup_servers() {
echo -e "\n🛑 Shutting down servers..."
if [ ! -z "$FRONTEND_PID" ]; then
kill $FRONTEND_PID 2>/dev/null
fi