You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@annotator.apache.org by ra...@apache.org on 2020/07/23 06:47:35 UTC

[incubator-annotator] branch master updated (2124faa -> 35cc009)

This is an automated email from the ASF dual-hosted git repository.

randall pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git.


    from 2124faa  update yarn.lock
     new 8e24974  Get Babel module resolver working with TypeScript preset
     new 28821d6  Set up TypeScript linting with ESLint
     new 3aeb518  Do not lint the demo build output
     new e59fb15  Lint the webpack config
     new 230c0d2  Use names for inter-package references
     new 58a0421  Use a single tsconfig.json
     new 1320153  Remove JSON module resolution in TypeScript
     new d9dcd28  Fix remaining test typecheck failures
     new f348d4d  Fix lexical scope in switch case
     new 35cc009  Apply automatic lint fixes

The 10 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .eslintignore                                  |   1 +
 .eslintrc.js                                   | 122 ++++++++++++++-----------
 @types/cartesian/index.d.ts                    |   4 +-
 @types/dom-seek/index.d.ts                     |   5 +-
 babel.config.js                                |   5 +-
 package.json                                   |   7 +-
 packages/dom/package.json                      |   3 +
 packages/dom/src/css.ts                        |   6 +-
 packages/dom/src/highlight-range.ts            |  25 ++---
 packages/dom/src/range/cartesian.ts            |  21 +++--
 packages/dom/src/range/match.ts                |  10 +-
 packages/dom/src/scope.ts                      |   6 +-
 packages/dom/src/text-quote/describe.ts        |  67 +++++++++-----
 packages/dom/src/text-quote/match.ts           |   8 +-
 packages/dom/src/types.ts                      |   6 +-
 packages/dom/test/range/cartesian.test.ts      |   3 +-
 packages/dom/test/text-quote/describe-cases.ts |  15 +--
 packages/dom/test/text-quote/describe.test.ts  |  30 ++++--
 packages/dom/test/text-quote/match-cases.ts    |  76 ++++++++-------
 packages/dom/test/text-quote/match.test.ts     |  41 ++++++---
 packages/dom/test/text-quote/utils.ts          |  39 +++++---
 packages/selector/src/index.ts                 |  10 +-
 packages/selector/src/types.ts                 |  22 ++---
 test/data-model.test.ts                        |  42 +++++----
 tsconfig.json                                  |  40 +++++---
 tsconfig.tests.json                            |  15 ---
 26 files changed, 371 insertions(+), 258 deletions(-)
 delete mode 100644 tsconfig.tests.json


[incubator-annotator] 01/10: Get Babel module resolver working with TypeScript preset

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

randall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git

commit 8e249749f5648fb86f8033aa33b2a4e67e06d9c1
Author: Randall Leeds <ra...@apache.org>
AuthorDate: Wed Jul 22 21:37:49 2020 -0700

    Get Babel module resolver working with TypeScript preset
    
    Only partially load the Babel configuration when configuring the ESLint
    import plugin's resolver, since the TypeScript preset requires a
    filename to function and there is no filename available without making a
    custom resolver.
---
 .eslintrc.js | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/.eslintrc.js b/.eslintrc.js
index 3145648..32a4ec9 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -24,9 +24,9 @@ const babel = require('@babel/core');
 
 // Use the root babel.config.js for module resolution.
 // Relevant issue: tleunen/eslint-import-resolver-babel-module#89
-const babelOptions = babel.loadOptions({ cwd: __dirname });
-const babelModuleResolver = babelOptions.plugins.find(
-  ({ key }) => key === 'module-resolver',
+const babelConfig = babel.loadPartialConfig({ cwd: __dirname });
+const babelModuleResolver = babelConfig.options.plugins.find(
+  item => item.file.request === 'module-resolver',
 );
 
 module.exports = {


[incubator-annotator] 02/10: Set up TypeScript linting with ESLint

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

randall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git

commit 28821d600ad08dd9eb19cbb431497cd89b580e80
Author: Randall Leeds <ra...@apache.org>
AuthorDate: Wed Jul 22 21:47:12 2020 -0700

    Set up TypeScript linting with ESLint
---
 .eslintrc.js | 113 +++++++++++++++++++++++++++++++++++------------------------
 package.json |   5 +--
 2 files changed, 70 insertions(+), 48 deletions(-)

diff --git a/.eslintrc.js b/.eslintrc.js
index 32a4ec9..82a6833 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -31,40 +31,9 @@ const babelModuleResolver = babelConfig.options.plugins.find(
 
 module.exports = {
   root: true,
-  env: {
-    es6: true,
-    'shared-node-browser': true,
-  },
-  extends: ['eslint:recommended', 'plugin:import/recommended', 'prettier'],
-  globals: {
-    globalThis: true,
-  },
-  parser: 'babel-eslint',
-  parserOptions: {
-    ecmaVersion: 2020,
-    sourceType: 'module',
-  },
-  plugins: ['import', 'prettier'],
+  extends: ['eslint:recommended', 'prettier'],
+  plugins: ['prettier'],
   rules: {
-    'import/extensions': ['error', 'always', { ignorePackages: true }],
-    'import/first': 'error',
-    'import/newline-after-import': 'error',
-    'import/no-default-export': 'error',
-    'import/no-internal-modules': 'error',
-    'import/no-relative-parent-imports': 'error',
-    'import/order': ['error', { 'newlines-between': 'always' }],
-    'import/unambiguous': 'error',
-    'no-restricted-syntax': [
-      'error',
-      'BindExpression',
-      'ClassProperty',
-      'Decorator',
-      'DoExpression',
-      'ExportDefaultSpecifier',
-      'ExportNamespaceSpecifier',
-      'TypeAnnotation',
-      'JSXElement',
-    ],
     'prettier/prettier': [
       'error',
       {
@@ -73,11 +42,6 @@ module.exports = {
       },
     ],
   },
-  settings: {
-    'import/resolver': {
-      'babel-module': babelModuleResolver.options,
-    },
-  },
   overrides: [
     {
       files: [
@@ -88,12 +52,9 @@ module.exports = {
         'nyc.config.js',
       ],
       env: {
+        es2017: true,
         node: true,
       },
-      parser: 'espree',
-      parserOptions: {
-        sourceType: 'script',
-      },
       plugins: ['node'],
       rules: {
         'no-console': 'off',
@@ -101,19 +62,69 @@ module.exports = {
       },
     },
     {
-      files: ['web/demo/**/*.js'],
+      files: ['**/*.ts'],
       env: {
-        browser: true,
+        es2020: true,
+        'shared-node-browser': true,
+      },
+      extends: [
+        'plugin:@typescript-eslint/recommended',
+        'plugin:@typescript-eslint/recommended-requiring-type-checking',
+        'plugin:import/recommended',
+        'plugin:import/typescript',
+      ],
+      parserOptions: {
+        ecmaVersion: 2020,
+        project: ['./tsconfig.json'],
+        tsconfigRootDir: __dirname,
+      },
+      plugins: ['@typescript-eslint', 'import'],
+      rules: {
+        '@typescript-eslint/explicit-function-return-type': 'off',
+        '@typescript-eslint/no-unused-vars': [
+          'error',
+          { argsIgnorePattern: '^_' },
+        ],
+
+        'import/extensions': [
+          'error',
+          'ignorePackages',
+          {
+            ts: 'never',
+          },
+        ],
+        'import/first': 'error',
+        'import/newline-after-import': 'error',
+        'import/no-default-export': 'error',
+        'import/no-internal-modules': 'error',
+        'import/no-relative-parent-imports': 'error',
+        'import/order': ['error', { 'newlines-between': 'always' }],
+        'import/unambiguous': 'error',
+      },
+      settings: {
+        'import/resolver': {
+          'babel-module': babelModuleResolver.options,
+        },
       },
     },
     {
-      files: ['packages/*/test/**/*.js', 'test/**/*.js'],
+      files: ['**/@types/**/*.d.ts'],
+      rules: {
+        'import/no-default-export': 'off',
+        'import/unambiguous': 'off',
+      },
+    },
+    {
+      files: ['packages/*/test/**/*.ts', 'test/**/*.ts'],
       env: {
         mocha: true,
       },
       globals: {
         assert: true,
       },
+      parserOptions: {
+        project: ['./tsconfig.tests.json'],
+      },
       rules: {
         'import/no-internal-modules': [
           'error',
@@ -128,10 +139,20 @@ module.exports = {
       },
     },
     {
-      files: ['packages/dom/{src,test}/**/*.js'],
+      files: ['packages/dom/**/*.js'],
       env: {
         browser: true,
       },
     },
+    {
+      files: ['web/demo/**/*.js'],
+      env: {
+        browser: true,
+        es2020: true,
+      },
+      parserOptions: {
+        sourceType: 'module',
+      },
+    },
   ],
 };
diff --git a/package.json b/package.json
index 190cae1..e30f679 100644
--- a/package.json
+++ b/package.json
@@ -21,7 +21,7 @@
     "build:esm": "cross-env BABEL_ENV=esm yarn build:babel -d esm src",
     "build:misc": "lerna exec -- cp ../../LICENSE ../../NOTICE .",
     "clean": "lerna exec -- rimraf LICENSE NOTICE esm lib",
-    "lint": "eslint .",
+    "lint": "eslint --ext js,ts .",
     "prepare": "lerna run prepare",
     "prepublishOnly": "yarn run build",
     "start": "yarn run web:server",
@@ -42,8 +42,9 @@
     "@types/mocha": "^7.0.2",
     "@types/node-fetch": "^2.5.7",
     "@types/resolve": "^1.17.0",
+    "@typescript-eslint/eslint-plugin": "^3.7.0",
+    "@typescript-eslint/parser": "^3.7.0",
     "ajv": "^6.11.0",
-    "babel-eslint": "^10.0.3",
     "babel-loader": "^8.0.5",
     "babel-plugin-istanbul": "^6.0.0",
     "babel-plugin-module-resolver": "^4.0.0",


[incubator-annotator] 10/10: Apply automatic lint fixes

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

randall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git

commit 35cc009c32e6b06bd700cf764802b37374b6e002
Author: Randall Leeds <ra...@apache.org>
AuthorDate: Wed Jul 22 23:46:45 2020 -0700

    Apply automatic lint fixes
---
 @types/cartesian/index.d.ts                    |  4 +-
 @types/dom-seek/index.d.ts                     |  5 +-
 babel.config.js                                |  5 +-
 packages/dom/src/css.ts                        |  4 +-
 packages/dom/src/highlight-range.ts            | 25 ++++-----
 packages/dom/src/range/cartesian.ts            | 21 ++++----
 packages/dom/src/range/match.ts                |  7 +--
 packages/dom/src/scope.ts                      |  6 +--
 packages/dom/src/text-quote/describe.ts        | 65 +++++++++++++++--------
 packages/dom/src/text-quote/match.ts           |  6 ++-
 packages/dom/src/types.ts                      |  4 +-
 packages/dom/test/range/cartesian.test.ts      |  3 +-
 packages/dom/test/text-quote/describe-cases.ts | 10 ++--
 packages/dom/test/text-quote/describe.test.ts  | 30 ++++++++---
 packages/dom/test/text-quote/match-cases.ts    | 71 +++++++++++++++-----------
 packages/dom/test/text-quote/match.test.ts     | 33 ++++++++----
 packages/dom/test/text-quote/utils.ts          | 37 ++++++++++----
 packages/selector/src/index.ts                 | 10 ++--
 packages/selector/src/types.ts                 | 22 ++++----
 19 files changed, 227 insertions(+), 141 deletions(-)

diff --git a/@types/cartesian/index.d.ts b/@types/cartesian/index.d.ts
index 9fc47e3..e7ad466 100644
--- a/@types/cartesian/index.d.ts
+++ b/@types/cartesian/index.d.ts
@@ -1,3 +1,5 @@
 declare module 'cartesian' {
-  export default function cartesian<T>(list: Array<Array<T>> | { [k: string]: Array<T> }): Array<Array<T>>;
+  export default function cartesian<T>(
+    list: Array<Array<T>> | { [k: string]: Array<T> },
+  ): Array<Array<T>>;
 }
diff --git a/@types/dom-seek/index.d.ts b/@types/dom-seek/index.d.ts
index 5bc1bc2..a8d9cd7 100644
--- a/@types/dom-seek/index.d.ts
+++ b/@types/dom-seek/index.d.ts
@@ -1,3 +1,6 @@
 declare module 'dom-seek' {
-  export default function seek(iter: NodeIterator, where: number | Text): number;
+  export default function seek(
+    iter: NodeIterator,
+    where: number | Text,
+  ): number;
 }
diff --git a/babel.config.js b/babel.config.js
index 0c052cc..e020409 100644
--- a/babel.config.js
+++ b/babel.config.js
@@ -55,9 +55,6 @@ module.exports = api => {
       ...(DEV ? [['module-resolver', resolverOptions]] : []),
       ...(TEST ? ['istanbul'] : []),
     ],
-    presets: [
-      ['@babel/env', envOptions],
-      '@babel/preset-typescript',
-    ],
+    presets: [['@babel/env', envOptions], '@babel/preset-typescript'],
   };
 };
diff --git a/packages/dom/src/css.ts b/packages/dom/src/css.ts
index 124dd01..b6b212d 100644
--- a/packages/dom/src/css.ts
+++ b/packages/dom/src/css.ts
@@ -20,7 +20,9 @@
 
 import { CssSelector, Matcher } from '@annotator/selector';
 
-export function createCssSelectorMatcher(selector: CssSelector): Matcher<Document, Element> {
+export function createCssSelectorMatcher(
+  selector: CssSelector,
+): Matcher<Document, Element> {
   return async function* matchAll(scope: Document) {
     yield* scope.querySelectorAll(selector.value);
   };
diff --git a/packages/dom/src/highlight-range.ts b/packages/dom/src/highlight-range.ts
index e18a6a4..922da67 100644
--- a/packages/dom/src/highlight-range.ts
+++ b/packages/dom/src/highlight-range.ts
@@ -30,8 +30,8 @@
 // - attributes: an Object defining any attributes to be set on the wrapper elements.
 export function highlightRange(
   range: Range,
-  tagName: string = 'mark',
-  attributes: Record<string, string> = {}
+  tagName = 'mark',
+  attributes: Record<string, string> = {},
 ): () => void {
   // First put all nodes in an array (splits start and end nodes if needed)
   const nodes = textNodesInRange(range);
@@ -59,10 +59,7 @@ function textNodesInRange(range: Range): Text[] {
   if (range.collapsed) return [];
 
   // If the start or end node is a text node and only partly in the range, split it.
-  if (
-    isTextNode(range.startContainer) &&
-    range.startOffset > 0
-  ) {
+  if (isTextNode(range.startContainer) && range.startOffset > 0) {
     const endOffset = range.endOffset; // (this may get lost when the splitting the node)
     const createdNode = range.startContainer.splitText(range.startOffset);
     if (range.endContainer === range.startContainer) {
@@ -79,7 +76,8 @@ function textNodesInRange(range: Range): Text[] {
   }
 
   // Collect the text nodes.
-  const document = range.startContainer.ownerDocument || range.startContainer as Document;
+  const document =
+    range.startContainer.ownerDocument || (range.startContainer as Document);
   const walker = document.createTreeWalker(
     range.commonAncestorContainer,
     NodeFilter.SHOW_TEXT,
@@ -87,7 +85,7 @@ function textNodesInRange(range: Range): Text[] {
       acceptNode: node =>
         range.intersectsNode(node)
           ? NodeFilter.FILTER_ACCEPT
-          : NodeFilter.FILTER_REJECT
+          : NodeFilter.FILTER_REJECT,
     },
   );
   walker.currentNode = range.startContainer;
@@ -107,15 +105,18 @@ function textNodesInRange(range: Range): Text[] {
   // }
 
   const nodes: Text[] = [];
-  if (isTextNode(walker.currentNode))
-    nodes.push(walker.currentNode);
+  if (isTextNode(walker.currentNode)) nodes.push(walker.currentNode);
   while (walker.nextNode() && range.comparePoint(walker.currentNode, 0) !== 1)
     nodes.push(walker.currentNode as Text);
   return nodes;
 }
 
 // Replace [node] with <tagName ...attributes>[node]</tagName>
-function wrapNodeInHighlight(node: ChildNode, tagName: string, attributes: Record<string, string>): HTMLElement {
+function wrapNodeInHighlight(
+  node: ChildNode,
+  tagName: string,
+  attributes: Record<string, string>,
+): HTMLElement {
   const document = node.ownerDocument as Document;
   const highlightElement = document.createElement(tagName);
   Object.keys(attributes).forEach(key => {
@@ -149,5 +150,5 @@ function removeHighlight(highlightElement: HTMLElement) {
 }
 
 function isTextNode(node: Node): node is Text {
-  return node.nodeType === Node.TEXT_NODE
+  return node.nodeType === Node.TEXT_NODE;
 }
diff --git a/packages/dom/src/range/cartesian.ts b/packages/dom/src/range/cartesian.ts
index 256e313..439cd8b 100644
--- a/packages/dom/src/range/cartesian.ts
+++ b/packages/dom/src/range/cartesian.ts
@@ -20,7 +20,9 @@
 
 import cartesianArrays from 'cartesian';
 
-export async function* product<T>(...iterables: AsyncIterable<T>[]): AsyncGenerator<Array<T>, void, undefined> {
+export async function* product<T>(
+  ...iterables: AsyncIterable<T>[]
+): AsyncGenerator<Array<T>, void, undefined> {
   // We listen to all iterators in parallel, while logging all the values they
   // produce. Whenever an iterator produces a value, we produce and yield all
   // combinations of that value with the logged values from other iterators.
@@ -31,18 +33,19 @@ export async function* product<T>(...iterables: AsyncIterable<T>[]): AsyncGenera
   const logs: T[][] = iterables.map(() => []);
 
   type NumberedResultPromise = Promise<{
-    nextResult: IteratorResult<T>,
-    iterableNr: number
+    nextResult: IteratorResult<T>;
+    iterableNr: number;
   }>;
 
-  function notNull(p: NumberedResultPromise | null): p is NumberedResultPromise {
-    return p !== null
+  function notNull(
+    p: NumberedResultPromise | null,
+  ): p is NumberedResultPromise {
+    return p !== null;
   }
 
-  const nextValuePromises: Array<NumberedResultPromise | null> = iterators.map((iterator, iterableNr) =>
-    iterator
-      .next()
-      .then(
+  const nextValuePromises: Array<NumberedResultPromise | null> = iterators.map(
+    (iterator, iterableNr) =>
+      iterator.next().then(
         // Label the result with iterableNr, to know which iterable produced
         // this value after Promise.race below.
         nextResult => ({ nextResult, iterableNr }),
diff --git a/packages/dom/src/range/match.ts b/packages/dom/src/range/match.ts
index 2e30af9..9cfe529 100644
--- a/packages/dom/src/range/match.ts
+++ b/packages/dom/src/range/match.ts
@@ -21,11 +21,12 @@
 import { RangeSelector, Selector } from '@annotator/selector';
 
 import { ownerDocument } from '../scope';
-import { product } from './cartesian';
 import { DomMatcher, DomScope } from '../types';
 
+import { product } from './cartesian';
+
 export function makeCreateRangeSelectorMatcher(
-  createMatcher: <T extends Selector>(selector: T) => DomMatcher
+  createMatcher: <T extends Selector>(selector: T) => DomMatcher,
 ): (selector: RangeSelector) => DomMatcher {
   return function createRangeSelectorMatcher(selector: RangeSelector) {
     const startMatcher = createMatcher(selector.startSelector);
@@ -39,7 +40,7 @@ export function makeCreateRangeSelectorMatcher(
 
       const pairs = product(startMatches, endMatches);
 
-      for await (let [start, end] of pairs) {
+      for await (const [start, end] of pairs) {
         const result = document.createRange();
 
         result.setStart(start.endContainer, start.endOffset);
diff --git a/packages/dom/src/scope.ts b/packages/dom/src/scope.ts
index e7aec59..816bb03 100644
--- a/packages/dom/src/scope.ts
+++ b/packages/dom/src/scope.ts
@@ -21,10 +21,8 @@
 import { DomScope } from './types';
 
 export function ownerDocument(scope: DomScope): Document {
-  const node = isRange(scope)
-    ? scope.commonAncestorContainer
-    : scope;
-  return node.ownerDocument || node as Document;
+  const node = isRange(scope) ? scope.commonAncestorContainer : scope;
+  return node.ownerDocument || (node as Document);
 }
 
 export function rangeFromScope(scope: DomScope): Range {
diff --git a/packages/dom/src/text-quote/describe.ts b/packages/dom/src/text-quote/describe.ts
index eebd86d..d690013 100644
--- a/packages/dom/src/text-quote/describe.ts
+++ b/packages/dom/src/text-quote/describe.ts
@@ -41,18 +41,22 @@ export async function describeTextQuote(
 
   const result: TextQuoteSelector = { type: 'TextQuoteSelector', exact };
 
-  const { prefix, suffix } = calculateContextForDisambiguation(range, result, scope);
+  const { prefix, suffix } = calculateContextForDisambiguation(
+    range,
+    result,
+    scope,
+  );
   result.prefix = prefix;
   result.suffix = suffix;
 
-  return result
+  return result;
 }
 
 function calculateContextForDisambiguation(
   range: Range,
   selector: TextQuoteSelector,
   scope: DomScope,
-): { prefix?: string, suffix?: string } {
+): { prefix?: string; suffix?: string } {
   const exactText = selector.exact;
   const scopeText = rangeFromScope(scope).toString();
   const targetStartIndex = getRangeTextPosition(range, scope);
@@ -72,11 +76,10 @@ function calculateContextForDisambiguation(
   // would have invalidated the match.
   const affixLengthPairs: Array<[number, number]> = [];
   for (const matchStartIndex of stringMatches) {
-    const matchEndIndex = matchStartIndex + exactText.length
+    const matchEndIndex = matchStartIndex + exactText.length;
 
     // Skip the found match if it is the actual target.
-    if (matchStartIndex === targetStartIndex)
-      continue;
+    if (matchStartIndex === targetStartIndex) continue;
 
     // Count how many characters before & after them the false match and target have in common.
     const sufficientPrefixLength = charactersNeededToBeUnique(
@@ -95,29 +98,46 @@ function calculateContextForDisambiguation(
   // Find the prefix and suffix that would invalidate all mismatches, using the minimal characters
   // for prefix and suffix combined.
   const [prefixLength, suffixLength] = minimalSolution(affixLengthPairs);
-  const prefix = scopeText.substring(targetStartIndex - prefixLength, targetStartIndex);
-  const suffix = scopeText.substring(targetEndIndex, targetEndIndex + suffixLength);
+  const prefix = scopeText.substring(
+    targetStartIndex - prefixLength,
+    targetStartIndex,
+  );
+  const suffix = scopeText.substring(
+    targetEndIndex,
+    targetEndIndex + suffixLength,
+  );
   return { prefix, suffix };
 }
 
-function charactersNeededToBeUnique(target: string, impostor: string, reverse: boolean = false) {
+function charactersNeededToBeUnique(
+  target: string,
+  impostor: string,
+  reverse = false,
+) {
   // Count how many characters the two strings have in common.
   let overlap = 0;
-  const charAt = (s: string, i: number) => reverse ? s[s.length - 1 - i] : s[overlap];
-  while (overlap < target.length && charAt(target, overlap) === charAt(impostor, overlap))
+  const charAt = (s: string, i: number) =>
+    reverse ? s[s.length - 1 - i] : s[overlap];
+  while (
+    overlap < target.length &&
+    charAt(target, overlap) === charAt(impostor, overlap)
+  )
     overlap++;
-  if (overlap === target.length)
-    return Infinity; // (no substring of target can make it distinguishable from its impostor)
-  else
-    return overlap + 1;
+  if (overlap === target.length) return Infinity;
+  // (no substring of target can make it distinguishable from its impostor)
+  else return overlap + 1;
 }
 
-function minimalSolution(requirements: Array<[number, number]>): [number, number] {
+function minimalSolution(
+  requirements: Array<[number, number]>,
+): [number, number] {
   // Ensure we try solutions with an empty prefix or suffix.
   requirements.push([0, 0]);
 
   // Build all the pairs and order them by their sums.
-  const pairs = requirements.flatMap(l => requirements.map<[number, number]>(r => [l[0], r[1]]));
+  const pairs = requirements.flatMap(l =>
+    requirements.map<[number, number]>(r => [l[0], r[1]]),
+  );
   pairs.sort((a, b) => a[0] + a[1] - (b[0] + b[1]));
 
   // Find the first pair that satisfies every requirement.
@@ -143,15 +163,16 @@ function getRangeTextPosition(range: Range, scope: DomScope): number {
         // Only reveal nodes within the range
         return scopeAsRange.intersectsNode(node)
           ? NodeFilter.FILTER_ACCEPT
-          : NodeFilter.FILTER_REJECT
+          : NodeFilter.FILTER_REJECT;
       },
     },
   );
-  const scopeOffset = isTextNode(scopeAsRange.startContainer) ? scopeAsRange.startOffset : 0;
+  const scopeOffset = isTextNode(scopeAsRange.startContainer)
+    ? scopeAsRange.startOffset
+    : 0;
   if (isTextNode(range.startContainer))
     return seek(iter, range.startContainer) + range.startOffset - scopeOffset;
-  else
-    return seek(iter, firstTextNodeInRange(range)) - scopeOffset;
+  else return seek(iter, firstTextNodeInRange(range)) - scopeOffset;
 }
 
 function firstTextNodeInRange(range: Range): Text {
@@ -164,7 +185,7 @@ function firstTextNodeInRange(range: Range): Text {
         // Only reveal nodes within the range; and skip any empty text nodes.
         return range.intersectsNode(node) && node.length > 0
           ? NodeFilter.FILTER_ACCEPT
-          : NodeFilter.FILTER_REJECT
+          : NodeFilter.FILTER_REJECT;
       },
     },
   );
diff --git a/packages/dom/src/text-quote/match.ts b/packages/dom/src/text-quote/match.ts
index 04bb8a6..ed4d46d 100644
--- a/packages/dom/src/text-quote/match.ts
+++ b/packages/dom/src/text-quote/match.ts
@@ -24,7 +24,9 @@ import seek from 'dom-seek';
 import { DomScope, DomMatcher } from '../types';
 import { ownerDocument, rangeFromScope } from '../scope';
 
-export function createTextQuoteSelectorMatcher(selector: TextQuoteSelector): DomMatcher {
+export function createTextQuoteSelectorMatcher(
+  selector: TextQuoteSelector,
+): DomMatcher {
   return async function* matchAll(scope: DomScope) {
     const document = ownerDocument(scope);
     const scopeAsRange = rangeFromScope(scope);
@@ -43,7 +45,7 @@ export function createTextQuoteSelectorMatcher(selector: TextQuoteSelector): Dom
           // Only reveal nodes within the range; and skip any empty text nodes.
           return scopeAsRange.intersectsNode(node) && node.length > 0
             ? NodeFilter.FILTER_ACCEPT
-            : NodeFilter.FILTER_REJECT
+            : NodeFilter.FILTER_REJECT;
         },
       },
     );
diff --git a/packages/dom/src/types.ts b/packages/dom/src/types.ts
index bc9636e..ae16c07 100644
--- a/packages/dom/src/types.ts
+++ b/packages/dom/src/types.ts
@@ -20,6 +20,6 @@
 
 import { Matcher } from '@annotator/selector';
 
-export type DomScope = Node | Range
+export type DomScope = Node | Range;
 
-export type DomMatcher = Matcher<DomScope, Range>
+export type DomMatcher = Matcher<DomScope, Range>;
diff --git a/packages/dom/test/range/cartesian.test.ts b/packages/dom/test/range/cartesian.test.ts
index 5fd854b..937b402 100644
--- a/packages/dom/test/range/cartesian.test.ts
+++ b/packages/dom/test/range/cartesian.test.ts
@@ -19,6 +19,7 @@
  */
 
 import { assert } from 'chai';
+
 import { product } from '../../src/range/cartesian';
 
 async function* gen1() {
@@ -51,7 +52,7 @@ describe('cartesian', () => {
       ];
 
       const result: number[][] = [];
-      for await (let value of cart) {
+      for await (const value of cart) {
         result.push(value);
       }
 
diff --git a/packages/dom/test/text-quote/describe-cases.ts b/packages/dom/test/text-quote/describe-cases.ts
index 8010b46..6e38aad 100644
--- a/packages/dom/test/text-quote/describe-cases.ts
+++ b/packages/dom/test/text-quote/describe-cases.ts
@@ -24,12 +24,12 @@ import { RangeInfo } from './utils';
 
 const testCases: {
   [name: string]: {
-    html: string,
-    range: RangeInfo,
-    expected: TextQuoteSelector,
-  }
+    html: string;
+    range: RangeInfo;
+    expected: TextQuoteSelector;
+  };
 } = {
-  'simple': {
+  simple: {
     html: '<b>lorem ipsum dolor amet yada yada</b>',
     range: {
       startContainerXPath: '//b/text()',
diff --git a/packages/dom/test/text-quote/describe.test.ts b/packages/dom/test/text-quote/describe.test.ts
index f962157..47e9d68 100644
--- a/packages/dom/test/text-quote/describe.test.ts
+++ b/packages/dom/test/text-quote/describe.test.ts
@@ -19,7 +19,9 @@
  */
 
 import { assert } from 'chai';
+
 import { describeTextQuote } from '../../src/text-quote/describe';
+
 import testCases from './describe-cases';
 import testMatchCases from './match-cases';
 import { hydrateRange, evaluateXPath } from './utils';
@@ -32,7 +34,7 @@ describe('describeTextQuote', () => {
       const doc = domParser.parseFromString(html, 'text/html');
       const result = await describeTextQuote(hydrateRange(range, doc), doc);
       assert.deepEqual(result, expected);
-    })
+    });
   }
 
   it('works with custom scope', async () => {
@@ -68,13 +70,17 @@ describe('describeTextQuote', () => {
   it('works if the range equals the scope', async () => {
     const { html, range, expected } = testCases['simple'];
     const doc = domParser.parseFromString(html, 'text/html');
-    const result = await describeTextQuote(hydrateRange(range, doc), hydrateRange(range, doc));
+    const result = await describeTextQuote(
+      hydrateRange(range, doc),
+      hydrateRange(range, doc),
+    );
     assert.deepEqual(result, expected);
   });
 
   describe('inverts test cases of text quote matcher', () => {
-    const applicableTestCases = Object.entries(testMatchCases)
-      .filter(([_, { expected }]) => expected.length > 0);
+    const applicableTestCases = Object.entries(testMatchCases).filter(
+      ([_, { expected }]) => expected.length > 0,
+    );
 
     for (const [name, { html, selector, expected }] of applicableTestCases) {
       it(`case: '${name}'`, async () => {
@@ -85,9 +91,21 @@ describe('describeTextQuote', () => {
           assert.equal(result.exact, selector.exact);
           // Our result may have a different combination of prefix/suffix; only check for obvious inconsistency.
           if (selector.prefix && result.prefix)
-            assert(selector.prefix.endsWith(result.prefix.substring(result.prefix.length - selector.prefix.length)), 'Inconsistent prefixes');
+            assert(
+              selector.prefix.endsWith(
+                result.prefix.substring(
+                  result.prefix.length - selector.prefix.length,
+                ),
+              ),
+              'Inconsistent prefixes',
+            );
           if (selector.suffix && result.suffix)
-            assert(selector.suffix.startsWith(result.suffix.substring(0, selector.suffix.length)), 'Inconsistent suffixes');
+            assert(
+              selector.suffix.startsWith(
+                result.suffix.substring(0, selector.suffix.length),
+              ),
+              'Inconsistent suffixes',
+            );
         }
       });
     }
diff --git a/packages/dom/test/text-quote/match-cases.ts b/packages/dom/test/text-quote/match-cases.ts
index 9ea434b..4f23c82 100644
--- a/packages/dom/test/text-quote/match-cases.ts
+++ b/packages/dom/test/text-quote/match-cases.ts
@@ -24,12 +24,12 @@ import { RangeInfo } from './utils';
 
 const testCases: {
   [name: string]: {
-    html: string,
-    selector: TextQuoteSelector,
-    expected: RangeInfo[],
-  }
+    html: string;
+    selector: TextQuoteSelector;
+    expected: RangeInfo[];
+  };
 } = {
-  'simple': {
+  simple: {
     html: '<b>lorem ipsum dolor amet yada yada</b>',
     selector: {
       type: 'TextQuoteSelector',
@@ -105,7 +105,8 @@ const testCases: {
     ],
   },
   'text inside <head>': {
-    html: '<head><title>The title</title></head><b>lorem ipsum dolor amet yada yada</b>',
+    html:
+      '<head><title>The title</title></head><b>lorem ipsum dolor amet yada yada</b>',
     selector: {
       type: 'TextQuoteSelector',
       exact: 'title',
@@ -292,12 +293,14 @@ const testCases: {
       exact: '',
     },
     // A five character string contains six spots to find an empty string
-    expected: Array(6).fill(null).map((_, i) => ({
-      startContainerXPath: '//b/text()',
-      startOffset: i,
-      endContainerXPath: '//b/text()',
-      endOffset: i,
-    }))
+    expected: Array(6)
+      .fill(null)
+      .map((_, i) => ({
+        startContainerXPath: '//b/text()',
+        startOffset: i,
+        endContainerXPath: '//b/text()',
+        endOffset: i,
+      })),
   },
   'empty quote, with prefix': {
     html: '<b>lorem ipsum dolor amet yada yada</b>',
@@ -306,12 +309,14 @@ const testCases: {
       exact: '',
       prefix: 'dolor',
     },
-    expected: [{
-      startContainerXPath: '//b/text()',
-      startOffset: 17,
-      endContainerXPath: '//b/text()',
-      endOffset: 17,
-    }]
+    expected: [
+      {
+        startContainerXPath: '//b/text()',
+        startOffset: 17,
+        endContainerXPath: '//b/text()',
+        endOffset: 17,
+      },
+    ],
   },
   'empty quote, with suffix': {
     html: '<b>lorem ipsum dolor amet yada yada</b>',
@@ -320,12 +325,14 @@ const testCases: {
       exact: '',
       suffix: 'i',
     },
-    expected: [{
-      startContainerXPath: '//b/text()',
-      startOffset: 6,
-      endContainerXPath: '//b/text()',
-      endOffset: 6,
-    }]
+    expected: [
+      {
+        startContainerXPath: '//b/text()',
+        startOffset: 6,
+        endContainerXPath: '//b/text()',
+        endOffset: 6,
+      },
+    ],
   },
   'empty quote, with prefix and suffix': {
     html: '<b>lorem ipsum dolor amet yada yada</b>',
@@ -335,12 +342,14 @@ const testCases: {
       prefix: 'lorem ',
       suffix: 'ipsum',
     },
-    expected: [{
-      startContainerXPath: '//b/text()',
-      startOffset: 6,
-      endContainerXPath: '//b/text()',
-      endOffset: 6,
-    }]
+    expected: [
+      {
+        startContainerXPath: '//b/text()',
+        startOffset: 6,
+        endContainerXPath: '//b/text()',
+        endOffset: 6,
+      },
+    ],
   },
   'empty quote, no matches': {
     html: '<b>lorem ipsum dolor amet yada yada</b>',
@@ -350,7 +359,7 @@ const testCases: {
       prefix: 'X',
     },
     expected: [],
-  }
+  },
 };
 
 export default testCases;
diff --git a/packages/dom/test/text-quote/match.test.ts b/packages/dom/test/text-quote/match.test.ts
index 6ea5563..5fea7a3 100644
--- a/packages/dom/test/text-quote/match.test.ts
+++ b/packages/dom/test/text-quote/match.test.ts
@@ -23,13 +23,16 @@ import { TextQuoteSelector } from '@annotator/selector';
 
 import { createTextQuoteSelectorMatcher } from '../../src/text-quote/match';
 import { DomScope } from '../../src/types';
+
 import testCases from './match-cases';
 import { evaluateXPath, RangeInfo } from './utils';
 
 const domParser = new window.DOMParser();
 
 describe('createTextQuoteSelectorMatcher', () => {
-  for (const [name, { html, selector, expected }] of Object.entries(testCases)) {
+  for (const [name, { html, selector, expected }] of Object.entries(
+    testCases,
+  )) {
     it(`works for case: '${name}'`, async () => {
       const doc = domParser.parseFromString(html, 'text/html');
       await testMatcher(doc, doc, selector, expected);
@@ -182,21 +185,29 @@ async function testMatcher(
 ) {
   const matcher = createTextQuoteSelectorMatcher(selector);
   const matches = [];
-  for await (const value of matcher(scope))
-    matches.push(value);
+  for await (const value of matcher(scope)) matches.push(value);
   assert.equal(matches.length, expected.length);
   matches.forEach((match, i) => {
     const expectedRange = expected[i];
-    const expectedStartContainer = evaluateXPath(doc, expectedRange.startContainerXPath);
-    const expectedEndContainer = evaluateXPath(doc, expectedRange.endContainerXPath);
-    assert(match.startContainer === expectedStartContainer,
-      `unexpected start container: ${prettyNodeName(match.startContainer)}; `
-      + `expected ${prettyNodeName(expectedStartContainer)}`
+    const expectedStartContainer = evaluateXPath(
+      doc,
+      expectedRange.startContainerXPath,
+    );
+    const expectedEndContainer = evaluateXPath(
+      doc,
+      expectedRange.endContainerXPath,
+    );
+    assert(
+      match.startContainer === expectedStartContainer,
+      `unexpected start container: ${prettyNodeName(match.startContainer)}; ` +
+        `expected ${prettyNodeName(expectedStartContainer)}`,
     );
     assert.equal(match.startOffset, expectedRange.startOffset);
-    assert(match.endContainer === evaluateXPath(doc, expectedRange.endContainerXPath),
-      `unexpected end container: ${prettyNodeName(match.endContainer)}; `
-      + `expected ${prettyNodeName(expectedEndContainer)}`
+    assert(
+      match.endContainer ===
+        evaluateXPath(doc, expectedRange.endContainerXPath),
+      `unexpected end container: ${prettyNodeName(match.endContainer)}; ` +
+        `expected ${prettyNodeName(expectedEndContainer)}`,
     );
     assert.equal(match.endOffset, expectedRange.endOffset);
   });
diff --git a/packages/dom/test/text-quote/utils.ts b/packages/dom/test/text-quote/utils.ts
index 511a89c..9a484a9 100644
--- a/packages/dom/test/text-quote/utils.ts
+++ b/packages/dom/test/text-quote/utils.ts
@@ -18,28 +18,43 @@
  * under the License.
  */
 
-import { assert } from "chai";
+import { assert } from 'chai';
 
 // RangeInfo serialises a Range’s start and end containers as XPaths.
 export type RangeInfo = {
-  startContainerXPath: string,
-  startOffset: number,
-  endContainerXPath: string,
-  endOffset: number,
+  startContainerXPath: string;
+  startOffset: number;
+  endContainerXPath: string;
+  endOffset: number;
 };
 
 export function evaluateXPath(doc: Document, xpath: string): Node {
-  const result = doc.evaluate(xpath, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
-  const nodes = new Array(result.snapshotLength).fill(undefined).map((_, i) => result.snapshotItem(i));
-  assert.equal(nodes.length, 1,
-    `Test suite contains XPath with ${nodes.length} results instead of 1: '${xpath}'`
+  const result = doc.evaluate(
+    xpath,
+    doc,
+    null,
+    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
+  );
+  const nodes = new Array(result.snapshotLength)
+    .fill(undefined)
+    .map((_, i) => result.snapshotItem(i));
+  assert.equal(
+    nodes.length,
+    1,
+    `Test suite contains XPath with ${nodes.length} results instead of 1: '${xpath}'`,
   );
   return nodes[0] as Node;
 }
 
 export function hydrateRange(rangeInfo: RangeInfo, doc: Document): Range {
   const range = doc.createRange();
-  range.setStart(evaluateXPath(doc, rangeInfo.startContainerXPath), rangeInfo.startOffset);
-  range.setEnd(evaluateXPath(doc, rangeInfo.endContainerXPath), rangeInfo.endOffset);
+  range.setStart(
+    evaluateXPath(doc, rangeInfo.startContainerXPath),
+    rangeInfo.startOffset,
+  );
+  range.setEnd(
+    evaluateXPath(doc, rangeInfo.endContainerXPath),
+    rangeInfo.endOffset,
+  );
   return range;
 }
diff --git a/packages/selector/src/index.ts b/packages/selector/src/index.ts
index 8135f6e..b0bf9af 100644
--- a/packages/selector/src/index.ts
+++ b/packages/selector/src/index.ts
@@ -25,21 +25,23 @@ export * from './types';
 export function makeRefinable<
   // Any subtype of Selector can be made refinable; but note we limit the value
   // of refinedBy because it must also be accepted by matcherCreator.
-  TSelector extends (Selector & { refinedBy: TSelector }),
+  TSelector extends Selector & { refinedBy: TSelector },
   TScope,
   // To enable refinement, the implementation’s Match object must be usable as a
   // Scope object itself.
-  TMatch extends TScope,
+  TMatch extends TScope
 >(
   matcherCreator: (selector: TSelector) => Matcher<TScope, TMatch>,
 ): (selector: TSelector) => Matcher<TScope, TMatch> {
   return function createMatcherWithRefinement(
-    sourceSelector: TSelector
+    sourceSelector: TSelector,
   ): Matcher<TScope, TMatch> {
     const matcher = matcherCreator(sourceSelector);
 
     if (sourceSelector.refinedBy) {
-      const refiningSelector = createMatcherWithRefinement(sourceSelector.refinedBy);
+      const refiningSelector = createMatcherWithRefinement(
+        sourceSelector.refinedBy,
+      );
 
       return async function* matchAll(scope) {
         for await (const match of matcher(scope)) {
diff --git a/packages/selector/src/types.ts b/packages/selector/src/types.ts
index bf7c9d0..fc4f64b 100644
--- a/packages/selector/src/types.ts
+++ b/packages/selector/src/types.ts
@@ -19,27 +19,27 @@
  */
 
 export interface Selector {
-  refinedBy?: Selector,
+  refinedBy?: Selector;
 }
 
 export interface CssSelector extends Selector {
-  type: 'CssSelector',
-  value: string,
+  type: 'CssSelector';
+  value: string;
 }
 
 export interface TextQuoteSelector extends Selector {
-  type: 'TextQuoteSelector',
-  exact: string,
-  prefix?: string,
-  suffix?: string,
+  type: 'TextQuoteSelector';
+  exact: string;
+  prefix?: string;
+  suffix?: string;
 }
 
 export interface RangeSelector extends Selector {
-  type: 'RangeSelector',
-  startSelector: Selector,
-  endSelector: Selector,
+  type: 'RangeSelector';
+  startSelector: Selector;
+  endSelector: Selector;
 }
 
 export interface Matcher<TScope, TMatch> {
-  (scope: TScope): AsyncGenerator<TMatch, void, void>,
+  (scope: TScope): AsyncGenerator<TMatch, void, void>;
 }


[incubator-annotator] 06/10: Use a single tsconfig.json

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

randall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git

commit 58a0421e43b86f9cd44164cfaf1fdbccec525313
Author: Randall Leeds <ra...@apache.org>
AuthorDate: Wed Jul 22 23:12:23 2020 -0700

    Use a single tsconfig.json
---
 .eslintrc.js        |  3 ---
 package.json        |  2 +-
 tsconfig.json       | 45 ++++++++++++++++++++++++++-------------------
 tsconfig.tests.json | 15 ---------------
 4 files changed, 27 insertions(+), 38 deletions(-)

diff --git a/.eslintrc.js b/.eslintrc.js
index 0ef6a11..8e628eb 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -123,9 +123,6 @@ module.exports = {
       globals: {
         assert: true,
       },
-      parserOptions: {
-        project: ['./tsconfig.tests.json'],
-      },
       rules: {
         'import/no-internal-modules': [
           'error',
diff --git a/package.json b/package.json
index e30f679..4517ae5 100644
--- a/package.json
+++ b/package.json
@@ -26,7 +26,7 @@
     "prepublishOnly": "yarn run build",
     "start": "yarn run web:server",
     "test": "cross-env BABEL_ENV=test nyc mocha packages/*/test/**/*.test.[jt]s",
-    "typecheck": "tsc && tsc -p tsconfig.tests.json",
+    "typecheck": "tsc",
     "validate": "cross-env BABEL_ENV=test mocha test/**/*.test.[jt]s",
     "web:build": "webpack  --config=web/webpack.config.js --mode development",
     "web:server": "webpack-dev-server --config=web/webpack.config.js --hot --mode development"
diff --git a/tsconfig.json b/tsconfig.json
index e217eda..cdd2af5 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,23 +1,30 @@
 {
-    "compilerOptions": {
-        "baseUrl": ".",
-        "strict": true,
-        "noEmit": true,
-        "target": "ES2017",
-        "lib": [
-            "ES2020",
-            "DOM",
-            "DOM.Iterable"
-        ],
-        "moduleResolution": "Node",
-        "paths": {
-          "@annotator/*": ["packages/*/src"]
-        },
-        "typeRoots": [
-            "./@types"
-        ]
+  "compilerOptions": {
+    "allowSyntheticDefaultImports": true,
+    "baseUrl": ".",
+    "isolatedModules": true,
+    "lib": [
+      "dom",
+      "dom.iterable",
+      "es2020",
+    ],
+    "moduleResolution": "node",
+    "noEmit": true,
+    "resolveJsonModule": true,
+    "paths": {
+      "@annotator/*": ["packages/*/src"]
     },
-    "include": [
-        "packages/*/src/index.ts"
+    "strict": true,
+    "target": "es2017",
+    "typeRoots": [
+      "@types",
+      "node_modules/@types"
     ]
+  },
+  "include": [
+    "@types",
+    "packages/*/src",
+    "packages/*/test",
+    "test"
+  ]
 }
diff --git a/tsconfig.tests.json b/tsconfig.tests.json
deleted file mode 100644
index 578fb4a..0000000
--- a/tsconfig.tests.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
-    "extends": "./tsconfig.json",
-    "compilerOptions": {
-        "allowSyntheticDefaultImports": true,
-        "resolveJsonModule": true,
-        "typeRoots": [
-            "./node_modules/@types",
-            "./@types"
-        ]
-    },
-    "include": [
-        "test/**/*.ts",
-        "packages/*/test/**/*.ts"
-    ]
-}


[incubator-annotator] 04/10: Lint the webpack config

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

randall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git

commit e59fb154fe8889f76ba8a87c31fd3daa22081082
Author: Randall Leeds <ra...@apache.org>
AuthorDate: Wed Jul 22 21:58:46 2020 -0700

    Lint the webpack config
---
 .eslintrc.js | 1 +
 1 file changed, 1 insertion(+)

diff --git a/.eslintrc.js b/.eslintrc.js
index 82a6833..0ef6a11 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -50,6 +50,7 @@ module.exports = {
         'babel.config.js',
         'husky.config.js',
         'nyc.config.js',
+        'web/webpack.config.js',
       ],
       env: {
         es2017: true,


[incubator-annotator] 03/10: Do not lint the demo build output

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

randall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git

commit 3aeb51876754e1596c639176fa46dd64af2b7818
Author: Randall Leeds <ra...@apache.org>
AuthorDate: Wed Jul 22 21:58:26 2020 -0700

    Do not lint the demo build output
---
 .eslintignore | 1 +
 1 file changed, 1 insertion(+)

diff --git a/.eslintignore b/.eslintignore
index 24dc1ae..b3bf706 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -4,3 +4,4 @@
 /packages/*/esm/*
 /packages/*/lib/*
 /packages/*/node_modules/*
+/web/dist


[incubator-annotator] 05/10: Use names for inter-package references

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

randall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git

commit 230c0d22394afa023f2a0fa9be7d04392e9853ba
Author: Randall Leeds <ra...@apache.org>
AuthorDate: Wed Jul 22 22:26:41 2020 -0700

    Use names for inter-package references
---
 packages/dom/package.json                      | 3 +++
 packages/dom/src/css.ts                        | 2 +-
 packages/dom/src/range/match.ts                | 3 ++-
 packages/dom/src/text-quote/describe.ts        | 2 +-
 packages/dom/src/text-quote/match.ts           | 2 +-
 packages/dom/src/types.ts                      | 2 +-
 packages/dom/test/text-quote/describe-cases.ts | 5 +++--
 packages/dom/test/text-quote/match-cases.ts    | 5 +++--
 packages/dom/test/text-quote/match.test.ts     | 3 ++-
 tsconfig.json                                  | 4 ++++
 10 files changed, 21 insertions(+), 10 deletions(-)

diff --git a/packages/dom/package.json b/packages/dom/package.json
index 4f0baed..c64f7ce 100644
--- a/packages/dom/package.json
+++ b/packages/dom/package.json
@@ -17,6 +17,9 @@
     "core-js": "^3.6.4",
     "dom-seek": "^5.1.0"
   },
+  "devDependencies": {
+    "@annotator/selector": "^0.1.0"
+  },
   "engines": {
     "node": ">=10.0.0"
   },
diff --git a/packages/dom/src/css.ts b/packages/dom/src/css.ts
index 004158c..124dd01 100644
--- a/packages/dom/src/css.ts
+++ b/packages/dom/src/css.ts
@@ -18,7 +18,7 @@
  * under the License.
  */
 
-import { CssSelector, Matcher } from "../../selector/src";
+import { CssSelector, Matcher } from '@annotator/selector';
 
 export function createCssSelectorMatcher(selector: CssSelector): Matcher<Document, Element> {
   return async function* matchAll(scope: Document) {
diff --git a/packages/dom/src/range/match.ts b/packages/dom/src/range/match.ts
index e540d5c..2e30af9 100644
--- a/packages/dom/src/range/match.ts
+++ b/packages/dom/src/range/match.ts
@@ -18,9 +18,10 @@
  * under the License.
  */
 
+import { RangeSelector, Selector } from '@annotator/selector';
+
 import { ownerDocument } from '../scope';
 import { product } from './cartesian';
-import { RangeSelector, Selector } from '../../../selector/src/types';
 import { DomMatcher, DomScope } from '../types';
 
 export function makeCreateRangeSelectorMatcher(
diff --git a/packages/dom/src/text-quote/describe.ts b/packages/dom/src/text-quote/describe.ts
index 15749c9..eebd86d 100644
--- a/packages/dom/src/text-quote/describe.ts
+++ b/packages/dom/src/text-quote/describe.ts
@@ -19,8 +19,8 @@
  */
 
 import seek from 'dom-seek';
+import { TextQuoteSelector } from '@annotator/selector';
 
-import { TextQuoteSelector } from '../../../selector/src';
 import { DomScope } from '../types';
 import { ownerDocument, rangeFromScope } from '../scope';
 
diff --git a/packages/dom/src/text-quote/match.ts b/packages/dom/src/text-quote/match.ts
index 18b077e..04bb8a6 100644
--- a/packages/dom/src/text-quote/match.ts
+++ b/packages/dom/src/text-quote/match.ts
@@ -18,9 +18,9 @@
  * under the License.
  */
 
+import { TextQuoteSelector } from '@annotator/selector';
 import seek from 'dom-seek';
 
-import { TextQuoteSelector } from '../../../selector/src';
 import { DomScope, DomMatcher } from '../types';
 import { ownerDocument, rangeFromScope } from '../scope';
 
diff --git a/packages/dom/src/types.ts b/packages/dom/src/types.ts
index 040aa56..bc9636e 100644
--- a/packages/dom/src/types.ts
+++ b/packages/dom/src/types.ts
@@ -18,7 +18,7 @@
  * under the License.
  */
 
-import { Matcher } from '../../selector/src';
+import { Matcher } from '@annotator/selector';
 
 export type DomScope = Node | Range
 
diff --git a/packages/dom/test/text-quote/describe-cases.ts b/packages/dom/test/text-quote/describe-cases.ts
index 129804d..8010b46 100644
--- a/packages/dom/test/text-quote/describe-cases.ts
+++ b/packages/dom/test/text-quote/describe-cases.ts
@@ -18,8 +18,9 @@
  * under the License.
  */
 
-import { TextQuoteSelector } from "../../../selector/src";
-import { RangeInfo } from "./utils";
+import { TextQuoteSelector } from '@annotator/selector';
+
+import { RangeInfo } from './utils';
 
 const testCases: {
   [name: string]: {
diff --git a/packages/dom/test/text-quote/match-cases.ts b/packages/dom/test/text-quote/match-cases.ts
index 1748d1d..9ea434b 100644
--- a/packages/dom/test/text-quote/match-cases.ts
+++ b/packages/dom/test/text-quote/match-cases.ts
@@ -18,8 +18,9 @@
  * under the License.
  */
 
-import { TextQuoteSelector } from "../../../selector/src";
-import { RangeInfo } from "./utils";
+import { TextQuoteSelector } from '@annotator/selector';
+
+import { RangeInfo } from './utils';
 
 const testCases: {
   [name: string]: {
diff --git a/packages/dom/test/text-quote/match.test.ts b/packages/dom/test/text-quote/match.test.ts
index 3148a3f..4df937a 100644
--- a/packages/dom/test/text-quote/match.test.ts
+++ b/packages/dom/test/text-quote/match.test.ts
@@ -19,8 +19,9 @@
  */
 
 import { assert } from 'chai';
+import { TextQuoteSelector } from '@annotator/selector';
+
 import { createTextQuoteSelectorMatcher } from '../../src/text-quote/match';
-import { TextQuoteSelector } from '../../../selector/src/types';
 import { DomScope } from '../../src/types';
 import testCases from './match-cases';
 import { evaluateXPath, RangeInfo } from './utils';
diff --git a/tsconfig.json b/tsconfig.json
index 49400f2..e217eda 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,5 +1,6 @@
 {
     "compilerOptions": {
+        "baseUrl": ".",
         "strict": true,
         "noEmit": true,
         "target": "ES2017",
@@ -9,6 +10,9 @@
             "DOM.Iterable"
         ],
         "moduleResolution": "Node",
+        "paths": {
+          "@annotator/*": ["packages/*/src"]
+        },
         "typeRoots": [
             "./@types"
         ]


[incubator-annotator] 07/10: Remove JSON module resolution in TypeScript

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

randall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git

commit 1320153ef3192d20f193cc5c9386f8bd6ee06a75
Author: Randall Leeds <ra...@apache.org>
AuthorDate: Wed Jul 22 23:13:24 2020 -0700

    Remove JSON module resolution in TypeScript
    
    Until JSON modules are not experimental in Node, avoid using them to
    avoid creating broken ESM packages.
---
 .eslintrc.js            |  5 +----
 test/data-model.test.ts | 42 ++++++++++++++++++++++++------------------
 tsconfig.json           |  1 -
 3 files changed, 25 insertions(+), 23 deletions(-)

diff --git a/.eslintrc.js b/.eslintrc.js
index 8e628eb..f8e4f1e 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -127,10 +127,7 @@ module.exports = {
         'import/no-internal-modules': [
           'error',
           {
-            allow: [
-              'ajv/lib/refs/json-schema-draft-04.json',
-              path.resolve(__dirname, './packages/*/src/**'),
-            ],
+            allow: [path.resolve(__dirname, './packages/*/src/**')],
           },
         ],
         'import/no-relative-parent-imports': 'off',
diff --git a/test/data-model.test.ts b/test/data-model.test.ts
index c52f4e1..b5661a5 100644
--- a/test/data-model.test.ts
+++ b/test/data-model.test.ts
@@ -24,7 +24,6 @@ import fs from 'fs';
 import { URL } from 'url';
 
 import Ajv from 'ajv';
-import META_SCHEMA from 'ajv/lib/refs/json-schema-draft-04.json';
 import { assert } from 'chai';
 import fetch from 'node-fetch';
 import resolve from 'resolve';
@@ -45,11 +44,10 @@ process.argv.forEach((val, index) => {
   }
 });
 
-function readSchema(schemaPath: string, base: string = 'web-annotation-tests/'): any {
-  const resolverOptions = { extensions: ['.json', '.test'] };
-  const resolvedPath = resolve.sync(`${base}${schemaPath}`, resolverOptions);
-  const schemaUnparsed = fs.readFileSync(resolvedPath);
-  return JSON.parse(schemaUnparsed.toString());
+function requireJSON(name: string): Record<string, unknown> {
+  const resolvedPath = resolve.sync(name);
+  const data = fs.readFileSync(resolvedPath).toString();
+  return JSON.parse(data) as Record<string, unknown>;
 }
 
 const DEFINITIONS = [
@@ -60,40 +58,48 @@ const DEFINITIONS = [
   'id',
   'otherProperties',
   'specificResource',
-].map(name => readSchema(`definitions/${name}`));
+].map(name => requireJSON(`web-annotation-tests/definitions/${name}.json`));
 
-const MUSTS = readSchema('annotations/annotationMusts');
+const MUSTS = requireJSON(
+  'web-annotation-tests/annotations/annotationMusts.test',
+);
 
-const ajv = new Ajv({ schemaId: 'auto' });
+const META_SCHEMA = requireJSON('ajv/lib/refs/json-schema-draft-04.json');
+
+const ajv = new Ajv({ schemaId: 'auto', meta: false });
 ajv.addMetaSchema(META_SCHEMA);
 DEFINITIONS.forEach(schema => ajv.addSchema(schema));
 
 describe('Test JSON against Schemas', () => {
-  let data = '';
+  let data: Record<string, unknown>;
 
   before(async function() {
     if (!found_url) {
       this.skip();
     } else {
       // load the data from the file or URL
-      let url_parsed = new URL(url);
+      const url_parsed = new URL(url);
       if (url_parsed.pathname !== url_parsed.href) {
         const data_response = await fetch(url_parsed.href);
-        data = await data_response.json();
+        data = (await data_response.json()) as Record<string, unknown>;
       } else {
         // assume we have a local file and use that
-        data = JSON.parse(fs.readFileSync(url_parsed.pathname, 'utf8'));
+        data = JSON.parse(
+          fs.readFileSync(url_parsed.pathname, 'utf8'),
+        ) as Record<string, unknown>;
       }
-      if (data === '') {
+
+      if (!data) {
         this.skip();
       }
     }
   });
 
-  MUSTS.assertions.forEach((schemaPath: string) => {
-    const schema = readSchema(schemaPath);
-    it(schema.title, () => {
-      let valid = ajv.validate(schema, data);
+  const assertions = MUSTS.assertions as [string];
+  assertions.forEach((schemaPath: string) => {
+    const schema = requireJSON(`web-annotation-tests/${schemaPath}`);
+    it(schema.title as string, () => {
+      const valid = ajv.validate(schema, data);
       assert.isOk(valid, ajv.errorsText());
     });
   });
diff --git a/tsconfig.json b/tsconfig.json
index cdd2af5..f37c6c5 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -10,7 +10,6 @@
     ],
     "moduleResolution": "node",
     "noEmit": true,
-    "resolveJsonModule": true,
     "paths": {
       "@annotator/*": ["packages/*/src"]
     },


[incubator-annotator] 08/10: Fix remaining test typecheck failures

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

randall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git

commit d9dcd289357c27e85d92db980cbf7b7ac85e1d09
Author: Randall Leeds <ra...@apache.org>
AuthorDate: Wed Jul 22 23:16:52 2020 -0700

    Fix remaining test typecheck failures
---
 packages/dom/test/text-quote/match.test.ts | 2 +-
 packages/dom/test/text-quote/utils.ts      | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/packages/dom/test/text-quote/match.test.ts b/packages/dom/test/text-quote/match.test.ts
index 4df937a..78ef7a5 100644
--- a/packages/dom/test/text-quote/match.test.ts
+++ b/packages/dom/test/text-quote/match.test.ts
@@ -205,7 +205,7 @@ async function testMatcher(
 function prettyNodeName(node: Node) {
   switch (node.nodeType) {
     case Node.TEXT_NODE:
-      const text = (node as Text).nodeValue;
+      const text = (node as Text).nodeValue || '';
       return `#text "${text.length > 50 ? text.substring(0, 50) + '…' : text}"`;
     case Node.ELEMENT_NODE:
       return `<${(node as Element).tagName.toLowerCase()}>`;
diff --git a/packages/dom/test/text-quote/utils.ts b/packages/dom/test/text-quote/utils.ts
index a59fb06..511a89c 100644
--- a/packages/dom/test/text-quote/utils.ts
+++ b/packages/dom/test/text-quote/utils.ts
@@ -34,7 +34,7 @@ export function evaluateXPath(doc: Document, xpath: string): Node {
   assert.equal(nodes.length, 1,
     `Test suite contains XPath with ${nodes.length} results instead of 1: '${xpath}'`
   );
-  return nodes[0];
+  return nodes[0] as Node;
 }
 
 export function hydrateRange(rangeInfo: RangeInfo, doc: Document): Range {


[incubator-annotator] 09/10: Fix lexical scope in switch case

Posted by ra...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

randall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-annotator.git

commit f348d4dd87d362708157b3164be828eba6c766b4
Author: Randall Leeds <ra...@apache.org>
AuthorDate: Wed Jul 22 23:45:56 2020 -0700

    Fix lexical scope in switch case
---
 packages/dom/test/text-quote/match.test.ts | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/packages/dom/test/text-quote/match.test.ts b/packages/dom/test/text-quote/match.test.ts
index 78ef7a5..6ea5563 100644
--- a/packages/dom/test/text-quote/match.test.ts
+++ b/packages/dom/test/text-quote/match.test.ts
@@ -204,9 +204,10 @@ async function testMatcher(
 
 function prettyNodeName(node: Node) {
   switch (node.nodeType) {
-    case Node.TEXT_NODE:
+    case Node.TEXT_NODE: {
       const text = (node as Text).nodeValue || '';
       return `#text "${text.length > 50 ? text.substring(0, 50) + '…' : text}"`;
+    }
     case Node.ELEMENT_NODE:
       return `<${(node as Element).tagName.toLowerCase()}>`;
     default: