Tests + splitt
This commit is contained in:
1 parent
a361f463a7
commit
2e2684779a
11 files changed
+428
-243
No files matched your search
+30
-16
@@ -13,6 +13,17 @@ repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
gradlePlugin {
|
||||
plugins {
|
||||
create("tsGenerator") {
|
||||
id = "no.iktdev.ts-gen"
|
||||
implementationClass = "no.iktdev.tsgen.TsGeneratorPlugin"
|
||||
// Denne er viktig for Gradle-menyen:
|
||||
displayName = "TS Generator"
|
||||
description = "Genererer TypeScript definisjoner fra Kotlin DTO-er"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
dependencies {
|
||||
@@ -20,6 +31,19 @@ dependencies {
|
||||
implementation("com.google.code.gson:gson:2.8.9")
|
||||
implementation(kotlin("reflect"))
|
||||
implementation(kotlin("stdlib"))
|
||||
|
||||
testImplementation("org.assertj:assertj-core:3.27.7")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")
|
||||
|
||||
// Bruk BOM for å styre alle JUnit-versjoner automatisk
|
||||
testImplementation(platform("org.junit:junit-bom:5.10.2"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
kotlin {
|
||||
@@ -34,28 +58,18 @@ val reposiliteUrl = if (version.toString().endsWith("SNAPSHOT")) {
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
create<MavenPublication>("reposilite") {
|
||||
artifactId = named
|
||||
versionMapping {
|
||||
usage("java-api") {
|
||||
fromResolutionOf("runtimeClasspath")
|
||||
}
|
||||
usage("java-runtime") {
|
||||
fromResolutionResult()
|
||||
}
|
||||
}
|
||||
pom {
|
||||
name.set(named)
|
||||
// 'pluginMaven' er den magiske tingen du trenger når du bruker java-gradle-plugin
|
||||
create<MavenPublication>("plugin") {
|
||||
from(components["java"])
|
||||
groupId = "no.iktdev"
|
||||
artifactId = "ts-gen" // Dette er navnet du refererer til
|
||||
version = project.version.toString()
|
||||
url.set(reposiliteUrl)
|
||||
}
|
||||
from(components["kotlin"])
|
||||
}
|
||||
}
|
||||
repositories {
|
||||
mavenLocal()
|
||||
maven {
|
||||
name = named
|
||||
name = "reposilite"
|
||||
url = uri(reposiliteUrl)
|
||||
credentials {
|
||||
username = System.getenv("reposiliteUsername")
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
import java.io.File
|
||||
import kotlin.reflect.KClass
|
||||
|
||||
class ClassScanner {
|
||||
fun scan(packageName: String, classLoader: ClassLoader): List<KClass<*>> {
|
||||
val path = packageName.replace('.', '/')
|
||||
println("TsGenerator: looking for resources at path: $path")
|
||||
|
||||
val resources = classLoader.getResources(path)
|
||||
|
||||
val classes = mutableListOf<KClass<*>>()
|
||||
|
||||
if (!resources.hasMoreElements()) {
|
||||
println("TsGenerator: NO RESOURCES FOUND for path: $path")
|
||||
}
|
||||
|
||||
while (resources.hasMoreElements()) {
|
||||
val url = resources.nextElement()
|
||||
println("TsGenerator: resource URL = $url")
|
||||
|
||||
val file = File(url.toURI())
|
||||
println("TsGenerator: resolved file = ${file.absolutePath}, exists=${file.exists()}, isDir=${file.isDirectory}")
|
||||
|
||||
if (file.exists() && file.isDirectory) {
|
||||
file.walkTopDown().forEach { f ->
|
||||
if (f.extension == "class") {
|
||||
val className = f.toClassName(path)
|
||||
try {
|
||||
val cls = Class.forName(className, false, classLoader).kotlin
|
||||
classes.add(cls)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return classes
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
import java.io.File
|
||||
import kotlin.reflect.KClass
|
||||
import kotlin.reflect.full.memberProperties
|
||||
import kotlin.reflect.full.primaryConstructor
|
||||
|
||||
object TsGenerator {
|
||||
val ttm = TsTypeMapper()
|
||||
val tmr = TsModelRenderer()
|
||||
|
||||
fun generate(packageName: String, output: File, classLoader: ClassLoader = Thread.currentThread().contextClassLoader) {
|
||||
println("TsGenerator: scanning package: $packageName")
|
||||
|
||||
val classes = scanClasses(packageName, classLoader)
|
||||
val classes = ClassScanner().scan(packageName, classLoader)
|
||||
|
||||
println("TsGenerator: found ${classes.size} classes total")
|
||||
classes.forEach { println(" - ${it.qualifiedName}") }
|
||||
@@ -51,7 +50,7 @@ object TsGenerator {
|
||||
// ----------------------------------------------------
|
||||
cls.isSealedSubtype() -> {
|
||||
println("Generating sealed subtype interface: ${cls.simpleName}")
|
||||
append(sealedSubtypeToTs(cls))
|
||||
append(tmr.sealedSubtypeToTs(cls))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
@@ -59,7 +58,7 @@ object TsGenerator {
|
||||
// ----------------------------------------------------
|
||||
cls.java.isEnum -> {
|
||||
println("Generating enum: ${cls.simpleName}")
|
||||
append(enumToTs(cls))
|
||||
append(tmr.enumToTs(cls))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
@@ -67,7 +66,7 @@ object TsGenerator {
|
||||
// ----------------------------------------------------
|
||||
cls.hasProperties() && !cls.isSealed -> {
|
||||
println("Generating interface: ${cls.simpleName}")
|
||||
append(dataClassToTs(cls))
|
||||
append(tmr.dataClassToTs(cls, ttm))
|
||||
}
|
||||
|
||||
else -> {
|
||||
@@ -84,216 +83,4 @@ object TsGenerator {
|
||||
println("TsGenerator: wrote file to ${output.absolutePath}")
|
||||
}
|
||||
|
||||
private fun File.toClassName(rootPath: String): String {
|
||||
val full = this.path.replace(File.separatorChar, '/')
|
||||
val idx = full.indexOf(rootPath)
|
||||
val relative = full.substring(idx)
|
||||
return relative
|
||||
.removeSuffix(".class")
|
||||
.replace('/', '.')
|
||||
}
|
||||
|
||||
private fun KClass<*>.hasProperties(): Boolean =
|
||||
this.memberProperties.isNotEmpty()
|
||||
|
||||
// sealed subtype = har en sealed supertype
|
||||
private fun KClass<*>.isSealedSubtype(): Boolean =
|
||||
this.supertypes
|
||||
.mapNotNull { it.classifier as? KClass<*> }
|
||||
.any { it.isSealed }
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// Kotlin → TS mapping
|
||||
// ------------------------------------------------------------
|
||||
|
||||
private fun enumToTs(cls: KClass<*>): String {
|
||||
val values = cls.java.enumConstants
|
||||
.joinToString(" | ") { "\"$it\"" }
|
||||
|
||||
return "export type ${cls.simpleName} = $values\n"
|
||||
}
|
||||
|
||||
private fun sealedSubtypeToTs(cls: KClass<*>): String {
|
||||
val props = cls.memberProperties
|
||||
.filter { it.name != "type" } // ← FIX: unngå duplisering
|
||||
.joinToString("\n") { prop ->
|
||||
val tsType = kotlinToTsType(prop.returnType.toString())
|
||||
" ${prop.name}: $tsType;"
|
||||
}
|
||||
|
||||
val propsBlock = if (props.isBlank()) "" else "\n$props"
|
||||
|
||||
return buildString {
|
||||
appendLine("export interface ${cls.simpleName} {")
|
||||
appendLine(" type: \"${cls.simpleName}\";$propsBlock")
|
||||
appendLine("}")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// NEW: extract default value for "type" discriminator
|
||||
private fun getDefaultTypeLiteral(cls: KClass<*>): String? {
|
||||
val ctor = cls.primaryConstructor ?: return null
|
||||
val param = ctor.parameters.find { it.name == "type" } ?: return null
|
||||
|
||||
return try {
|
||||
val instance = ctor.callBy(emptyMap())
|
||||
val prop = cls.memberProperties.find { it.name == "type" }
|
||||
prop?.getter?.call(instance)?.toString()
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun dataClassToTs(cls: KClass<*>): String {
|
||||
val typeParams = cls.typeParameters.map { it.name }
|
||||
val generic = if (typeParams.isNotEmpty()) {
|
||||
"<" + typeParams.joinToString(", ") + ">"
|
||||
} else ""
|
||||
|
||||
val defaultTypeLiteral = getDefaultTypeLiteral(cls)
|
||||
|
||||
val props = cls.memberProperties.joinToString("\n") { prop ->
|
||||
val tsType =
|
||||
if (prop.name == "type" && defaultTypeLiteral != null) {
|
||||
"\"$defaultTypeLiteral\"" // literal type
|
||||
} else {
|
||||
kotlinToTsType(prop.returnType.toString(), typeParams)
|
||||
}
|
||||
|
||||
" ${prop.name}: $tsType;"
|
||||
}
|
||||
|
||||
return buildString {
|
||||
appendLine("export interface ${cls.simpleName}$generic {")
|
||||
appendLine(props)
|
||||
appendLine("}")
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// Type mapping
|
||||
// ------------------------------------------------------------
|
||||
|
||||
private fun kotlinToTsType(kotlinType: String, genericParams: List<String> = emptyList()): String {
|
||||
val isNullable = kotlinType.endsWith("?")
|
||||
val clean = kotlinType.removeSuffix("?")
|
||||
|
||||
// UUID → string
|
||||
if (clean == "java.util.UUID") {
|
||||
return if (isNullable) "string | null" else "string"
|
||||
}
|
||||
|
||||
// Instant → string
|
||||
if (clean == "java.time.Instant") {
|
||||
return if (isNullable) "string | null" else "string"
|
||||
}
|
||||
|
||||
// Duration → string
|
||||
if (clean in listOf("kotlin.time.Duration", "java.time.Duration")) {
|
||||
return if (isNullable) "string | null" else "string"
|
||||
}
|
||||
|
||||
// Map<K, V> → Record<K, V>
|
||||
if (clean.startsWith("kotlin.collections.Map") ||
|
||||
clean.startsWith("kotlin.collections.MutableMap")) {
|
||||
|
||||
val inner = clean.substringAfter("<").substringBeforeLast(">")
|
||||
val (key, value) = inner.split(",").map { it.trim() }
|
||||
|
||||
val tsKey = kotlinToTsType(key, genericParams)
|
||||
val tsValue = kotlinToTsType(value, genericParams)
|
||||
|
||||
val base = "Record<$tsKey, $tsValue>"
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
// Set<T> → T[]
|
||||
if (clean.startsWith("kotlin.collections.Set") ||
|
||||
clean.startsWith("kotlin.collections.MutableSet")) {
|
||||
|
||||
val inner = clean.substringAfter("<").substringBeforeLast(">")
|
||||
|
||||
if (genericParams.contains(inner)) {
|
||||
val base = "${inner}[]"
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
val tsInner = kotlinToTsType(inner, genericParams)
|
||||
val base = "$tsInner[]"
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
// List<T> → T[]
|
||||
if (clean.startsWith("kotlin.collections.List") ||
|
||||
clean.startsWith("kotlin.collections.MutableList")) {
|
||||
|
||||
val inner = clean.substringAfter("<").substringBeforeLast(">")
|
||||
|
||||
if (genericParams.contains(inner)) {
|
||||
val base = "${inner}[]"
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
val tsInner = kotlinToTsType(inner, genericParams)
|
||||
val base = "$tsInner[]"
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
// Primitive mappings
|
||||
val base = when (clean) {
|
||||
"kotlin.String" -> "string"
|
||||
"kotlin.Int",
|
||||
"kotlin.Long",
|
||||
"kotlin.Float",
|
||||
"kotlin.Double" -> "number"
|
||||
"kotlin.Boolean" -> "boolean"
|
||||
"kotlin.Any" -> "any"
|
||||
else -> {
|
||||
if (clean.contains(".")) clean.substringAfterLast(".")
|
||||
else "any"
|
||||
}
|
||||
}
|
||||
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// Class scanning
|
||||
// ------------------------------------------------------------
|
||||
|
||||
private fun scanClasses(packageName: String, classLoader: ClassLoader): List<KClass<*>> {
|
||||
val path = packageName.replace('.', '/')
|
||||
println("TsGenerator: looking for resources at path: $path")
|
||||
|
||||
val resources = classLoader.getResources(path)
|
||||
|
||||
val classes = mutableListOf<KClass<*>>()
|
||||
|
||||
if (!resources.hasMoreElements()) {
|
||||
println("TsGenerator: NO RESOURCES FOUND for path: $path")
|
||||
}
|
||||
|
||||
while (resources.hasMoreElements()) {
|
||||
val url = resources.nextElement()
|
||||
println("TsGenerator: resource URL = $url")
|
||||
|
||||
val file = File(url.toURI())
|
||||
println("TsGenerator: resolved file = ${file.absolutePath}, exists=${file.exists()}, isDir=${file.isDirectory}")
|
||||
|
||||
if (file.exists() && file.isDirectory) {
|
||||
file.walkTopDown().forEach { f ->
|
||||
if (f.extension == "class") {
|
||||
val className = f.toClassName(path)
|
||||
try {
|
||||
val cls = Class.forName(className, false, classLoader).kotlin
|
||||
classes.add(cls)
|
||||
} catch (_: Throwable) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return classes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
import no.iktdev.ts.TsGenerator.ttm
|
||||
import kotlin.reflect.KClass
|
||||
import kotlin.reflect.full.memberProperties
|
||||
import kotlin.reflect.full.primaryConstructor
|
||||
|
||||
class TsModelRenderer {
|
||||
fun enumToTs(cls: KClass<*>): String {
|
||||
val values = cls.java.enumConstants
|
||||
.joinToString(" | ") { "\"$it\"" }
|
||||
|
||||
return "export type ${cls.simpleName} = $values\n"
|
||||
}
|
||||
|
||||
fun sealedSubtypeToTs(cls: KClass<*>): String {
|
||||
val props = cls.memberProperties
|
||||
.filter { it.name != "type" } // ← FIX: unngå duplisering
|
||||
.joinToString("\n") { prop ->
|
||||
val tsType = ttm.kotlinToTsType(prop.returnType.toString())
|
||||
" ${prop.name}: $tsType;"
|
||||
}
|
||||
|
||||
val propsBlock = if (props.isBlank()) "" else "\n$props"
|
||||
|
||||
return buildString {
|
||||
appendLine("export interface ${cls.simpleName} {")
|
||||
appendLine(" type: \"${cls.simpleName}\";$propsBlock")
|
||||
appendLine("}")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// NEW: extract default value for "type" discriminator
|
||||
fun getDefaultTypeLiteral(cls: KClass<*>): String? {
|
||||
val ctor = cls.primaryConstructor ?: return null
|
||||
val param = ctor.parameters.find { it.name == "type" } ?: return null
|
||||
|
||||
return try {
|
||||
val instance = ctor.callBy(emptyMap())
|
||||
val prop = cls.memberProperties.find { it.name == "type" }
|
||||
prop?.getter?.call(instance)?.toString()
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun dataClassToTs(cls: KClass<*>, ttm: TsTypeMapper): String {
|
||||
val typeParams = cls.typeParameters.map { it.name }
|
||||
val generic = if (typeParams.isNotEmpty()) "<" + typeParams.joinToString(", ") + ">" else ""
|
||||
|
||||
// 1. Finn alle super-interfacer (ekskluder Any/Object)
|
||||
val superInterfaces = cls.supertypes
|
||||
.mapNotNull { it.classifier as? KClass<*> }
|
||||
.filter { it.java.isInterface && it.simpleName != "Any" }
|
||||
|
||||
// 2. Lag "extends"-biten
|
||||
val extendsClause = if (superInterfaces.isNotEmpty()) {
|
||||
" extends ${superInterfaces.joinToString(", ") { it.simpleName!! }}"
|
||||
} else ""
|
||||
|
||||
// 3. Finn navn på egenskaper som finnes i super-interfacer, så vi unngår duplikater
|
||||
val inheritedPropNames = superInterfaces.flatMap { it.memberProperties }.map { it.name }.toSet()
|
||||
|
||||
val defaultTypeLiteral = getDefaultTypeLiteral(cls)
|
||||
|
||||
// 4. Generer kun props som IKKE er arvet
|
||||
val props = cls.memberProperties
|
||||
.filter { it.name !in inheritedPropNames }
|
||||
.joinToString("\n") { prop ->
|
||||
val tsType = if (prop.name == "type" && defaultTypeLiteral != null) {
|
||||
"\"$defaultTypeLiteral\""
|
||||
} else {
|
||||
ttm.kotlinToTsType(prop.returnType.toString(), typeParams)
|
||||
}
|
||||
" ${prop.name}: $tsType;"
|
||||
}
|
||||
|
||||
return buildString {
|
||||
appendLine("export interface ${cls.simpleName}$generic$extendsClause {")
|
||||
if (props.isNotBlank()) appendLine(props)
|
||||
appendLine("}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
class TsTypeMapper {
|
||||
fun kotlinToTsType(kotlinType: String, genericParams: List<String> = emptyList()): String {
|
||||
val isNullable = kotlinType.endsWith("?")
|
||||
val clean = kotlinType.removeSuffix("?")
|
||||
|
||||
// UUID → string
|
||||
if (clean == "java.util.UUID") {
|
||||
return if (isNullable) "string | null" else "string"
|
||||
}
|
||||
|
||||
// Instant → string
|
||||
if (clean == "java.time.Instant") {
|
||||
return if (isNullable) "string | null" else "string"
|
||||
}
|
||||
|
||||
// Duration → string
|
||||
if (clean in listOf("kotlin.time.Duration", "java.time.Duration")) {
|
||||
return if (isNullable) "string | null" else "string"
|
||||
}
|
||||
|
||||
// Map<K, V> → Record<K, V>
|
||||
if (clean.startsWith("kotlin.collections.Map") ||
|
||||
clean.startsWith("kotlin.collections.MutableMap")) {
|
||||
|
||||
val inner = clean.substringAfter("<").substringBeforeLast(">")
|
||||
val (key, value) = inner.split(",").map { it.trim() }
|
||||
|
||||
val tsKey = kotlinToTsType(key, genericParams)
|
||||
val tsValue = kotlinToTsType(value, genericParams)
|
||||
|
||||
val base = "Record<$tsKey, $tsValue>"
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
// Set<T> → T[]
|
||||
if (clean.startsWith("kotlin.collections.Set") ||
|
||||
clean.startsWith("kotlin.collections.MutableSet")) {
|
||||
|
||||
val inner = clean.substringAfter("<").substringBeforeLast(">")
|
||||
|
||||
if (genericParams.contains(inner)) {
|
||||
val base = "${inner}[]"
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
val tsInner = kotlinToTsType(inner, genericParams)
|
||||
val base = "$tsInner[]"
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
// List<T> → T[]
|
||||
if (clean.startsWith("kotlin.collections.List") ||
|
||||
clean.startsWith("kotlin.collections.MutableList")) {
|
||||
|
||||
val inner = clean.substringAfter("<").substringBeforeLast(">")
|
||||
|
||||
if (genericParams.contains(inner)) {
|
||||
val base = "${inner}[]"
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
val tsInner = kotlinToTsType(inner, genericParams)
|
||||
val base = "$tsInner[]"
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
|
||||
// Primitive mappings
|
||||
val base = when (clean) {
|
||||
"kotlin.String" -> "string"
|
||||
"kotlin.Int",
|
||||
"kotlin.Long",
|
||||
"kotlin.Float",
|
||||
"kotlin.Double" -> "number"
|
||||
"kotlin.Boolean" -> "boolean"
|
||||
"kotlin.Any" -> "any"
|
||||
else -> {
|
||||
if (clean.contains(".")) clean.substringAfterLast(".")
|
||||
else "any"
|
||||
}
|
||||
}
|
||||
|
||||
return if (isNullable) "$base | null" else base
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
import java.io.File
|
||||
import kotlin.reflect.KClass
|
||||
import kotlin.reflect.full.memberProperties
|
||||
|
||||
fun File.toClassName(rootPath: String): String {
|
||||
val full = this.path.replace(File.separatorChar, '/')
|
||||
val idx = full.indexOf(rootPath)
|
||||
val relative = full.substring(idx)
|
||||
return relative
|
||||
.removeSuffix(".class")
|
||||
.replace('/', '.')
|
||||
}
|
||||
|
||||
fun KClass<*>.hasProperties(): Boolean =
|
||||
this.memberProperties.isNotEmpty()
|
||||
|
||||
// sealed subtype = har en sealed supertype
|
||||
fun KClass<*>.isSealedSubtype(): Boolean =
|
||||
this.supertypes
|
||||
.mapNotNull { it.classifier as? KClass<*> }
|
||||
.any { it.isSealed }
|
||||
@@ -1,32 +1,40 @@
|
||||
package no.iktdev.tsgen
|
||||
|
||||
import no.iktdev.ts.TsGenerator // Importer generatoren din
|
||||
import no.iktdev.ts.TsGenerator
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.plugins.JavaPluginExtension
|
||||
import org.gradle.api.provider.Property
|
||||
import java.io.File
|
||||
import java.net.URLClassLoader
|
||||
|
||||
// Interface for brukerkonfigurasjon
|
||||
interface TsGeneratorExtension {
|
||||
val packageName: Property<String>
|
||||
val outputDir: Property<File>
|
||||
val outputFile: Property<File>
|
||||
}
|
||||
|
||||
class TsGeneratorPlugin : Plugin<Project> {
|
||||
override fun apply(project: Project) {
|
||||
// Lag en extension så brukeren kan sette config
|
||||
val extension = project.extensions.create("tsGenerator", TsGeneratorExtension::class.java)
|
||||
|
||||
project.tasks.register("generateTs") {
|
||||
// Sett avhengighet (valgfritt: gjør at den alltid kjører før compile)
|
||||
group = "typescript"
|
||||
dependsOn("compileKotlin")
|
||||
|
||||
doLast {
|
||||
val pkg = extension.packageName.get()
|
||||
val out = extension.outputDir.get()
|
||||
val out = extension.outputFile.get() // Henter File direkte
|
||||
|
||||
// Kall din generator-logikk
|
||||
TsGenerator.generate(pkg, out)
|
||||
// Hent classpath for å lage ClassLoaderen
|
||||
val mainSourceSet = project.extensions.getByType(JavaPluginExtension::class.java)
|
||||
.sourceSets.getByName("main")
|
||||
|
||||
val urls = mainSourceSet.runtimeClasspath.map { it.toURI().toURL() }.toTypedArray()
|
||||
val cl = URLClassLoader(urls, TsGenerator::class.java.classLoader)
|
||||
|
||||
|
||||
// Kall din signatur: generate(packageName, output, classLoader)
|
||||
TsGenerator.generate(pkg, out, cl)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class ClassScannerTest {
|
||||
|
||||
@Test
|
||||
fun `should scan package and find this class`() {
|
||||
val scanner = ClassScanner()
|
||||
val classes = scanner.scan("no.iktdev.ts", this.javaClass.classLoader)
|
||||
|
||||
// Sjekk at vi fant minst oss selv
|
||||
assertThat(classes).anyMatch { it.simpleName == "ClassScanner" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
import no.iktdev.ts.models.Camera
|
||||
import no.iktdev.ts.models.DeviceStatus
|
||||
import no.iktdev.ts.models.Fancy
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.jupiter.api.Assertions.*
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class TsModelRendererTest {
|
||||
|
||||
private val renderer = TsModelRenderer()
|
||||
private val ttm = TsTypeMapper()
|
||||
|
||||
@Test
|
||||
fun `should maintain exact property names without renaming`() {
|
||||
val result = renderer.dataClassToTs(Fancy::class, ttm)
|
||||
|
||||
// Sjekk at "isFancy" ikke ble endret til "fancy"
|
||||
assertThat(result).contains("isFancy: boolean;")
|
||||
// Sjekk at arv er med
|
||||
assertThat(result).contains("extends Parent")
|
||||
// Sjekk at arvet felt (id) ikke dupliseres hvis du har filtrert det bort
|
||||
assertThat(result).doesNotContain("id: string;")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `full test - verifiser arv, typer og union`() {
|
||||
// 1. Test Interface Arv
|
||||
val cameraTs = renderer.dataClassToTs(Camera::class, ttm)
|
||||
|
||||
assertThat(cameraTs).contains("interface Camera extends BaseDevice")
|
||||
assertThat(cameraTs).contains("resolution: number;")
|
||||
assertThat(cameraTs).doesNotContain("id: string;") // Skal være arvet, ikke duplisert
|
||||
|
||||
// 2. Test Enum til Union Type
|
||||
val enumTs = renderer.enumToTs(DeviceStatus::class)
|
||||
assertThat(enumTs).isEqualTo("export type DeviceStatus = \"ONLINE\" | \"OFFLINE\"\n")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sealed subtype test - verifiser type discriminator`() {
|
||||
// La oss si vi har en klasse som bruker sealed-logikken din
|
||||
data class Sensor(val type: String = "TEMP_SENSOR", val value: Double)
|
||||
|
||||
val sensorTs = renderer.sealedSubtypeToTs(Sensor::class)
|
||||
|
||||
assertThat(sensorTs).contains("type: \"Sensor\";")
|
||||
assertThat(sensorTs).contains("value: number;")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package no.iktdev.ts
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
|
||||
class TsTypeMapperTest {
|
||||
|
||||
private val mapper = TsTypeMapper()
|
||||
|
||||
@Test
|
||||
fun `should map primitives correctly`() {
|
||||
assertEquals("string", mapper.kotlinToTsType("kotlin.String"))
|
||||
assertEquals("number", mapper.kotlinToTsType("kotlin.Int"))
|
||||
assertEquals("number", mapper.kotlinToTsType("kotlin.Double"))
|
||||
assertEquals("boolean", mapper.kotlinToTsType("kotlin.Boolean"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should map java types to string`() {
|
||||
assertEquals("string", mapper.kotlinToTsType("java.util.UUID"))
|
||||
assertEquals("string", mapper.kotlinToTsType("java.time.Instant"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should handle nullability`() {
|
||||
assertEquals("string | null", mapper.kotlinToTsType("kotlin.String?"))
|
||||
assertEquals("number | null", mapper.kotlinToTsType("kotlin.Int?"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should map List and Set to arrays`() {
|
||||
assertEquals("string[]", mapper.kotlinToTsType("kotlin.collections.List<kotlin.String>"))
|
||||
assertEquals("number[]", mapper.kotlinToTsType("kotlin.collections.MutableSet<kotlin.Int>"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should handle nested Map`() {
|
||||
val input = "kotlin.collections.Map<kotlin.String, kotlin.Int>"
|
||||
assertEquals("Record<string, number>", mapper.kotlinToTsType(input))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should handle generic parameters`() {
|
||||
// Antar at "T" er definert i genericParams
|
||||
val generics = listOf("T")
|
||||
assertEquals("T[]", mapper.kotlinToTsType("kotlin.collections.List<T>", generics))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `should handle unknown types by taking simple name`() {
|
||||
assertEquals("MyCustomClass", mapper.kotlinToTsType("no.iktdev.models.MyCustomClass"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package no.iktdev.ts.models
|
||||
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
// Dummy-klasser for testing
|
||||
interface Parent {
|
||||
val id: String
|
||||
}
|
||||
data class Fancy(val isFancy: Boolean) : Parent {
|
||||
override val id: String = "123"
|
||||
}
|
||||
|
||||
interface BaseDevice {
|
||||
val id: String
|
||||
}
|
||||
|
||||
data class Camera(override val id: String, val resolution: Int) : BaseDevice
|
||||
|
||||
enum class DeviceStatus { ONLINE, OFFLINE }
|
||||
Reference in new issue
Block a user