janja-language-server 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 李文富
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # janja-language-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) server for [Janja](https://github.com/vvenv/janja) templates, for any editor that speaks LSP.
4
+
5
+ - **Diagnostics** as you type: the syntax errors rendering would report, plus warnings for unknown filters
6
+ - **Completions** for directives (with snippets), built-in filters after `|`, and expression keywords
7
+ - **Hover** documentation for directives and built-in filters
8
+ - **Formatting** of whole documents: normalises the spacing inside tags and never touches the text between them
9
+
10
+ ```bash
11
+ npm install -g janja-language-server
12
+ ```
13
+
14
+ The server is started by the editor, with the transport on the command line: `janja-language-server --stdio` (also `--node-ipc` and `--socket=<port>`).
15
+
16
+ ## Editor setup
17
+
18
+ **Neovim** (0.11+):
19
+
20
+ ```lua
21
+ vim.filetype.add({ extension = { janja = 'janja' } })
22
+ vim.lsp.config('janja', {
23
+ cmd = { 'janja-language-server', '--stdio' },
24
+ filetypes = { 'janja' },
25
+ })
26
+ vim.lsp.enable('janja')
27
+ ```
28
+
29
+ **Helix** (`languages.toml`):
30
+
31
+ ```toml
32
+ [language-server.janja]
33
+ command = "janja-language-server"
34
+ args = ["--stdio"]
35
+
36
+ [[language]]
37
+ name = "janja"
38
+ scope = "text.html.janja"
39
+ file-types = ["janja"]
40
+ language-servers = ["janja"]
41
+ ```
42
+
43
+ **VS Code**: use the [Janja extension](../vscode-janja), which provides the same features together with syntax highlighting.
44
+
45
+ ## Programmatic use
46
+
47
+ ```js
48
+ import { createConnection } from 'vscode-languageserver/node.js';
49
+ import { startServer } from 'janja-language-server';
50
+
51
+ startServer(createConnection(process.stdin, process.stdout));
52
+ ```
53
+
54
+ The editor-independent functions behind the server are exported from `janja-language-server/service`: `getDiagnostics`, `getCompletions`, `getHover` and `formatDocument`.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { createConnection, ProposedFeatures, } from 'vscode-languageserver/node.js';
3
+ import { startServer } from './server.js';
4
+ // The transport is taken from the command line, as editors pass it:
5
+ // --stdio, --node-ipc or --socket=<port>
6
+ startServer(createConnection(ProposedFeatures.all));
@@ -0,0 +1,7 @@
1
+ import { type Connection } from 'vscode-languageserver/node.js';
2
+ export * from './service.js';
3
+ /**
4
+ * Serve the Language Server Protocol on a connection: diagnostics as
5
+ * documents change, completions, hover and whole-document formatting.
6
+ */
7
+ export declare function startServer(connection: Connection): void;
package/dist/server.js ADDED
@@ -0,0 +1,99 @@
1
+ import { CompletionItemKind, DiagnosticSeverity, InsertTextFormat, MarkupKind, TextDocuments, TextDocumentSyncKind, } from 'vscode-languageserver/node.js';
2
+ import { TextDocument } from 'vscode-languageserver-textdocument';
3
+ import { formatDocument, getCompletions, getDiagnostics, getHover, } from './service.js';
4
+ export * from './service.js';
5
+ const completionKinds = {
6
+ directive: CompletionItemKind.Keyword,
7
+ keyword: CompletionItemKind.Operator,
8
+ filter: CompletionItemKind.Function,
9
+ };
10
+ /**
11
+ * Serve the Language Server Protocol on a connection: diagnostics as
12
+ * documents change, completions, hover and whole-document formatting.
13
+ */
14
+ export function startServer(connection) {
15
+ const documents = new TextDocuments(TextDocument);
16
+ connection.onInitialize(() => ({
17
+ capabilities: {
18
+ textDocumentSync: TextDocumentSyncKind.Incremental,
19
+ completionProvider: { triggerCharacters: ['|', ' ', '{'] },
20
+ hoverProvider: true,
21
+ documentFormattingProvider: true,
22
+ },
23
+ serverInfo: { name: 'janja-language-server' },
24
+ }));
25
+ const validate = async (document) => {
26
+ const { version } = document;
27
+ const found = await getDiagnostics(document.getText());
28
+ // The document may have changed, or been closed, while it was checked
29
+ if (documents.get(document.uri)?.version !== version) {
30
+ return;
31
+ }
32
+ const diagnostics = found.map(({ severity, message, line, column, length }) => ({
33
+ severity: severity === 'error'
34
+ ? DiagnosticSeverity.Error
35
+ : DiagnosticSeverity.Warning,
36
+ range: {
37
+ start: { line, character: column },
38
+ end: { line, character: column + length },
39
+ },
40
+ message,
41
+ source: 'janja',
42
+ }));
43
+ await connection.sendDiagnostics({
44
+ uri: document.uri,
45
+ version,
46
+ diagnostics,
47
+ });
48
+ };
49
+ documents.onDidChangeContent(({ document }) => void validate(document));
50
+ documents.onDidClose(({ document }) => {
51
+ void connection.sendDiagnostics({ uri: document.uri, diagnostics: [] });
52
+ });
53
+ connection.onCompletion(({ textDocument, position }) => {
54
+ const document = documents.get(textDocument.uri);
55
+ if (!document) {
56
+ return [];
57
+ }
58
+ return getCompletions(document.getText(), document.offsetAt(position)).map(({ label, kind, detail, snippet }) => ({
59
+ label,
60
+ kind: completionKinds[kind],
61
+ detail,
62
+ ...(snippet
63
+ ? { insertText: snippet, insertTextFormat: InsertTextFormat.Snippet }
64
+ : {}),
65
+ }));
66
+ });
67
+ connection.onHover(({ textDocument, position }) => {
68
+ const document = documents.get(textDocument.uri);
69
+ const hover = document && getHover(document.getText(), document.offsetAt(position));
70
+ if (!hover) {
71
+ return null;
72
+ }
73
+ return {
74
+ contents: { kind: MarkupKind.Markdown, value: hover.contents },
75
+ range: {
76
+ start: document.positionAt(hover.start),
77
+ end: document.positionAt(hover.end),
78
+ },
79
+ };
80
+ });
81
+ connection.onDocumentFormatting(({ textDocument }) => {
82
+ const document = documents.get(textDocument.uri);
83
+ const formatted = document && formatDocument(document.getText());
84
+ if (!formatted) {
85
+ return [];
86
+ }
87
+ return [
88
+ {
89
+ range: {
90
+ start: { line: 0, character: 0 },
91
+ end: document.positionAt(document.getText().length),
92
+ },
93
+ newText: formatted,
94
+ },
95
+ ];
96
+ });
97
+ documents.listen(connection);
98
+ connection.listen();
99
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Editor features as plain functions over text, independent of any editor
3
+ * or protocol.
4
+ */
5
+ export interface Diagnostic {
6
+ severity: 'error' | 'warning';
7
+ message: string;
8
+ /** Zero-based */
9
+ line: number;
10
+ /** Zero-based */
11
+ column: number;
12
+ /** Number of characters to underline */
13
+ length: number;
14
+ }
15
+ export interface Completion {
16
+ label: string;
17
+ kind: 'directive' | 'filter' | 'keyword';
18
+ detail?: string;
19
+ /** Snippet inserted instead of the label, with `$1`-style placeholders */
20
+ snippet?: string;
21
+ }
22
+ export declare function getDiagnostics(text: string): Promise<Diagnostic[]>;
23
+ /**
24
+ * What can be typed at `offset`: filter names after a pipe, directive names
25
+ * at the start of a `{{ }}` tag, expression keywords elsewhere inside a tag,
26
+ * and nothing in plain text or comments.
27
+ */
28
+ export declare function getCompletions(text: string, offset: number): Completion[];
29
+ /**
30
+ * The formatted text, or `null` when there is nothing to change or the
31
+ * template cannot be formatted (an unclosed tag, typically while typing).
32
+ */
33
+ export declare function formatDocument(text: string): string | null;
34
+ export interface Hover {
35
+ /** Markdown */
36
+ contents: string;
37
+ /** Zero-based offsets of the word the hover is for */
38
+ start: number;
39
+ end: number;
40
+ }
41
+ /**
42
+ * Documentation for the directive or built-in filter at `offset`.
43
+ */
44
+ export declare function getHover(text: string, offset: number): Hover | null;
@@ -0,0 +1,150 @@
1
+ // Snippets use VS Code's `${1:placeholder}` syntax in ordinary strings
2
+ /* eslint-disable no-template-curly-in-string */
3
+ import { filters as builtinFilters, formatTemplate, validateTemplate, } from 'janja';
4
+ const directives = [
5
+ ['if', 'if ${1:condition} }}$0{{ endif'],
6
+ ['elif', 'elif ${1:condition}'],
7
+ ['else', 'else'],
8
+ ['endif', 'endif'],
9
+ ['for', 'for ${1:item} of ${2:items} }}$0{{ endfor'],
10
+ ['endfor', 'endfor'],
11
+ ['break', 'break'],
12
+ ['continue', 'continue'],
13
+ ['set', 'set ${1:name} = ${2:value}'],
14
+ ['include', 'include "${1:path}"'],
15
+ ['block', 'block ${1:name} }}$0{{ endblock'],
16
+ ['endblock', 'endblock'],
17
+ ['super', 'super'],
18
+ ['macro', 'macro ${1:name}(${2:params}) }}$0{{ endmacro'],
19
+ ['endmacro', 'endmacro'],
20
+ ['caller', 'caller'],
21
+ ['call', 'call ${1:name}(${2:args}) }}$0{{ endcall'],
22
+ ['endcall', 'endcall'],
23
+ ['capture', 'capture ${1:name} }}$0{{ endcapture'],
24
+ ['endcapture', 'endcapture'],
25
+ ['with', 'with ${1:value} }}$0{{ endwith'],
26
+ ['endwith', 'endwith'],
27
+ ].map(([label, snippet]) => ({ label, kind: 'directive', snippet }));
28
+ const keywords = [
29
+ 'and',
30
+ 'or',
31
+ 'not',
32
+ 'in',
33
+ 'ni',
34
+ 'is',
35
+ 'eq',
36
+ 'ne',
37
+ 'gt',
38
+ 'ge',
39
+ 'lt',
40
+ 'le',
41
+ 'if',
42
+ 'else',
43
+ 'true',
44
+ 'false',
45
+ 'null',
46
+ ].map((label) => ({ label, kind: 'keyword' }));
47
+ const filters = Object.keys(builtinFilters)
48
+ .filter((name) => name !== 'escape')
49
+ .sort()
50
+ .map((label) => ({ label, kind: 'filter', detail: 'built-in filter' }));
51
+ export async function getDiagnostics(text) {
52
+ const { errors, warnings } = await validateTemplate(text);
53
+ const lines = text.split('\n');
54
+ return [...errors, ...warnings].map(({ type, message, line, column }) => {
55
+ const zeroLine = Math.max((line ?? 1) - 1, 0);
56
+ const zeroColumn = Math.max((column ?? 1) - 1, 0);
57
+ const rest = lines[zeroLine]?.slice(zeroColumn) ?? '';
58
+ // Underline the tag the problem starts in, or else the word it is at
59
+ const tag = /^\{\{[^]*?\}\}/.exec(rest) ?? /^[\w$]+/.exec(rest);
60
+ return {
61
+ severity: type,
62
+ message,
63
+ line: zeroLine,
64
+ column: zeroColumn,
65
+ length: Math.max(tag?.[0].length ?? 1, 1),
66
+ };
67
+ });
68
+ }
69
+ /**
70
+ * What can be typed at `offset`: filter names after a pipe, directive names
71
+ * at the start of a `{{ }}` tag, expression keywords elsewhere inside a tag,
72
+ * and nothing in plain text or comments.
73
+ */
74
+ export function getCompletions(text, offset) {
75
+ const before = text.slice(0, offset);
76
+ const open = before.lastIndexOf('{{');
77
+ if (open === -1 || before.lastIndexOf('}}') > open) {
78
+ return [];
79
+ }
80
+ const inside = before.slice(open + 2);
81
+ if (inside.startsWith('#')) {
82
+ return [];
83
+ }
84
+ if (/\|\s*[\w$]*$/.test(inside)) {
85
+ return filters;
86
+ }
87
+ if (!inside.startsWith('=') && /^-?\s*[A-Za-z_]*$/.test(inside)) {
88
+ return directives;
89
+ }
90
+ return /(^|[\s(,])[A-Za-z_]*$/.test(inside) ? keywords : [];
91
+ }
92
+ /**
93
+ * The formatted text, or `null` when there is nothing to change or the
94
+ * template cannot be formatted (an unclosed tag, typically while typing).
95
+ */
96
+ export function formatDocument(text) {
97
+ try {
98
+ const formatted = formatTemplate(text);
99
+ return formatted === text ? null : formatted;
100
+ }
101
+ catch {
102
+ return null;
103
+ }
104
+ }
105
+ const directiveDocs = {
106
+ if: '`{{ if test }}...{{ elif test }}...{{ else }}...{{ endif }}`\n\nRenders the first branch whose test is truthy.',
107
+ for: '`{{ for item of items }}...{{ else }}...{{ endfor }}`\n\nIterates arrays, strings and other iterables. `loop.index`, `loop.first` and `loop.last` are available in the body; `else` renders when there is nothing to iterate.',
108
+ set: '`{{ set name = expression }}`\n\nAssigns in the current scope. `{{ set (a, b) = value }}` reads properties.',
109
+ include: '`{{ include "path" }}`\n\nRenders another template in place, loaded through the `loader` option.',
110
+ block: '`{{ block name }}...{{ endblock }}`\n\nA replaceable region. The last definition of a name is rendered where the block first appears; `{{ super }}` renders the definition it replaced.',
111
+ macro: '`{{ macro name(param, other = default) }}...{{ endmacro }}`\n\nA reusable piece of template, invoked with `{{ call name(args) }}...{{ endcall }}`. `{{ caller }}` renders the body of the call.',
112
+ call: '`{{ call name(args) }}...{{ endcall }}`\n\nInvokes a macro; the body is rendered where the macro has `{{ caller }}`.',
113
+ capture: '`{{ capture name }}...{{ endcapture }}`\n\nRenders the body into a variable instead of the output.',
114
+ with: '`{{ with value }}...{{ endwith }}`\n\nRenders the body in a scope made of the properties of `value` only.',
115
+ break: '`{{ break }}`\n\nEnds the innermost loop.',
116
+ continue: '`{{ continue }}`\n\nSkips to the next iteration of the innermost loop.',
117
+ super: '`{{ super }}`\n\nInside a block, renders the definition this block replaced.',
118
+ caller: '`{{ caller }}`\n\nInside a macro, renders the body of the `call` that invoked it.',
119
+ };
120
+ /**
121
+ * Documentation for the directive or built-in filter at `offset`.
122
+ */
123
+ export function getHover(text, offset) {
124
+ const open = text.lastIndexOf('{{', offset);
125
+ if (open === -1 || text.lastIndexOf('}}', offset - 1) > open) {
126
+ return null;
127
+ }
128
+ let start = offset;
129
+ let end = offset;
130
+ while (start > 0 && /[\w$]/.test(text[start - 1])) {
131
+ start--;
132
+ }
133
+ while (end < text.length && /[\w$]/.test(text[end])) {
134
+ end++;
135
+ }
136
+ const word = text.slice(start, end);
137
+ if (!word) {
138
+ return null;
139
+ }
140
+ const before = text.slice(open + 2, start);
141
+ if (/\|\s*$/.test(before)) {
142
+ return word in builtinFilters
143
+ ? { contents: `\`${word}\` — built-in filter`, start, end }
144
+ : null;
145
+ }
146
+ if (/^-?\s*$/.test(before) && word in directiveDocs) {
147
+ return { contents: directiveDocs[word], start, end };
148
+ }
149
+ return null;
150
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "janja-language-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Language server for Janja templates: diagnostics, completions and formatting",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/vvenv/janja.git",
10
+ "directory": "packages/janja-language-server"
11
+ },
12
+ "homepage": "https://janja.wenfu.dev",
13
+ "bugs": "https://github.com/vvenv/janja/issues",
14
+ "keywords": [
15
+ "janja",
16
+ "lsp",
17
+ "language-server",
18
+ "template"
19
+ ],
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "bin": {
24
+ "janja-language-server": "./dist/cli.js"
25
+ },
26
+ "main": "./dist/server.js",
27
+ "types": "./dist/server.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/server.d.ts",
31
+ "import": "./dist/server.js"
32
+ },
33
+ "./service": {
34
+ "types": "./dist/service.d.ts",
35
+ "import": "./dist/service.js"
36
+ }
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "README.md"
41
+ ],
42
+ "dependencies": {
43
+ "vscode-languageserver": "^9.0.1",
44
+ "vscode-languageserver-textdocument": "^1.0.12",
45
+ "janja": "^3.0.0"
46
+ },
47
+ "devDependencies": {
48
+ "@types/node": "^24.10.3",
49
+ "typescript": "^5.9.3",
50
+ "vitest": "^4.0.16"
51
+ },
52
+ "scripts": {
53
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
54
+ "test": "vitest",
55
+ "typecheck": "tsc --noEmit"
56
+ }
6
57
  }