Skip to content

Commit

Permalink
refactor: enable strictNullChecks in tsconfig
Browse files Browse the repository at this point in the history
  • Loading branch information
arildm committed Sep 25, 2024
1 parent 1f63b5a commit a7118c8
Show file tree
Hide file tree
Showing 45 changed files with 236 additions and 213 deletions.
16 changes: 7 additions & 9 deletions app/scripts/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ korpApp.run([
s.$on("$localeChangeSuccess", () => {
// The fresh info in $locale only has the 2-letter code, not the 3-letter code that we use
// Find the configured 3-letter UI language matching the new 2-letter locale
const lang = settings["languages"]
const lang = settings.languages
.map((language) => language.value)
.find((lang3) => tmhDynamicLocaleCache.get<ILocaleService>(lang3)?.id == $locale.id)

Expand Down Expand Up @@ -237,11 +237,9 @@ korpApp.run([
<div>{{'access_partly_denied_continue' | loc:$root.lang}}</div>`,
onClose: () => {
const neededIds = loginNeededFor.map((corpus) => corpus.id)
let newIds = selectedIds.filter((corpusId) => !neededIds.includes(corpusId))
if (newIds.length == 0) {
newIds = settings["preselected_corpora"]
}
initializeCorpusSelection(newIds)
const filtered = selectedIds.filter((corpusId) => !neededIds.includes(corpusId))
const selected = filtered.length ? filtered : settings["preselected_corpora"] || []
initializeCorpusSelection(selected)
},
})
}
Expand All @@ -262,7 +260,7 @@ korpApp.run([
content: `{{'corpus_not_available' | loc:$root.lang}}`,
onClose: () => {
const validIds = selectedIds.filter((corpusId) => allCorpusIds.includes(corpusId))
const newIds = validIds.length >= 0 ? validIds : settings["preselected_corpora"]
const newIds = validIds.length ? validIds : settings["preselected_corpora"] || []
initializeCorpusSelection(newIds)
},
})
Expand All @@ -275,7 +273,7 @@ korpApp.run([

// TODO the top bar could show even though the modal is open,
// thus allowing switching modes or language when an error has occured.
s.openErrorModal = ({ content, resolvable = true, onClose = null, buttonText = null, translations = null }) => {
s.openErrorModal = ({ content, resolvable = true, onClose, buttonText, translations }) => {
type ModalScope = IScope & {
translations?: LocLangMap
closeModal: () => void
Expand Down Expand Up @@ -315,7 +313,7 @@ korpApp.run([
}

function getCorporaFromHash(): string[] {
const corpus: string = $location.search().corpus
const corpus = $location.search().corpus
return corpus ? corpus.split(",") : settings["preselected_corpora"] || []
}

Expand Down
12 changes: 7 additions & 5 deletions app/scripts/backend/base-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,13 +120,15 @@ export default abstract class BaseProxy<R extends {} = {}> {

Object.keys(struct).forEach((key) => {
if (key !== "progress_corpora" && key.split("_")[0] === "progress") {
const val = struct[key]
const currentCorpus = val["corpus"] || val
const sum = _(currentCorpus.split("|"))
const val = struct[key] as ProgressResponse["progress_0"]
const currentCorpus = typeof val == "string" ? val : val["corpus"]
const sum = currentCorpus
.split("|")
.map((corpus) => Number(settings.corpora[corpus.toLowerCase()].info.Size))
.reduce((a, b) => a + b, 0)
this.progress += sum
this.total_results += val["hits"] !== null ? parseInt(val["hits"]) : null
if (typeof val != "string" && "hits" in val)
this.total_results = (this.total_results || 0) + Number(val.hits)
}
})

Expand All @@ -143,7 +145,7 @@ export default abstract class BaseProxy<R extends {} = {}> {
this.total = _.reduce(tmp, (val1, val2) => val1 + val2, 0)
}

const stats = (this.progress / this.total) * 100
const stats = (this.progress / this.total!) * 100

this.prev = e.target.responseText
return {
Expand Down
8 changes: 4 additions & 4 deletions app/scripts/backend/graph-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Factory, httpConfAddMethod } from "@/util"

export class GraphProxy extends BaseProxy<KorpCountTimeResponse> {
granularity: Granularity
prevParams: KorpCountTimeParams
prevParams: KorpCountTimeParams | null
prevRequest: AjaxSettings

constructor() {
Expand All @@ -18,13 +18,13 @@ export class GraphProxy extends BaseProxy<KorpCountTimeResponse> {

expandSubCqps(subArray: string[]): Record<`subcqp${number}`, string> {
const padding = _.fill(new Array(subArray.length.toString().length), "0")
const result = []
const result: Record<`subcqp${number}`, string> = {}
for (let i = 0; i < subArray.length; i++) {
const cqp = subArray[i]
const p = padding.slice(i.toString().length).join("")
result.push([`subcqp${p}${i}`, cqp])
result[`subcqp${p}${i}`] = cqp
}
return _.fromPairs(result)
return result
}

makeRequest(
Expand Down
22 changes: 13 additions & 9 deletions app/scripts/backend/kwic-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,22 @@ export class KwicProxy extends BaseProxy<KorpQueryResponse> {
constructor() {
super()
this.prevRequest = null
this.queryData = null
this.queryData = undefined
this.prevParams = null
this.foundKwic = false
}

makeRequest(
options: KorpQueryRequestOptions,
page: number,
page: number | undefined,
progressCallback: (data: ProgressReport<KorpQueryResponse>) => void,
kwicCallback: (data: KorpResponse<KorpQueryResponse>) => void
): JQuery.jqXHR<KorpResponse<KorpQueryResponse>> {
const self = this
this.foundKwic = false
this.resetRequest()
if (!kwicCallback) {
console.error("No callback for query result")
return
throw new Error("No callback for query result")
}
self.progress = 0

Expand All @@ -56,13 +55,13 @@ export class KwicProxy extends BaseProxy<KorpQueryResponse> {
...options.ajaxParams,
}

const show = []
const show_struct = []
const show: string[] = []
const show_struct: string[] = []

for (let corpus of settings.corpusListing.selected) {
for (let key in corpus.within) {
// val = corpus.within[key]
show.push(_.last(key.split(" ")))
show.push(key.split(" ").pop()!)
}
for (let key in corpus.attributes) {
// val = corpus.attributes[key]
Expand Down Expand Up @@ -160,7 +159,7 @@ export type KorpQueryRequestOptions = {
// TODO Should start,end really exist here as well as under ajaxParams?
start?: number
end?: number
ajaxParams?: KorpQueryParams & {
ajaxParams: KorpQueryParams & {
command?: string
}
}
Expand All @@ -186,7 +185,7 @@ export type KorpQueryResponse = {
/** Search hits */
export type ApiKwic = {
/** An object for each token in the context, with attribute values for that token */
tokens: Record<string, any>[]
tokens: Token[]
/** Attribute values for the context (e.g. sentence) */
structs: Record<string, any>
/** Specifies the position of the match in the context. If `in_order` is false, `match` will consist of a list of match objects, one per highlighted word */
Expand All @@ -206,3 +205,8 @@ type KwicMatch = {
/** Global corpus position of the match */
position: number
}

export type Token = {
word: string
[attr: string]: any
}
4 changes: 2 additions & 2 deletions app/scripts/backend/stats-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ export class StatsProxy extends BaseProxy<KorpStatsResponse> {

makeParameters(reduceVals: string[], cqp: string, ignoreCase: boolean): KorpStatsParams {
const structAttrs = settings.corpusListing.getStructAttrs(settings.corpusListing.getReduceLang())
const groupBy = []
const groupByStruct = []
const groupBy: string[] = []
const groupByStruct: string[] = []
for (let reduceVal of reduceVals) {
if (
structAttrs[reduceVal] &&
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/backend/time-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ export class TimeProxy extends BaseProxy<KorpTimespanResponse> {
if (!years.length) {
return
}
const minYear = _.min(years)
const maxYear = _.max(years)
const minYear = Math.min(...years)!
const maxYear = Math.max(...years)!

if (_.isNaN(maxYear) || _.isNaN(minYear)) {
console.log("expandTimestruct broken, years:", years)
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/backend/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export type ProgressResponse = {
/** Selected corpora in the order they will be searched. This is returned first. */
progress_corpora?: string[]
/** Repeated for each corpus (or sometimes batch of corpora?) Hits can be 0. These are returned a few at a time. */
[progress_n: `progress${number}`]: string | { corpus: string; hits: number }
[progress_n: `progress_${number}`]: string | { corpus: string; hits: number }
}

/** Extends JQuery `jaxSettings` with stuff we use. */
Expand All @@ -42,7 +42,7 @@ export type ProgressReport<R = {}> = {
/** How many percent of the material has been searched. */
stats: number
/** How many search hits so far. */
total_results: number
total_results: number | null
}

/** A string consisting of numbers. */
Expand Down
5 changes: 3 additions & 2 deletions app/scripts/components/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@ function findAuthModule(): AuthModule | undefined {
try {
return require("custom/" + authModuleName)
} catch (error) {
console.log("Auth module not available: ", authModule)
console.error("Auth module not available: ", authModule)
}
}

const authModule = findAuthModule()
// TODO Provide dummy auth module if not found? Or produce visible crash because it's a config error.
const authModule = findAuthModule()!

export async function init(): Promise<boolean> {
const loggedIn = await authModule.init()
Expand Down
6 changes: 3 additions & 3 deletions app/scripts/components/auth/basic_auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const getAuthorizationHeader = () =>
function toBase64(str: string) {
// copied from https://stackoverflow.com/a/43271130
function u_btoa(buffer: Uint8Array | Buffer) {
const binary = []
const binary: string[] = []
const bytes = new Uint8Array(buffer)
for (let i = 0; i < bytes.byteLength; i++) {
binary.push(String.fromCharCode(bytes[i]))
Expand Down Expand Up @@ -76,7 +76,7 @@ export const login = (usr: string, pass: string, saveLogin: boolean): JQueryDefe
}

export const hasCredential = (corpusId: string): boolean =>
state.loginObj?.credentials?.includes(corpusId.toUpperCase())
state.loginObj?.credentials?.includes(corpusId.toUpperCase()) || false

export const logout = (): void => {
state.loginObj = undefined
Expand All @@ -85,6 +85,6 @@ export const logout = (): void => {

export const getCredentials = (): string[] => state.loginObj?.credentials || []

export const getUsername = () => state.loginObj.name
export const getUsername = () => state.loginObj?.name

export const isLoggedIn = () => !_.isEmpty(state.loginObj)
22 changes: 15 additions & 7 deletions app/scripts/components/auth/federatedauth/fed_auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ import { loginStatusComponent } from "./login_status"
import settings from "@/settings"
import { IModule } from "angular"

export type AuthModuleOptions = {
jwt_url: string
login_service: string
logout_service: string
}

type State = {
credentials?: string[]
otherCredentials?: string[]
Expand All @@ -27,12 +33,14 @@ type JwtPayload = {
}

const state: State = {
jwt: null,
username: null,
jwt: undefined,
username: undefined,
}

const authModule = settings.auth_module as { module: string; options: AuthModuleOptions }

export const init = async () => {
const response = await fetch(settings.auth_module["options"]?.jwt_url, {
const response = await fetch(authModule.options.jwt_url, {
headers: { accept: "text/plain" },
credentials: "include",
})
Expand All @@ -54,11 +62,11 @@ export const init = async () => {
state.username = name || email

state.credentials = Object.keys(scope.corpora || {})
.filter((id) => scope.corpora[id] > levels["READ"])
.filter((id) => (scope.corpora?.[id] || 0) > levels["READ"])
.map((id) => id.toUpperCase())

state.otherCredentials = Object.keys(scope.other || {})
.filter((id) => scope.other[id] > levels["READ"])
.filter((id) => (scope.other?.[id] || 0) > levels["READ"])
.map((id) => id.toUpperCase())

return true
Expand All @@ -73,14 +81,14 @@ export const login = () => {
// if we already tried to login, don't redirect again, to avoid infinite loops
// if (document.referrer == "") {
// }
window.location.href = `${settings["auth_module"]["options"]["login_service"]}?redirect=${window.location.href}`
window.location.href = `${authModule.options.login_service}?redirect=${window.location.href}`
}

export const getAuthorizationHeader = () => (isLoggedIn() ? { Authorization: `Bearer ${state.jwt}` } : {})

export const hasCredential = (corpusId) => getCredentials().includes(corpusId)

export const logout = () => (window.location.href = settings["auth_module"]["options"]["logout_service"])
export const logout = () => (window.location.href = authModule.options.logout_service)

export const getCredentials = () => state.credentials || []

Expand Down
4 changes: 2 additions & 2 deletions app/scripts/components/corpus-updates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export default angular.module("korpApp").component("corpusUpdates", {
// Find most recently updated corpora
$scope.recentUpdates = settings.corpusListing.corpora
.filter((corpus) => corpus.info.Updated && moment(corpus.info.Updated).isSameOrAfter(limitDate))
.sort((a, b) => b.info.Updated.localeCompare(a.info.Updated))
.sort((a, b) => b.info.Updated!.localeCompare(a.info.Updated!))
$scope.toggleExpanded(false)
}
}
Expand All @@ -59,7 +59,7 @@ export default angular.module("korpApp").component("corpusUpdates", {
$scope.expanded = to !== undefined ? to : !$scope.expanded
$scope.recentUpdatesFiltered = $scope.expanded
? $scope.recentUpdates
: $scope.recentUpdates.slice(0, $scope.LIMIT)
: $scope.recentUpdates!.slice(0, $scope.LIMIT)
}
},
],
Expand Down
2 changes: 1 addition & 1 deletion app/scripts/components/corpus_chooser/corpus-time-graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ angular.module("korpApp").component("corpusTimeGraph", {
const datasetsUndated = [
{
label: loc("corpselector_selected"),
data: {},
data: {} as Record<number, number | undefined>,
backgroundColor: "#cd5c5c",
},
{
Expand Down
4 changes: 2 additions & 2 deletions app/scripts/components/datetime-picker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ angular.module("korpApp").component("datetimePicker", {
})

$scope.handleClick = function (event) {
event.originalEvent.preventDefault()
event.originalEvent.stopPropagation()
event.originalEvent?.preventDefault()
event.originalEvent?.stopPropagation()
}
},
],
Expand Down
9 changes: 6 additions & 3 deletions app/scripts/components/extended/widgets/date-interval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,12 @@ export const dateInterval: Widget = {
function ($scope: DateIntervalScope) {
function updateIntervals() {
const moments = settings.corpusListing.getMomentInterval()
if (moments.length) {
if (moments) {
;[$scope.minDate, $scope.maxDate] = moments.map((m) => m.toDate())
} else {
const [from, to] = settings.corpusListing.getTimeInterval()
const interval = settings.corpusListing.getTimeInterval()
if (!interval) return
const [from, to] = interval
$scope.minDate = getYear(from)
$scope.maxDate = getYear(to)
}
Expand Down Expand Up @@ -112,7 +114,8 @@ export const dateInterval: Widget = {
if (!$scope.model) {
$scope.fromDate = $scope.minDate
$scope.toDate = $scope.maxDate
;[$scope.fromTime, $scope.toTime] = settings.corpusListing.getMomentInterval().map((m) => m.toDate())
const moments = settings.corpusListing.getMomentInterval()
if (moments) [$scope.fromTime, $scope.toTime] = moments.map((m) => m.toDate())
} else if ($scope.model.length === 4) {
;[$scope.fromDate, $scope.toDate] = $scope.model.slice(0, 3).map(getDate)
;[$scope.fromTime, $scope.toTime] = $scope.model.slice(2).map(getTime)
Expand Down
2 changes: 1 addition & 1 deletion app/scripts/components/header.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ angular.module("korpApp").component("header", {
}
}

$ctrl.languages = settings["languages"]
$ctrl.languages = settings.languages

$scope.$watch("lang", (newVal, oldVal) => {
// Watcher gets called with `undefined` on init.
Expand Down
Loading

0 comments on commit a7118c8

Please sign in to comment.