Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix and improve types #106

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,18 @@ module.exports = {
plugins: [
'@typescript-eslint',
],
parserOptions: {
project: './tsconfig.json'
},
extends: [
// See https://github.com/standard/eslint-config-standard/blob/master/eslintrc.json
'standard',
'standard-with-typescript',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
'array-bracket-spacing': [ 'error', 'always' ],
'arrow-parens': [ 'error', 'as-needed' ],
'comma-dangle': 'off',
'@typescript-eslint/comma-dangle': [ 'error', 'always-multiline' ],
eqeqeq: [ 'error', 'smart' ],
'implicit-arrow-linebreak': [ 'error', 'beside' ],
Expand All @@ -36,28 +38,26 @@ module.exports = {
alphabetize: { order: 'asc' },
},
],
'indent': 'off',
'@typescript-eslint/indent': [ 'error', 2, { MemberExpression: 'off' } ],
'no-var': [ 'error' ],
// Primarily to avoid false positive with interfaces declarations
// See https://github.com/typescript-eslint/typescript-eslint/issues/1262
'no-use-before-define': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'nonblock-statement-body-position': [ 'error', 'beside' ],
'object-curly-spacing': 'off',
'@typescript-eslint/object-curly-spacing': [ 'error', 'always' ],
'object-shorthand': [ 'error', 'properties' ],
'prefer-arrow-callback': [ 'error' ],
'prefer-const': [ 'error' ],
'prefer-rest-params': 'off',

// TODO remove (= enable these lints and fix the issues)
'@typescript-eslint/ban-ts-comment': [ 'error', {
'ts-expect-error': false, // TODO: "allow-with-description",
'ts-nocheck': false,
} ],
'@typescript-eslint/consistent-type-imports': [ 'error', { prefer: 'type-imports' } ],
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
semi: 'off',
'@typescript-eslint/semi': [ 'error', 'never' ],
'@typescript-eslint/restrict-plus-operands': 'off',
'@typescript-eslint/restrict-template-expressions': 'off',

// Enable when strict or strictNullChecks is enabled in tsconfig
'@typescript-eslint/prefer-nullish-coalescing': 'off',
'@typescript-eslint/strict-boolean-expressions': 'off',
},
globals: {
// Mocha globals
Expand Down
30 changes: 29 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
"@typescript-eslint/parser": "^5.49.0",
"@vercel/git-hooks": "^1.0.0",
"eslint": "^8.32.0",
"eslint-config-standard": "^17.0.0",
"eslint-config-standard-with-typescript": "^34.0.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-n": "^15.6.1",
"eslint-plugin-promise": "^6.1.1",
Expand Down
7 changes: 3 additions & 4 deletions scripts/compare_datatypes.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#!/usr/bin/env ts-node
import { kebabCase } from 'lodash-es'
import { red, green } from 'tiny-chalk'
import { parsers } from '../src/helpers/parse_claim.js'
import { DataTypes } from '../src/types/claim.js'
import { isOfType } from '../src/utils/utils.js'
import { readJsonFile } from '../tests/lib/utils.js'

const supportedTypes = Object.keys(parsers)

const allDatatypes = readJsonFile('/tmp/all_wikidata_datatypes.json') as string[]
allDatatypes
.map(typeUri => {
Expand All @@ -15,7 +14,7 @@ allDatatypes
return kebabCase(typeName)
})
.forEach(type => {
if (supportedTypes.includes(type)) {
if (isOfType(DataTypes, type)) {
console.log(green('ok'), type)
} else {
console.error(red('unsupported type'), type)
Expand Down
80 changes: 4 additions & 76 deletions src/helpers/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { wikibaseTimeToDateObject as toDateObject } from './wikibase_time_to_date_object.js'
import type {
EntityId,
EntityPageTitle,
Expand All @@ -23,18 +22,18 @@ function isIdBuilder<T extends string> (regex: { readonly source: string, readon
}

export const isNumericId = isIdBuilder<NumericId>(/^[1-9][0-9]*$/)
export const isEntityId = isIdBuilder<EntityId>(/^((Q|P|L|M)[1-9][0-9]*|L[1-9][0-9]*-(F|S)[1-9][0-9]*)$/)
export const isEntityId = isIdBuilder<EntityId>(/^((Q|P|L|M|E)[1-9][0-9]*|L[1-9][0-9]*-(F|S)[1-9][0-9]*)$/)
export const isEntitySchemaId = isIdBuilder<EntitySchemaId>(/^E[1-9][0-9]*$/)
export const isItemId = isIdBuilder<ItemId>(/^Q[1-9][0-9]*$/)
export const isPropertyId = isIdBuilder<PropertyId>(/^P[1-9][0-9]*$/)
export const isLexemeId = isIdBuilder<LexemeId>(/^L[1-9][0-9]*$/)
export const isFormId = isIdBuilder<FormId>(/^L[1-9][0-9]*-F[1-9][0-9]*$/)
export const isSenseId = isIdBuilder<SenseId>(/^L[1-9][0-9]*-S[1-9][0-9]*$/)
export const isMediaInfoId = isIdBuilder<MediaInfoId>(/^M[1-9][0-9]*$/)
export const isGuid = isIdBuilder<Guid>(/^((Q|P|L|M)[1-9][0-9]*|L[1-9][0-9]*-(F|S)[1-9][0-9]*)\$[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)
export const isGuid = isIdBuilder<Guid>(/^((Q|P|L|M|E)[1-9][0-9]*|L[1-9][0-9]*-(F|S)[1-9][0-9]*)\$[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)
export const isHash = isIdBuilder<Hash>(/^[0-9a-f]{40}$/)
export const isRevisionId = isIdBuilder<RevisionId>(/^\d+$/)
export const isNonNestedEntityId = isIdBuilder<NonNestedEntityId>(/^(Q|P|L|M)[1-9][0-9]*$/)
export const isNonNestedEntityId = isIdBuilder<NonNestedEntityId>(/^(Q|P|L|M|E)[1-9][0-9]*$/)

export function isPropertyClaimsId (id: string): id is PropertyClaimsId {
if (typeof id !== 'string') return false
Expand Down Expand Up @@ -62,80 +61,9 @@ export function isEntityPageTitle (title: string): title is EntityPageTitle {

export function getNumericId (id: string): NumericId {
if (!isNonNestedEntityId(id)) throw new Error(`invalid entity id: ${id}`)
return id.replace(/^(Q|P|L|M)/, '') as NumericId
return id.replace(/^(Q|P|L|M|E)/, '') as NumericId
}

export interface WikibaseTimeObject {
time: string
precision: number
}

export type TimeInputValue = string | WikibaseTimeObject

type TimeFunction<T> = (wikibaseTime: TimeInputValue) => T

// Try to parse the date or return the input
function bestEffort<T> (fn: TimeFunction<T>) {
return (value: TimeInputValue) => {
try {
return fn(value)
} catch {
value = typeof value === 'string' ? value : value.time

const sign = value[0]
let [ yearMonthDay, withinDay ] = value.slice(1).split('T')
if (!sign || !yearMonthDay || !withinDay) {
throw new Error('TimeInput is invalid: ' + JSON.stringify(value))
}

yearMonthDay = yearMonthDay.replace(/-00/g, '-01')

return `${sign}${yearMonthDay}T${withinDay}`
}
}
}

const toEpochTime = (wikibaseTime: TimeInputValue) => toDateObject(wikibaseTime).getTime()
const toISOString = (wikibaseTime: TimeInputValue) => toDateObject(wikibaseTime).toISOString()

// A date format that knows just three precisions:
// 'yyyy', 'yyyy-mm', and 'yyyy-mm-dd' (including negative and non-4 digit years)
// Should be able to handle the old and the new Wikidata time:
// - in the old one, units below the precision where set to 00
// - in the new one, those months and days are set to 01 in those cases,
// so when we can access the full claim object, we check the precision
// to recover the old format
const toSimpleDay = (wikibaseTime: TimeInputValue): string => {
// Also accept claim datavalue.value objects, and actually prefer those,
// as we can check the precision
if (typeof wikibaseTime === 'object') {
const { time, precision } = wikibaseTime
// Year precision
if (precision === 9) wikibaseTime = time.replace('-01-01T', '-00-00T')
// Month precision
else if (precision === 10) wikibaseTime = time.replace('-01T', '-00T')
else wikibaseTime = time
}

return wikibaseTime.split('T')[0]
// Remove positive years sign
.replace(/^\+/, '')
// Remove years padding zeros
.replace(/^(-?)0+/, '$1')
// Remove days if not included in the Wikidata date precision
.replace(/-00$/, '')
// Remove months if not included in the Wikidata date precision
.replace(/-00$/, '')
}

export const wikibaseTimeToEpochTime = bestEffort(toEpochTime)

export const wikibaseTimeToISOString = bestEffort(toISOString)

export const wikibaseTimeToSimpleDay = bestEffort(toSimpleDay)

export const wikibaseTimeToDateObject = toDateObject

export function getImageUrl (filename: string, width?: number): Url {
let url = `https://commons.wikimedia.org/wiki/Special:FilePath/${filename}`
if (typeof width === 'number') url += `?width=${width}`
Expand Down
Loading