File size: 8,118 Bytes
b450976
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  withAppBuildGradle,
  withGradleProperties,
  withMainApplication,
  withProjectBuildGradle,
  type ConfigPlugin,
} from "expo/config-plugins"

// Marker comments double as idempotency checks: each injection looks for its
// OWN unique marker (never a shared substring — a marker one block contains
// can silently mask another block's check).
const MAPBOX_REPO_MARKER = "mapbox: navigation sdk downloads repo (injected by @mentra/crust)"
const MAPBOX_REPO = [
  "    maven {",
  `      // ${MAPBOX_REPO_MARKER}`,
  "      url 'https://api.mapbox.com/downloads/v2/releases/maven'",
  "      authentication { basic(BasicAuthentication) }",
  "      credentials {",
  "        username = 'mapbox'",
  "        password = System.getenv('MAPBOX_DOWNLOADS_TOKEN') ?: (findProperty('MAPBOX_DOWNLOADS_TOKEN') ?: '')",
  "      }",
  "      content {",
  "        includeGroupByRegex 'com\\\\.mapbox.*'",
  "      }",
  "    }",
].join("\n")

// quickjs-kt 1.0.15 is compiled with Kotlin 2.4, and a Kotlin compiler reads
// metadata one version ahead. 2.3.0 is the newest 2.3 release Expo SDK 55's
// root plugin maps to a KSP version.
const MIN_KOTLIN_VERSION = "2.3.0"
// The template's unversioned classpath entry resolves to the Kotlin Gradle
// plugin React Native's Gradle plugin depends on (2.1.20 on RN 0.83), whatever
// `android.kotlinVersion` says; Expo fixes that only in SDK 58
// (expo/expo#49668). SDK 56 also never copies the property into Expo's catalog,
// so pin both the compiler and the root `kotlinVersion` to the property itself.
const UNVERSIONED_KOTLIN_PLUGIN = "classpath('org.jetbrains.kotlin:kotlin-gradle-plugin')"
const PINNED_KOTLIN_PLUGIN = `classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:\${findProperty('android.kotlinVersion')}")`
const KOTLIN_VERSION_MARKER = "kotlinVersion from android.kotlinVersion (injected by @mentra/crust)"
const EXPO_ROOT_PROJECT = 'apply plugin: "expo-root-project"'

function isOlderVersion(version: string, minimum: string) {
  const actual = version.split(".").map(Number)
  const required = minimum.split(".").map(Number)
  for (let i = 0; i < required.length; i++) {
    if ((actual[i] ?? 0) !== required[i]) return (actual[i] ?? 0) < required[i]
  }
  return false
}

function withCrustKotlinVersion(config: Parameters<ConfigPlugin>[0]) {
  return withGradleProperties(config, (cfg) => {
    const property = cfg.modResults.find((item) => item.type === "property" && item.key === "android.kotlinVersion")
    if (property?.type !== "property") {
      cfg.modResults.push({type: "property", key: "android.kotlinVersion", value: MIN_KOTLIN_VERSION})
    } else if (isOlderVersion(property.value, MIN_KOTLIN_VERSION)) {
      property.value = MIN_KOTLIN_VERSION
    }
    return cfg
  })
}

const PROTOBUF_EXCLUDE = "exclude group: 'com.google.protobuf', module: 'protobuf-javalite'"
const NOTIFICATION_PROCESS_GUARD = "crust: skip React Native in notification process"
const NOTIFICATION_CONFIG_GUARD = "crust: skip Expo lifecycle in notification process"

function withCrustProjectGradle(config: Parameters<ConfigPlugin>[0]) {
  return withProjectBuildGradle(config, (cfg) => {
    let gradle = cfg.modResults.contents

    gradle = gradle.replace(UNVERSIONED_KOTLIN_PLUGIN, PINNED_KOTLIN_PLUGIN)
    if (!gradle.includes(KOTLIN_VERSION_MARKER)) {
      gradle = gradle.replace(
        EXPO_ROOT_PROJECT,
        `// ${KOTLIN_VERSION_MARKER}\next.kotlinVersion = findProperty('android.kotlinVersion')\n${EXPO_ROOT_PROJECT}`,
      )
    }

    // Mapbox Downloads repo, inserted at the top of allprojects.repositories.
    if (!gradle.includes(MAPBOX_REPO_MARKER)) {
      const reposMatch = gradle.match(/allprojects\s*\{[\s\S]*?repositories\s*\{/)
      if (reposMatch) {
        const idx = (reposMatch.index ?? 0) + reposMatch[0].length
        gradle = gradle.slice(0, idx) + "\n" + MAPBOX_REPO + gradle.slice(idx)
      } else {
        gradle += `\nallprojects {\n  repositories {\n${MAPBOX_REPO}\n  }\n}\n`
      }
    }

    // protobuf-javalite exclusion, appended as its own allprojects block so
    // placement never depends on the shape of existing gradle content (other
    // plugins add maven{} entries that break brace-counting regexes).
    if (!gradle.includes(PROTOBUF_EXCLUDE)) {
      gradle += `

// Exclude protobuf-javalite in every project to avoid duplicate classes with

// protobuf-java (injected by @mentra/crust).

allprojects {

  configurations.all {

    ${PROTOBUF_EXCLUDE}

  }

}

`
    }

    cfg.modResults.contents = gradle
    return cfg
  })
}

function withCrustAppGradle(config: Parameters<ConfigPlugin>[0]) {
  return withAppBuildGradle(config, (cfg) => {
    let gradle = cfg.modResults.contents

    if (!gradle.includes("coreLibraryDesugaringEnabled")) {
      gradle = gradle.replace(
        /(namespace\s+['"][^'"]+['"])/,
        `$1

    compileOptions {

        coreLibraryDesugaringEnabled true

        sourceCompatibility JavaVersion.VERSION_17

        targetCompatibility JavaVersion.VERSION_17

    }`,
      )
    }

    if (!gradle.includes("coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs")) {
      gradle = gradle.replace(
        /(implementation\("com\.facebook\.react:react-android"\))/,
        `$1



    // Required by :mentra-crust (Mapbox Navigation SDK uses newer core libs).

    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.4'`,
      )
    }

    cfg.modResults.contents = gradle
    return cfg
  })
}

function withNotificationProcessGuard(config: Parameters<ConfigPlugin>[0]) {
  return withMainApplication(config, (cfg) => {
    let source = cfg.modResults.contents

    const isJava = cfg.modResults.language === "java"
    if (!source.includes(NOTIFICATION_PROCESS_GUARD)) {
      const pattern = isJava
        ? /public void onCreate\(\)\s*\{\s*super\.onCreate\(\);/
        : /override fun onCreate\(\)\s*\{\s*super\.onCreate\(\)/
      const replacement = isJava
        ? `public void onCreate() {

    super.onCreate();

    // ${NOTIFICATION_PROCESS_GUARD}

    if (com.mentra.crust.services.NotificationProcess.isCurrent(this)) {

      return;

    }`
        : `override fun onCreate() {

    super.onCreate()

    // ${NOTIFICATION_PROCESS_GUARD}

    if (com.mentra.crust.services.NotificationProcess.isCurrent(this)) {

      return

    }`

      if (!pattern.test(source)) {
        throw new Error("@mentra/crust could not add the notification-process guard to MainApplication")
      }
      source = source.replace(pattern, replacement)
    }

    if (!source.includes(NOTIFICATION_CONFIG_GUARD)) {
      const pattern = isJava
        ? /public void onConfigurationChanged\(Configuration newConfig\)\s*\{\s*super\.onConfigurationChanged\(newConfig\);/
        : /override fun onConfigurationChanged\(newConfig: Configuration\)\s*\{\s*super\.onConfigurationChanged\(newConfig\)/
      const replacement = isJava
        ? `public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);

    // ${NOTIFICATION_CONFIG_GUARD}

    if (com.mentra.crust.services.NotificationProcess.isCurrent(this)) {

      return;

    }`
        : `override fun onConfigurationChanged(newConfig: Configuration) {

    super.onConfigurationChanged(newConfig)

    // ${NOTIFICATION_CONFIG_GUARD}

    if (com.mentra.crust.services.NotificationProcess.isCurrent(this)) {

      return

    }`

      // Some custom hosts do not override onConfigurationChanged. In that case
      // there is no Expo lifecycle callback to guard.
      if (pattern.test(source)) source = source.replace(pattern, replacement)
    }

    cfg.modResults.contents = source
    return cfg
  })
}

export const withCrustAndroidBuildContract: ConfigPlugin = (config) => {
  config = withCrustKotlinVersion(config)
  config = withCrustProjectGradle(config)
  config = withCrustAppGradle(config)
  return withNotificationProcessGuard(config)
}