larry babby and threejs for glsl

This commit is contained in:
Sam
2024-06-24 21:24:00 +12:00
parent 87d5dc634d
commit 907ebae4c0
6474 changed files with 1279596 additions and 8 deletions

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017-present Devon Govett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,154 @@
import type { Mapping } from "@mischnic/json-sourcemap";
/** These positions are 1-based (so <code>1</code> is the first line/column) */
export type DiagnosticHighlightLocation = {
readonly line: number;
readonly column: number;
};
export type DiagnosticSeverity = "error" | "warn" | "info";
/**
* Note: A tab character is always counted as a single character
* This is to prevent any mismatch of highlighting across machines
*/
export type DiagnosticCodeHighlight = {
/** Location of the first character that should get highlighted for this highlight. */
start: DiagnosticHighlightLocation;
/** Location of the last character that should get highlighted for this highlight. */
end: DiagnosticHighlightLocation;
/** A message that should be displayed at this location in the code (optional). */
message?: string;
};
/**
* Describes how to format a code frame.
* A code frame is a visualization of a piece of code with a certain amount of
* code highlights that point to certain chunk(s) inside the code.
*/
export type DiagnosticCodeFrame = {
/**
* The contents of the source file.
*
* If no code is passed, it will be read in from filePath, remember that
* the asset's current code could be different from the input contents.
*
*/
code?: string;
/** Path to the file this code frame is about (optional, absolute or relative to the project root) */
filePath?: string;
/** Language of the file this code frame is about (optional) */
language?: string;
codeHighlights: Array<DiagnosticCodeHighlight>;
};
/**
* A style agnostic way of emitting errors, warnings and info.
* Reporters are responsible for rendering the message, codeframes, hints, ...
*/
export type Diagnostic = {
/** This is the message you want to log. */
message: string;
/** Name of plugin or file that threw this error */
origin?: string;
/** A stacktrace of the error (optional) */
stack?: string;
/** Name of the error (optional) */
name?: string;
/** A code frame points to a certain location(s) in the file this diagnostic is linked to (optional) */
codeFrames?: Array<DiagnosticCodeFrame> | null | undefined;
/** An optional list of strings that suggest ways to resolve this issue */
hints?: Array<string>;
/** @private */
skipFormatting?: boolean;
/** A URL to documentation to learn more about the diagnostic. */
documentationURL?: string;
};
export interface PrintableError extends Error {
fileName?: string;
filePath?: string;
codeFrame?: string;
highlightedCodeFrame?: string;
loc?: {
column: number;
line: number;
} | null | undefined;
source?: string;
}
export type DiagnosticWithoutOrigin = Diagnostic & {
origin?: string;
};
/** Something that can be turned into a diagnostic. */
export type Diagnostifiable = Diagnostic | Array<Diagnostic> | ThrowableDiagnostic | PrintableError | Error | string;
/** Normalize the given value into a diagnostic. */
export declare function anyToDiagnostic(input: Diagnostifiable): Array<Diagnostic>;
/** Normalize the given error into a diagnostic. */
export declare function errorToDiagnostic(error: ThrowableDiagnostic | PrintableError | string, defaultValues?: {
origin?: string | null | undefined;
filePath?: string | null | undefined;
}): Array<Diagnostic>;
type ThrowableDiagnosticOpts = {
diagnostic: Diagnostic | Array<Diagnostic>;
};
/**
* An error wrapper around a diagnostic that can be <code>throw</code>n (e.g. to signal a
* build error).
*/
export default class ThrowableDiagnostic extends Error {
diagnostics: Array<Diagnostic>;
constructor(opts: ThrowableDiagnosticOpts);
}
/**
* Turns a list of positions in a JSON5 file with messages into a list of diagnostics.
* Uses <a href="https://github.com/mischnic/json-sourcemap">@mischnic/json-sourcemap</a>.
*
* @param code the JSON code
* @param ids A list of JSON keypaths (<code>key: "/some/parent/child"</code>) with corresponding messages, \
* <code>type</code> signifies whether the key of the value in a JSON object should be highlighted.
*/
export declare function generateJSONCodeHighlights(data: string | {
data: unknown;
pointers: Record<string, Mapping>;
}, ids: Array<{
key: string;
type?: ("key" | null | undefined) | "value";
message?: string;
}>): Array<DiagnosticCodeHighlight>;
/**
* Converts entries in <a href="https://github.com/mischnic/json-sourcemap">@mischnic/json-sourcemap</a>'s
* <code>result.pointers</code> array.
*/
export declare function getJSONHighlightLocation(pos: Mapping, type?: ("key" | null | undefined) | "value"): {
start: DiagnosticHighlightLocation;
end: DiagnosticHighlightLocation;
};
/** Result is 1-based, but end is exclusive */
export declare function getJSONSourceLocation(pos: Mapping, type?: ("key" | null | undefined) | "value"): {
start: {
readonly line: number;
readonly column: number;
};
end: {
readonly line: number;
readonly column: number;
};
};
export declare function convertSourceLocationToHighlight<Location extends {
/** 1-based, inclusive */
readonly start: {
readonly line: number;
readonly column: number;
};
/** 1-based, exclusive */
readonly end: {
readonly line: number;
readonly column: number;
};
}>({ start, end }: Location, message?: string): DiagnosticCodeHighlight;
/** Sanitizes object keys before using them as <code>key</code> in generateJSONCodeHighlights */
export declare function encodeJSONKeyComponent(component: string): string;
export declare function escapeMarkdown(s: string): string;
type TemplateInput = any;
export declare function md(strings: Array<string>, ...params: Array<TemplateInput>): string;
export declare namespace md {
var bold: (s: any) => any;
var italic: (s: any) => any;
var underline: (s: any) => any;
var strikethrough: (s: any) => any;
}
export {};

View File

@@ -0,0 +1,290 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.anyToDiagnostic = anyToDiagnostic;
exports.convertSourceLocationToHighlight = convertSourceLocationToHighlight;
exports.default = void 0;
exports.encodeJSONKeyComponent = encodeJSONKeyComponent;
exports.errorToDiagnostic = errorToDiagnostic;
exports.escapeMarkdown = escapeMarkdown;
exports.generateJSONCodeHighlights = generateJSONCodeHighlights;
exports.getJSONHighlightLocation = getJSONHighlightLocation;
exports.getJSONSourceLocation = getJSONSourceLocation;
exports.md = md;
function _assert() {
const data = _interopRequireDefault(require("assert"));
_assert = function () {
return data;
};
return data;
}
function _nullthrows() {
const data = _interopRequireDefault(require("nullthrows"));
_nullthrows = function () {
return data;
};
return data;
}
function _jsonSourcemap() {
const data = require("@mischnic/json-sourcemap");
_jsonSourcemap = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/** These positions are 1-based (so <code>1</code> is the first line/column) */
/**
* Note: A tab character is always counted as a single character
* This is to prevent any mismatch of highlighting across machines
*/
/**
* Describes how to format a code frame.
* A code frame is a visualization of a piece of code with a certain amount of
* code highlights that point to certain chunk(s) inside the code.
*/
/**
* A style agnostic way of emitting errors, warnings and info.
* Reporters are responsible for rendering the message, codeframes, hints, ...
*/
// This type should represent all error formats Parcel can encounter...
/** Something that can be turned into a diagnostic. */
/** Normalize the given value into a diagnostic. */
function anyToDiagnostic(input) {
if (Array.isArray(input)) {
return input;
} else if (input instanceof ThrowableDiagnostic) {
return input.diagnostics;
} else if (input instanceof Error) {
return errorToDiagnostic(input);
} else if (typeof input === 'string') {
return [{
message: input
}];
} else if (typeof input === 'object') {
return [input];
} else {
return errorToDiagnostic(input);
}
}
/** Normalize the given error into a diagnostic. */
function errorToDiagnostic(error, defaultValues) {
var _defaultValues$origin2, _ref4, _error$highlightedCod;
let codeFrames = undefined;
if (typeof error === 'string') {
var _defaultValues$origin;
return [{
origin: (_defaultValues$origin = defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.origin) !== null && _defaultValues$origin !== void 0 ? _defaultValues$origin : 'Error',
message: escapeMarkdown(error)
}];
}
if (error instanceof ThrowableDiagnostic) {
return error.diagnostics.map(d => {
var _ref, _d$origin;
return {
...d,
origin: (_ref = (_d$origin = d.origin) !== null && _d$origin !== void 0 ? _d$origin : defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.origin) !== null && _ref !== void 0 ? _ref : 'unknown'
};
});
}
if (error.loc && error.source != null) {
var _ref2, _ref3, _error$filePath;
codeFrames = [{
filePath: (_ref2 = (_ref3 = (_error$filePath = error.filePath) !== null && _error$filePath !== void 0 ? _error$filePath : error.fileName) !== null && _ref3 !== void 0 ? _ref3 : defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.filePath) !== null && _ref2 !== void 0 ? _ref2 : undefined,
code: error.source,
codeHighlights: [{
start: {
line: error.loc.line,
column: error.loc.column
},
end: {
line: error.loc.line,
column: error.loc.column
}
}]
}];
}
return [{
origin: (_defaultValues$origin2 = defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.origin) !== null && _defaultValues$origin2 !== void 0 ? _defaultValues$origin2 : 'Error',
message: escapeMarkdown(error.message),
name: error.name,
stack: codeFrames == null ? (_ref4 = (_error$highlightedCod = error.highlightedCodeFrame) !== null && _error$highlightedCod !== void 0 ? _error$highlightedCod : error.codeFrame) !== null && _ref4 !== void 0 ? _ref4 : error.stack : undefined,
codeFrames
}];
}
/**
* An error wrapper around a diagnostic that can be <code>throw</code>n (e.g. to signal a
* build error).
*/
class ThrowableDiagnostic extends Error {
constructor(opts) {
var _diagnostics$0$stack, _diagnostics$0$name;
let diagnostics = Array.isArray(opts.diagnostic) ? opts.diagnostic : [opts.diagnostic];
// Construct error from diagnostics
super(diagnostics[0].message);
// @ts-ignore
this.stack = (_diagnostics$0$stack = diagnostics[0].stack) !== null && _diagnostics$0$stack !== void 0 ? _diagnostics$0$stack : super.stack;
// @ts-ignore
this.name = (_diagnostics$0$name = diagnostics[0].name) !== null && _diagnostics$0$name !== void 0 ? _diagnostics$0$name : super.name;
this.diagnostics = diagnostics;
}
}
/**
* Turns a list of positions in a JSON5 file with messages into a list of diagnostics.
* Uses <a href="https://github.com/mischnic/json-sourcemap">@mischnic/json-sourcemap</a>.
*
* @param code the JSON code
* @param ids A list of JSON keypaths (<code>key: "/some/parent/child"</code>) with corresponding messages, \
* <code>type</code> signifies whether the key of the value in a JSON object should be highlighted.
*/
exports.default = ThrowableDiagnostic;
function generateJSONCodeHighlights(data, ids) {
let map = typeof data == 'string' ? (0, _jsonSourcemap().parse)(data, undefined, {
dialect: 'JSON5',
tabWidth: 1
}) : data;
return ids.map(({
key,
type,
message
}) => {
let pos = (0, _nullthrows().default)(map.pointers[key]);
return {
...getJSONHighlightLocation(pos, type),
message
};
});
}
/**
* Converts entries in <a href="https://github.com/mischnic/json-sourcemap">@mischnic/json-sourcemap</a>'s
* <code>result.pointers</code> array.
*/
function getJSONHighlightLocation(pos, type) {
let key = 'key' in pos ? pos.key : undefined;
let keyEnd = 'keyEnd' in pos ? pos.keyEnd : undefined;
if (!type && key && pos.value) {
// key and value
return {
start: {
line: key.line + 1,
column: key.column + 1
},
end: {
line: pos.valueEnd.line + 1,
column: pos.valueEnd.column
}
};
} else if (type == 'key' || !pos.value) {
(0, _assert().default)(key && keyEnd);
return {
start: {
line: key.line + 1,
column: key.column + 1
},
end: {
line: keyEnd.line + 1,
column: keyEnd.column
}
};
} else {
return {
start: {
line: pos.value.line + 1,
column: pos.value.column + 1
},
end: {
line: pos.valueEnd.line + 1,
column: pos.valueEnd.column
}
};
}
}
/** Result is 1-based, but end is exclusive */
function getJSONSourceLocation(pos, type) {
let v = getJSONHighlightLocation(pos, type);
return {
start: v.start,
end: {
line: v.end.line,
column: v.end.column + 1
}
};
}
function convertSourceLocationToHighlight({
start,
end
}, message) {
return {
message,
start,
end: {
line: end.line,
column: end.column - 1
}
};
}
/** Sanitizes object keys before using them as <code>key</code> in generateJSONCodeHighlights */
function encodeJSONKeyComponent(component) {
return component.replace(/~/g, '~0').replace(/\//g, '~1');
}
const escapeCharacters = ['\\', '*', '_', '~'];
function escapeMarkdown(s) {
let result = s;
for (const char of escapeCharacters) {
result = result.replace(new RegExp(`\\${char}`, 'g'), `\\${char}`);
}
return result;
}
const mdVerbatim = Symbol();
function md(strings, ...params) {
let result = [];
for (let i = 0; i < params.length; i++) {
result.push(strings[i]);
let param = params[i];
if (Array.isArray(param)) {
for (let j = 0; j < param.length; j++) {
var _param$j$mdVerbatim, _param$j;
result.push((_param$j$mdVerbatim = (_param$j = param[j]) === null || _param$j === void 0 ? void 0 : _param$j[mdVerbatim]) !== null && _param$j$mdVerbatim !== void 0 ? _param$j$mdVerbatim : escapeMarkdown(`${param[j]}`));
if (j < param.length - 1) {
result.push(', ');
}
}
} else {
var _param$mdVerbatim;
result.push((_param$mdVerbatim = param === null || param === void 0 ? void 0 : param[mdVerbatim]) !== null && _param$mdVerbatim !== void 0 ? _param$mdVerbatim : escapeMarkdown(`${param}`));
}
}
return result.join('') + strings[strings.length - 1];
}
md.bold = function (s) {
// $FlowFixMe[invalid-computed-prop]
return {
[mdVerbatim]: '**' + escapeMarkdown(`${s}`) + '**'
};
};
md.italic = function (s) {
// $FlowFixMe[invalid-computed-prop]
return {
[mdVerbatim]: '_' + escapeMarkdown(`${s}`) + '_'
};
};
md.underline = function (s) {
// $FlowFixMe[invalid-computed-prop]
return {
[mdVerbatim]: '__' + escapeMarkdown(`${s}`) + '__'
};
};
md.strikethrough = function (s) {
// $FlowFixMe[invalid-computed-prop]
return {
[mdVerbatim]: '~~' + escapeMarkdown(`${s}`) + '~~'
};
};

View File

@@ -0,0 +1,31 @@
{
"name": "@parcel/diagnostic",
"version": "2.12.0",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/parcel"
},
"repository": {
"type": "git",
"url": "https://github.com/parcel-bundler/parcel.git"
},
"main": "lib/diagnostic.js",
"source": "src/diagnostic.js",
"types": "lib/diagnostic.d.ts",
"engines": {
"node": ">= 12.0.0"
},
"scripts": {
"build-ts": "flow-to-ts src/*.js --write && tsc --emitDeclarationOnly --declaration --esModuleInterop src/*.ts && mkdir -p lib && mv src/*.d.ts lib/. && rm src/*.ts",
"check-ts": "tsc --noEmit lib/diagnostic.d.ts"
},
"dependencies": {
"@mischnic/json-sourcemap": "^0.1.0",
"nullthrows": "^1.1.1"
},
"gitHead": "2059029ee91e5f03a273b0954d3e629d7375f986"
}

View File

@@ -0,0 +1,376 @@
// @flow strict-local
import invariant from 'assert';
import nullthrows from 'nullthrows';
import {parse, type Mapping} from '@mischnic/json-sourcemap';
/** These positions are 1-based (so <code>1</code> is the first line/column) */
export type DiagnosticHighlightLocation = {|
+line: number,
+column: number,
|};
export type DiagnosticSeverity = 'error' | 'warn' | 'info';
/**
* Note: A tab character is always counted as a single character
* This is to prevent any mismatch of highlighting across machines
*/
export type DiagnosticCodeHighlight = {|
/** Location of the first character that should get highlighted for this highlight. */
start: DiagnosticHighlightLocation,
/** Location of the last character that should get highlighted for this highlight. */
end: DiagnosticHighlightLocation,
/** A message that should be displayed at this location in the code (optional). */
message?: string,
|};
/**
* Describes how to format a code frame.
* A code frame is a visualization of a piece of code with a certain amount of
* code highlights that point to certain chunk(s) inside the code.
*/
export type DiagnosticCodeFrame = {|
/**
* The contents of the source file.
*
* If no code is passed, it will be read in from filePath, remember that
* the asset's current code could be different from the input contents.
*
*/
code?: string,
/** Path to the file this code frame is about (optional, absolute or relative to the project root) */
filePath?: string,
/** Language of the file this code frame is about (optional) */
language?: string,
codeHighlights: Array<DiagnosticCodeHighlight>,
|};
/**
* A style agnostic way of emitting errors, warnings and info.
* Reporters are responsible for rendering the message, codeframes, hints, ...
*/
export type Diagnostic = {|
/** This is the message you want to log. */
message: string,
/** Name of plugin or file that threw this error */
origin?: string,
/** A stacktrace of the error (optional) */
stack?: string,
/** Name of the error (optional) */
name?: string,
/** A code frame points to a certain location(s) in the file this diagnostic is linked to (optional) */
codeFrames?: ?Array<DiagnosticCodeFrame>,
/** An optional list of strings that suggest ways to resolve this issue */
hints?: Array<string>,
/** @private */
skipFormatting?: boolean,
/** A URL to documentation to learn more about the diagnostic. */
documentationURL?: string,
|};
// This type should represent all error formats Parcel can encounter...
export interface PrintableError extends Error {
fileName?: string;
filePath?: string;
codeFrame?: string;
highlightedCodeFrame?: string;
loc?: ?{
column: number,
line: number,
...
};
source?: string;
}
export type DiagnosticWithoutOrigin = {|
...Diagnostic,
origin?: string,
|};
/** Something that can be turned into a diagnostic. */
export type Diagnostifiable =
| Diagnostic
| Array<Diagnostic>
| ThrowableDiagnostic
| PrintableError
| Error
| string;
/** Normalize the given value into a diagnostic. */
export function anyToDiagnostic(input: Diagnostifiable): Array<Diagnostic> {
if (Array.isArray(input)) {
return input;
} else if (input instanceof ThrowableDiagnostic) {
return input.diagnostics;
} else if (input instanceof Error) {
return errorToDiagnostic(input);
} else if (typeof input === 'string') {
return [{message: input}];
} else if (typeof input === 'object') {
return [input];
} else {
return errorToDiagnostic(input);
}
}
/** Normalize the given error into a diagnostic. */
export function errorToDiagnostic(
error: ThrowableDiagnostic | PrintableError | string,
defaultValues?: {|
origin?: ?string,
filePath?: ?string,
|},
): Array<Diagnostic> {
let codeFrames: ?Array<DiagnosticCodeFrame> = undefined;
if (typeof error === 'string') {
return [
{
origin: defaultValues?.origin ?? 'Error',
message: escapeMarkdown(error),
},
];
}
if (error instanceof ThrowableDiagnostic) {
return error.diagnostics.map(d => {
return {
...d,
origin: d.origin ?? defaultValues?.origin ?? 'unknown',
};
});
}
if (error.loc && error.source != null) {
codeFrames = [
{
filePath:
error.filePath ??
error.fileName ??
defaultValues?.filePath ??
undefined,
code: error.source,
codeHighlights: [
{
start: {
line: error.loc.line,
column: error.loc.column,
},
end: {
line: error.loc.line,
column: error.loc.column,
},
},
],
},
];
}
return [
{
origin: defaultValues?.origin ?? 'Error',
message: escapeMarkdown(error.message),
name: error.name,
stack:
codeFrames == null
? error.highlightedCodeFrame ?? error.codeFrame ?? error.stack
: undefined,
codeFrames,
},
];
}
type ThrowableDiagnosticOpts = {
diagnostic: Diagnostic | Array<Diagnostic>,
...
};
/**
* An error wrapper around a diagnostic that can be <code>throw</code>n (e.g. to signal a
* build error).
*/
export default class ThrowableDiagnostic extends Error {
diagnostics: Array<Diagnostic>;
constructor(opts: ThrowableDiagnosticOpts) {
let diagnostics = Array.isArray(opts.diagnostic)
? opts.diagnostic
: [opts.diagnostic];
// Construct error from diagnostics
super(diagnostics[0].message);
// @ts-ignore
this.stack = diagnostics[0].stack ?? super.stack;
// @ts-ignore
this.name = diagnostics[0].name ?? super.name;
this.diagnostics = diagnostics;
}
}
/**
* Turns a list of positions in a JSON5 file with messages into a list of diagnostics.
* Uses <a href="https://github.com/mischnic/json-sourcemap">@mischnic/json-sourcemap</a>.
*
* @param code the JSON code
* @param ids A list of JSON keypaths (<code>key: "/some/parent/child"</code>) with corresponding messages, \
* <code>type</code> signifies whether the key of the value in a JSON object should be highlighted.
*/
export function generateJSONCodeHighlights(
data:
| string
| {|
data: mixed,
pointers: {|[key: string]: Mapping|},
|},
ids: Array<{|key: string, type?: ?'key' | 'value', message?: string|}>,
): Array<DiagnosticCodeHighlight> {
let map =
typeof data == 'string'
? parse(data, undefined, {dialect: 'JSON5', tabWidth: 1})
: data;
return ids.map(({key, type, message}) => {
let pos = nullthrows(map.pointers[key]);
return {
...getJSONHighlightLocation(pos, type),
message,
};
});
}
/**
* Converts entries in <a href="https://github.com/mischnic/json-sourcemap">@mischnic/json-sourcemap</a>'s
* <code>result.pointers</code> array.
*/
export function getJSONHighlightLocation(
pos: Mapping,
type?: ?'key' | 'value',
): {|
start: DiagnosticHighlightLocation,
end: DiagnosticHighlightLocation,
|} {
let key = 'key' in pos ? pos.key : undefined;
let keyEnd = 'keyEnd' in pos ? pos.keyEnd : undefined;
if (!type && key && pos.value) {
// key and value
return {
start: {line: key.line + 1, column: key.column + 1},
end: {line: pos.valueEnd.line + 1, column: pos.valueEnd.column},
};
} else if (type == 'key' || !pos.value) {
invariant(key && keyEnd);
return {
start: {line: key.line + 1, column: key.column + 1},
end: {line: keyEnd.line + 1, column: keyEnd.column},
};
} else {
return {
start: {line: pos.value.line + 1, column: pos.value.column + 1},
end: {line: pos.valueEnd.line + 1, column: pos.valueEnd.column},
};
}
}
/** Result is 1-based, but end is exclusive */
export function getJSONSourceLocation(
pos: Mapping,
type?: ?'key' | 'value',
): {|
start: {|
+line: number,
+column: number,
|},
end: {|
+line: number,
+column: number,
|},
|} {
let v = getJSONHighlightLocation(pos, type);
return {start: v.start, end: {line: v.end.line, column: v.end.column + 1}};
}
export function convertSourceLocationToHighlight<
Location: {
/** 1-based, inclusive */
+start: {|
+line: number,
+column: number,
|},
/** 1-based, exclusive */
+end: {|
+line: number,
+column: number,
|},
...
},
>({start, end}: Location, message?: string): DiagnosticCodeHighlight {
return {message, start, end: {line: end.line, column: end.column - 1}};
}
/** Sanitizes object keys before using them as <code>key</code> in generateJSONCodeHighlights */
export function encodeJSONKeyComponent(component: string): string {
return component.replace(/~/g, '~0').replace(/\//g, '~1');
}
const escapeCharacters = ['\\', '*', '_', '~'];
export function escapeMarkdown(s: string): string {
let result = s;
for (const char of escapeCharacters) {
result = result.replace(new RegExp(`\\${char}`, 'g'), `\\${char}`);
}
return result;
}
type TemplateInput = $FlowFixMe;
const mdVerbatim = Symbol();
export function md(
strings: Array<string>,
...params: Array<TemplateInput>
): string {
let result = [];
for (let i = 0; i < params.length; i++) {
result.push(strings[i]);
let param = params[i];
if (Array.isArray(param)) {
for (let j = 0; j < param.length; j++) {
result.push(param[j]?.[mdVerbatim] ?? escapeMarkdown(`${param[j]}`));
if (j < param.length - 1) {
result.push(', ');
}
}
} else {
result.push(param?.[mdVerbatim] ?? escapeMarkdown(`${param}`));
}
}
return result.join('') + strings[strings.length - 1];
}
md.bold = function (s: TemplateInput): TemplateInput {
// $FlowFixMe[invalid-computed-prop]
return {[mdVerbatim]: '**' + escapeMarkdown(`${s}`) + '**'};
};
md.italic = function (s: TemplateInput): TemplateInput {
// $FlowFixMe[invalid-computed-prop]
return {[mdVerbatim]: '_' + escapeMarkdown(`${s}`) + '_'};
};
md.underline = function (s: TemplateInput): TemplateInput {
// $FlowFixMe[invalid-computed-prop]
return {[mdVerbatim]: '__' + escapeMarkdown(`${s}`) + '__'};
};
md.strikethrough = function (s: TemplateInput): TemplateInput {
// $FlowFixMe[invalid-computed-prop]
return {[mdVerbatim]: '~~' + escapeMarkdown(`${s}`) + '~~'};
};

View File

@@ -0,0 +1,36 @@
// @flow strict-local
import assert from 'assert';
import {generateJSONCodeHighlights} from '../src/diagnostic';
describe('generateJSONCodeHighlights', () => {
it('returns an escaped string 01', () => {
let result = generateJSONCodeHighlights(
`{
"a": 1
}`,
[
{key: '/a', type: 'key', message: 'foo1'},
{key: '/a', type: 'value', message: 'foo2'},
{key: '/a', message: 'foo3'},
],
);
assert.deepEqual(result, [
{
start: {line: 2, column: 3},
end: {line: 2, column: 5},
message: 'foo1',
},
{
start: {line: 2, column: 8},
end: {line: 2, column: 8},
message: 'foo2',
},
{
start: {line: 2, column: 3},
end: {line: 2, column: 8},
message: 'foo3',
},
]);
});
});

View File

@@ -0,0 +1,81 @@
// @flow
import assert from 'assert';
import {escapeMarkdown, md} from '../src/diagnostic';
describe('escapeMarkdown', () => {
it('returns an escaped string 01', () => {
assert.strictEqual('\\*test\\*', escapeMarkdown('*test*'));
});
it('returns an escaped string 02', () => {
assert.strictEqual('\\_test\\_', escapeMarkdown('_test_'));
});
it('returns an escaped string 03', () => {
assert.strictEqual('\\~test\\~', escapeMarkdown('~test~'));
});
it('returns an escaped string 04', () => {
assert.strictEqual('\\*\\_\\~test\\~\\_\\*', escapeMarkdown('*_~test~_*'));
});
it('returns an escaped string with backslash 01', () => {
assert.strictEqual('\\\\test\\\\', escapeMarkdown('\\test\\'));
});
it('returns an escaped string with backslash 02', () => {
assert.strictEqual('\\\\\\*test\\*\\\\', escapeMarkdown('\\*test*\\'));
});
});
describe('md tagged template literal', () => {
it('bold placeholder', () => {
assert.strictEqual(
'*Test*: **\\_abc\\_**',
md`*Test*: ${md.bold('_abc_')}`,
);
});
it('italic placeholder', () => {
assert.strictEqual(
'*Test*: _\\_abc\\__',
md`*Test*: ${md.italic('_abc_')}`,
);
});
it('underline placeholder', () => {
assert.strictEqual(
'*Test*: __\\_abc\\___',
md`*Test*: ${md.underline('_abc_')}`,
);
});
it('strikethrough placeholder', () => {
assert.strictEqual(
'*Test*: ~~\\_abc\\_~~',
md`*Test*: ${md.strikethrough('_abc_')}`,
);
});
it('escapes only placeholders', () => {
assert.strictEqual('*Test*: \\_abc\\_', md`*Test*: ${'_abc_'}`);
});
it('behaves like native template literal', () => {
let v = {
toString() {
return 'a';
},
// $FlowFixMe[invalid-computed-prop]
[Symbol.toPrimitive]() {
return 'b';
},
};
assert.strictEqual('Test: b', md`Test: ${v}`);
});
it('supports null and undefined', () => {
assert.strictEqual('Test: undefined null', md`Test: ${undefined} ${null}`);
});
});