@akanjs/language 3.1.2-rc.3 → 3.1.2-rc.4

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/server.js ADDED
@@ -0,0 +1,1890 @@
1
+ #!/usr/bin/env node
2
+
3
+ // pkgs/@akanjs/language/akanLanguageServer.ts
4
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+
8
+ // pkgs/@akanjs/language/akanGraph.ts
9
+ var capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
10
+ var lowerFirst = (text) => text.charAt(0).toLowerCase() + text.slice(1);
11
+ var memberSourcePattern = /\.(signal|service|store)\.ts$/;
12
+ var skippedPattern = /(?:\.(?:constant|document|dictionary|test|spec)\.tsx?|\/lib\/(?:cnst|db|dict|sig|srv|st|useClient|useServer)\.ts|\/index\.tsx?|^(?:apps|libs)\/[^/]+\/(?:client|server)\.ts)$/;
13
+ var scalarPattern = /\/lib\/__scalar\/([^/]+)\/[^/]+\.constant\.ts$/;
14
+ var moduleDirPattern = /\/lib\/([^/]+)\//;
15
+ var typeKinds = new Set(["model", "scalar", "enum"]);
16
+ var clientRoots = new Set(["fetch", "st", "sig"]);
17
+
18
+ class GraphBuilder {
19
+ #source;
20
+ #nodes = new Map;
21
+ #edges = new Map;
22
+ #contexts = new Map;
23
+ #members = new Map;
24
+ constructor(source) {
25
+ this.#source = source;
26
+ }
27
+ build() {
28
+ const { facts } = this.#source;
29
+ const constantsByOwner = new Map;
30
+ for (const file of facts)
31
+ constantsByOwner.set(file.owner, [...constantsByOwner.get(file.owner) ?? [], ...file.constants]);
32
+ const scopeOf = (owner) => [
33
+ ...constantsByOwner.get(owner) ?? [],
34
+ ...[...constantsByOwner].filter(([key]) => key !== owner && key?.startsWith("libs/")).flatMap(([, list]) => list)
35
+ ];
36
+ const typed = [];
37
+ for (const file of facts) {
38
+ const { owner } = file;
39
+ const scalar = this.#source.relative(file.fileName).match(scalarPattern)?.[1];
40
+ const scalarClass = scalar ? file.constants.find((constant) => constant.name === capitalize(scalar)) : undefined;
41
+ if (scalar && scalarClass) {
42
+ const id = this.#key("scalar", owner, scalar);
43
+ const node = this.#addNode(id, "scalar", owner, scalar, scalarClass.name, scalarClass.span);
44
+ node.fields = this.#fieldsOf(scalarClass, scopeOf(owner));
45
+ typed.push(node);
46
+ }
47
+ for (const item of file.enums) {
48
+ const id = this.#key("enum", owner, item.name);
49
+ this.#addNode(id, "enum", owner, this.#moduleDirOf(file.fileName), item.name, item.span).values = item.values;
50
+ }
51
+ }
52
+ for (const file of facts) {
53
+ const { owner } = file;
54
+ for (const service of file.services) {
55
+ const refName = service.model;
56
+ if (!refName)
57
+ continue;
58
+ const modelId = this.#key("model", owner, refName);
59
+ const modelClass = constantsByOwner.get(owner)?.find((constant) => constant.name === capitalize(refName));
60
+ if (modelClass && !this.#nodes.has(modelId)) {
61
+ const node = this.#addNode(modelId, "model", owner, refName, modelClass.name, modelClass.span);
62
+ node.fields = this.#fieldsOf(modelClass, scopeOf(owner));
63
+ typed.push(node);
64
+ }
65
+ for (const method of service.methods)
66
+ this.#addMember("method", owner, refName, method, `${service.name}.${method.name}`, file.fileName);
67
+ }
68
+ for (const filter of file.filters) {
69
+ if (!filter.name.endsWith("Filter"))
70
+ continue;
71
+ const refName = lowerFirst(filter.name.slice(0, -"Filter".length));
72
+ this.#addNode(this.#key("query", owner, refName), "query", owner, refName, "", filter.span);
73
+ for (const query of filter.queries)
74
+ this.#digest(this.#addNode(this.#key("query", owner, refName, query.name), "query", owner, refName, query.name, query.span), this.#source.readText(file.fileName), query.extent);
75
+ }
76
+ for (const slice of file.slices) {
77
+ const refName = slice.model;
78
+ if (!refName)
79
+ continue;
80
+ const fallback = this.#addNode(this.#key("slice", owner, refName), "slice", owner, refName, "", slice.span, slice.guards);
81
+ for (const guard of slice.guards)
82
+ this.#guard(fallback, guard);
83
+ for (const key of slice.keys) {
84
+ const detail = [...key.guards, ...key.live ? ["live"] : []];
85
+ const node = this.#addMember("slice", owner, refName, key, `${refName}.${key.name}`, file.fileName, detail);
86
+ for (const guard of key.guards)
87
+ this.#guard(node, guard);
88
+ }
89
+ }
90
+ for (const endpoint of file.endpoints) {
91
+ const refName = endpoint.model;
92
+ if (!refName)
93
+ continue;
94
+ for (const key of endpoint.keys) {
95
+ const detail = [...key.verb ? [key.verb] : [], ...key.guards];
96
+ const node = this.#addMember("endpoint", owner, refName, key, `${refName}.${key.name}`, file.fileName, detail);
97
+ for (const guard of key.guards)
98
+ this.#guard(node, guard);
99
+ }
100
+ }
101
+ for (const store of file.stores)
102
+ if (store.model)
103
+ for (const action of store.actions)
104
+ this.#addMember("action", owner, store.model, action, `${store.name}.${action.name}`, file.fileName);
105
+ }
106
+ const types = new Map;
107
+ for (const node of this.#nodes.values())
108
+ if (typeKinds.has(node.kind))
109
+ types.set(node.label, [...types.get(node.label) ?? [], node]);
110
+ for (const node of typed)
111
+ for (const field of node.fields ?? []) {
112
+ const candidates = (field.type ? types.get(field.type) ?? [] : []).filter((type) => this.#visible(type.owner, node.owner));
113
+ field.ref = (candidates.find((type) => type.owner === node.owner) ?? candidates[0])?.id ?? null;
114
+ if (field.ref)
115
+ this.#addEdge(node.id, field.ref, "field", `${field.name}${field.array ? "[]" : ""}`, field.at);
116
+ }
117
+ for (const [fileName, words] of this.#source.files)
118
+ this.#walk(fileName, words);
119
+ return {
120
+ version: 1,
121
+ nodes: [...this.#nodes.values()].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
122
+ edges: [...this.#edges.values()]
123
+ };
124
+ }
125
+ #key(kind, owner, scope, name = "") {
126
+ return `${kind}:${owner ?? ""}:${scope}${name ? `.${name}` : ""}`;
127
+ }
128
+ #location(span) {
129
+ return { file: this.#source.relative(span.fileName), line: span.line + 1, column: span.character + 1 };
130
+ }
131
+ #addNode(id, kind, owner, module, name, span, detail = [], label = (kind === "query" || kind === "slice") && module ? `${module}${name ? `.${name}` : " (default)"}` : name) {
132
+ const existing = this.#nodes.get(id);
133
+ if (existing)
134
+ return existing;
135
+ const node = {
136
+ id,
137
+ kind,
138
+ name,
139
+ label,
140
+ owner,
141
+ module,
142
+ detail,
143
+ at: span ? this.#location(span) : null
144
+ };
145
+ this.#nodes.set(id, node);
146
+ return node;
147
+ }
148
+ #addMember(kind, owner, refName, member, label, fileName, detail = []) {
149
+ const id = this.#key(kind, owner, refName, member.name);
150
+ const node = this.#addNode(id, kind, owner, refName, member.name, member.span, detail, label);
151
+ this.#digest(node, this.#source.readText(fileName), member.extent);
152
+ this.#contexts.set(fileName, [
153
+ ...this.#contexts.get(fileName) ?? [],
154
+ { id, kind, owner, module: refName, extent: member.extent }
155
+ ]);
156
+ const byName = `${kind}:${member.name}`;
157
+ this.#members.set(byName, [...this.#members.get(byName) ?? [], node]);
158
+ return node;
159
+ }
160
+ #hashOf(text, { start, end }) {
161
+ if (!this.#source.digests || text === undefined)
162
+ return null;
163
+ let hash = 2166136261;
164
+ for (let idx = start;idx < end; idx++) {
165
+ const code = text.charCodeAt(idx);
166
+ if (code !== 13)
167
+ hash = Math.imul(hash ^ code, 16777619);
168
+ }
169
+ return (hash >>> 0).toString(16).padStart(8, "0");
170
+ }
171
+ #digest(node, text, extent) {
172
+ const digest = node.digest ? null : this.#hashOf(text, extent);
173
+ if (digest)
174
+ node.digest = digest;
175
+ }
176
+ #addEdge(from, to, kind, label, at) {
177
+ if (from === to)
178
+ return;
179
+ const key = `${from}
180
+ ${to}
181
+ ${kind}
182
+ ${label ?? ""}`;
183
+ const existing = this.#edges.get(key);
184
+ if (existing)
185
+ existing.count += 1;
186
+ else
187
+ this.#edges.set(key, { from, to, kind, label, count: 1, at });
188
+ }
189
+ #guard(node, guard) {
190
+ const [role, name] = guard.includes(" ") ? guard.split(" ") : [null, guard];
191
+ if (!name || name === "?")
192
+ return;
193
+ const id = `guard:${name}`;
194
+ if (!this.#nodes.has(id))
195
+ this.#nodes.set(id, { id, kind: "guard", name, label: name, owner: null, module: null, detail: [], at: null });
196
+ this.#addEdge(node.id, id, "guard", role, node.at);
197
+ }
198
+ #moduleDirOf(fileName) {
199
+ const dir = this.#source.relative(fileName).match(moduleDirPattern)?.[1] ?? null;
200
+ return dir?.startsWith("_") && !dir.startsWith("__") ? dir.slice(1) : dir;
201
+ }
202
+ #fieldsOf(constant, scope) {
203
+ const fields = new Map;
204
+ const seen = new Set;
205
+ const visit = (current) => {
206
+ if (seen.has(current))
207
+ return;
208
+ seen.add(current);
209
+ for (const parent of current.parents) {
210
+ const parentClass = scope.find((other) => other.name === parent && other.span.fileName === current.span.fileName) ?? scope.find((other) => other.name === parent);
211
+ if (parentClass)
212
+ visit(parentClass);
213
+ }
214
+ for (const field of current.fields) {
215
+ if (fields.has(field.name))
216
+ continue;
217
+ const digest = this.#hashOf(this.#source.readText(field.span.fileName), field.extent);
218
+ fields.set(field.name, {
219
+ name: field.name,
220
+ type: field.type,
221
+ array: field.array,
222
+ optional: field.optional,
223
+ ref: null,
224
+ declaredIn: current.name,
225
+ at: this.#location(field.span),
226
+ ...digest ? { digest } : {}
227
+ });
228
+ }
229
+ };
230
+ visit(constant);
231
+ return [...fields.values()];
232
+ }
233
+ #visible(target, from) {
234
+ return !from || !target || target === from || target.startsWith("libs/");
235
+ }
236
+ #targetNodeOf({ family, owner, refName, sourceKey }) {
237
+ const isDefault = /^[A-Z]/.test(sourceKey);
238
+ const id = family === "slice" || family === "query" ? this.#key(family, owner, refName, isDefault ? "" : sourceKey) : family === "model" || family === "formSetter" ? this.#key("model", owner, refName) : family === "endpoint" ? this.#key("endpoint", owner, refName, sourceKey) : null;
239
+ return id && this.#nodes.has(id) ? id : null;
240
+ }
241
+ #membersNamed(kind, name, owner, refName) {
242
+ const nodes = (this.#members.get(`${kind}:${name}`) ?? []).filter((node) => (!refName || node.module === refName) && this.#visible(node.owner, owner));
243
+ const own = nodes.filter((node) => node.owner === owner);
244
+ return (own.length ? own : nodes).map((node) => node.id);
245
+ }
246
+ #plainTargetsOf(chain, name, context, owner) {
247
+ const [head, second] = chain ?? [];
248
+ if (chain?.length === 1 && head === "fetch")
249
+ return this.#membersNamed("endpoint", name, owner);
250
+ if (chain?.length === 2 && head === "st" && second === "do")
251
+ return this.#membersNamed("action", name, owner);
252
+ if (chain?.length === 1 && head === "this" && (context.kind === "method" || context.kind === "action"))
253
+ return this.#membersNamed(context.kind, name, context.owner, context.module).filter((id) => id.startsWith(`${context.kind}:${context.owner ?? ""}:`));
254
+ if (chain?.length === 2 && head === "this" && second && /.Service$/.test(second))
255
+ return this.#membersNamed("method", name, owner, second.slice(0, -"Service".length));
256
+ return [];
257
+ }
258
+ #walk(fileName, words) {
259
+ const relative = this.#source.relative(fileName);
260
+ const contexts = this.#contexts.get(fileName);
261
+ const isComponentFile = !memberSourcePattern.test(fileName) && !skippedPattern.test(relative) && (words.includes(`
262
+ fetch
263
+ `) || words.includes(`
264
+ st
265
+ `));
266
+ if (!contexts && !isComponentFile)
267
+ return;
268
+ const text = this.#source.readText(fileName);
269
+ if (text === undefined)
270
+ return;
271
+ const { ts } = this.#source;
272
+ const owner = this.#source.ownerOf(fileName);
273
+ const source = this.#source.parse(fileName, text);
274
+ const visit = (node) => {
275
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name)) {
276
+ const start = node.name.getStart(source);
277
+ const chain = this.#chainOf(node.expression);
278
+ const context = contexts ? contexts.find(({ extent }) => extent.start <= start && start < extent.end) : chain && clientRoots.has(chain[0]) ? this.#componentOf(source, node) : undefined;
279
+ if (context)
280
+ this.#link(fileName, source, node.name, chain, context, owner);
281
+ }
282
+ ts.forEachChild(node, visit);
283
+ };
284
+ visit(source);
285
+ }
286
+ #link(fileName, source, identifier, chain, context, owner) {
287
+ const resolved = this.#source.resolve(fileName, identifier).map((target) => this.#targetNodeOf(target)).filter((id) => id !== null);
288
+ const targets = resolved.length ? resolved : this.#plainTargetsOf(chain, identifier.text, context, owner);
289
+ if (!targets.length)
290
+ return;
291
+ if (context.pending && !this.#nodes.has(context.id)) {
292
+ this.#nodes.set(context.id, context.pending);
293
+ this.#digest(context.pending, source.text, context.extent);
294
+ }
295
+ const own = targets.filter((id) => this.#nodes.get(id)?.owner === owner);
296
+ const kind = context.kind === "component" ? "uses" : chain?.[0] === "fetch" ? "fetches" : "calls";
297
+ const position = source.getLineAndCharacterOfPosition(identifier.getStart(source));
298
+ const at = { file: this.#source.relative(fileName), line: position.line + 1, column: position.character + 1 };
299
+ for (const target of new Set(own.length ? own : targets))
300
+ this.#addEdge(context.id, target, kind, identifier.text, at);
301
+ }
302
+ #chainOf(expression) {
303
+ const { ts } = this.#source;
304
+ if (ts.isNonNullExpression(expression) || ts.isParenthesizedExpression(expression))
305
+ return this.#chainOf(expression.expression);
306
+ if (ts.isIdentifier(expression))
307
+ return [expression.text];
308
+ if (expression.kind === ts.SyntaxKind.ThisKeyword)
309
+ return ["this"];
310
+ if (!ts.isPropertyAccessExpression(expression))
311
+ return null;
312
+ const head = this.#chainOf(expression.expression);
313
+ return head ? [...head, expression.name.text] : null;
314
+ }
315
+ #componentOf(source, node) {
316
+ const { ts } = this.#source;
317
+ let top = node;
318
+ while (top.parent && !ts.isSourceFile(top.parent))
319
+ top = top.parent;
320
+ const declared = ts.isVariableStatement(top) ? top.declarationList.declarations[0]?.name : ts.isFunctionDeclaration(top) || ts.isClassDeclaration(top) ? top.name : undefined;
321
+ const isDefaultExport = ts.canHaveModifiers(top) && !!ts.getModifiers(top)?.some(({ kind }) => kind === ts.SyntaxKind.DefaultKeyword);
322
+ const name = declared && ts.isIdentifier(declared) && !isDefaultExport ? declared.text : "default";
323
+ const relative = this.#source.relative(source.fileName);
324
+ const owner = this.#source.ownerOf(source.fileName);
325
+ const id = `component:${relative}#${name}`;
326
+ const context = {
327
+ id,
328
+ kind: "component",
329
+ owner,
330
+ module: null,
331
+ extent: { start: top.getStart(source), end: top.getEnd() }
332
+ };
333
+ if (this.#nodes.has(id))
334
+ return context;
335
+ const pagePrefix = owner ? `${owner}/page/` : null;
336
+ const route = pagePrefix && relative.startsWith(pagePrefix) ? relative.slice(pagePrefix.length).replace(/\.tsx?$/, "") : null;
337
+ const base = relative.slice(relative.lastIndexOf("/") + 1).replace(/\.tsx?$/, "");
338
+ const label = route ? `${route}${name === "default" ? "" : `#${name}`}` : name === "default" ? base : `${base}.${name}`;
339
+ const position = source.getLineAndCharacterOfPosition((declared ?? top).getStart(source));
340
+ context.pending = {
341
+ id,
342
+ kind: "component",
343
+ name,
344
+ label,
345
+ owner,
346
+ module: this.#moduleDirOf(source.fileName),
347
+ detail: route ? ["page"] : [],
348
+ at: { file: relative, line: position.line + 1, column: position.character + 1 }
349
+ };
350
+ return context;
351
+ }
352
+ }
353
+
354
+ // pkgs/@akanjs/language/ast.ts
355
+ var createAst = (ts) => {
356
+ const sourceFileFor = (fileName, content, scriptKind = ts.ScriptKind.TS) => ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, true, scriptKind);
357
+ const nodeName = (node) => {
358
+ if (!node)
359
+ return null;
360
+ if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node))
361
+ return node.text;
362
+ return null;
363
+ };
364
+ const propertyName = (node) => ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node) || ts.isMethodDeclaration(node) ? nodeName(node.name) : null;
365
+ const expressionName = (expression) => {
366
+ if (ts.isIdentifier(expression))
367
+ return expression.text;
368
+ if (ts.isPropertyAccessExpression(expression))
369
+ return expression.name.text;
370
+ if (ts.isCallExpression(expression))
371
+ return expressionName(expression.expression);
372
+ if (ts.isAsExpression(expression))
373
+ return expressionName(expression.expression);
374
+ return null;
375
+ };
376
+ const callExpressionName = (node) => ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : expressionName(node.expression);
377
+ const firstObjectReturnedByArrow = (node) => {
378
+ if (!ts.isArrowFunction(node) && !ts.isFunctionExpression(node))
379
+ return null;
380
+ if (ts.isObjectLiteralExpression(node.body))
381
+ return node.body;
382
+ if (ts.isParenthesizedExpression(node.body) && ts.isObjectLiteralExpression(node.body.expression)) {
383
+ return node.body.expression;
384
+ }
385
+ if (!ts.isBlock(node.body))
386
+ return null;
387
+ for (const statement of node.body.statements) {
388
+ if (ts.isReturnStatement(statement) && statement.expression && ts.isObjectLiteralExpression(statement.expression)) {
389
+ return statement.expression;
390
+ }
391
+ }
392
+ return null;
393
+ };
394
+ const heritageCallNamed = (node, names) => {
395
+ const heritage = node.heritageClauses?.flatMap((clause) => [...clause.types]) ?? [];
396
+ for (const { expression } of heritage) {
397
+ if (!ts.isCallExpression(expression))
398
+ continue;
399
+ const callee = expressionName(expression.expression);
400
+ if (callee && names.has(callee))
401
+ return { callee, call: expression };
402
+ }
403
+ return null;
404
+ };
405
+ const viaNames = new Set(["via"]);
406
+ const heritageCall = (node) => heritageCallNamed(node, viaNames)?.call ?? null;
407
+ return {
408
+ sourceFileFor,
409
+ nodeName,
410
+ propertyName,
411
+ expressionName,
412
+ callExpressionName,
413
+ firstObjectReturnedByArrow,
414
+ heritageCallNamed,
415
+ heritageCall
416
+ };
417
+ };
418
+
419
+ // pkgs/@akanjs/language/moduleFacts.ts
420
+ var moduleCallees = new Set(["via", "from", "into", "serve", "slice", "endpoint", "store", "enumOf"]);
421
+ var argMethods = new Set(["param", "body", "search", "room", "msg"]);
422
+ var ownerOf = (relativePath) => {
423
+ const [root, name] = relativePath.split("/");
424
+ return (root === "apps" || root === "libs") && name ? `${root}/${name}` : null;
425
+ };
426
+ var createFactReader = (ts, ast) => {
427
+ const spanOf = (source, node) => {
428
+ const start = node.getStart(source);
429
+ const end = node.getEnd();
430
+ const head = source.getLineAndCharacterOfPosition(start);
431
+ const tail = source.getLineAndCharacterOfPosition(end);
432
+ return {
433
+ fileName: source.fileName,
434
+ start,
435
+ end,
436
+ line: head.line,
437
+ character: head.character,
438
+ endLine: tail.line,
439
+ endCharacter: tail.character
440
+ };
441
+ };
442
+ const extentOf = (source, node) => ({
443
+ start: node.getStart(source),
444
+ end: node.getEnd()
445
+ });
446
+ const unwrap = (expression) => {
447
+ let current = expression;
448
+ while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression(current))
449
+ current = current.expression;
450
+ return current;
451
+ };
452
+ const moduleRefOf = (expression, holder) => {
453
+ let current = expression && unwrap(expression);
454
+ while (current && ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression))
455
+ current = current.expression.expression;
456
+ if (current && ts.isStringLiteral(current))
457
+ return current.text;
458
+ if (!current || !ts.isPropertyAccessExpression(current))
459
+ return null;
460
+ return ts.isIdentifier(current.expression) && current.expression.text === holder ? current.name.text : null;
461
+ };
462
+ const returnedObject = (builder) => builder ? ast.firstObjectReturnedByArrow(builder) : null;
463
+ const builderOf = (call) => [...call.arguments].reverse().find((arg) => ts.isArrowFunction(arg) || ts.isFunctionExpression(arg));
464
+ const guardsIn = (object) => {
465
+ const guards = object?.properties.find((property) => ts.isPropertyAssignment(property) && ast.nodeName(property.name) === "guards")?.initializer;
466
+ if (!guards)
467
+ return [];
468
+ if (ts.isArrayLiteralExpression(guards))
469
+ return guards.elements.map((element) => ast.expressionName(element)).filter((name) => name !== null);
470
+ if (ts.isObjectLiteralExpression(guards))
471
+ return guards.properties.filter(ts.isPropertyAssignment).map((property) => `${ast.nodeName(property.name)} ${ast.expressionName(property.initializer) ?? "?"}`);
472
+ const single = ast.expressionName(guards);
473
+ return single ? [single] : [];
474
+ };
475
+ const optionObjectOf = (call) => call.arguments.find((arg) => ts.isObjectLiteralExpression(arg) && arg.properties.some((property) => ast.propertyName(property) === "guards"));
476
+ const chainOf = (initializer) => {
477
+ let root = unwrap(initializer);
478
+ const methods = [];
479
+ while (ts.isCallExpression(root) && ts.isPropertyAccessExpression(root.expression) && ts.isCallExpression(unwrap(root.expression.expression))) {
480
+ methods.push(root.expression.name.text);
481
+ root = unwrap(root.expression.expression);
482
+ }
483
+ return { root: ts.isCallExpression(root) ? root : null, methods };
484
+ };
485
+ const keyName = (property) => ts.isPropertyAssignment(property) || ts.isMethodDeclaration(property) || ts.isShorthandPropertyAssignment(property) ? property.name : null;
486
+ const objectKeys = (source, object) => (object?.properties ?? []).flatMap((property) => {
487
+ const name = ast.propertyName(property);
488
+ const node = keyName(property);
489
+ return name && node ? [{ name, span: spanOf(source, node), extent: extentOf(source, property) }] : [];
490
+ });
491
+ const sliceKeysOf = (source, builder) => (returnedObject(builder)?.properties ?? []).flatMap((property) => {
492
+ if (!ts.isPropertyAssignment(property))
493
+ return [];
494
+ const name = ast.nodeName(property.name);
495
+ if (!name)
496
+ return [];
497
+ const { root, methods } = chainOf(property.initializer);
498
+ return [
499
+ {
500
+ name,
501
+ span: spanOf(source, property.name),
502
+ extent: extentOf(source, property),
503
+ guards: root ? guardsIn(optionObjectOf(root)) : [],
504
+ live: methods.includes("live"),
505
+ argCount: methods.filter((method) => argMethods.has(method)).length
506
+ }
507
+ ];
508
+ });
509
+ const verbReaderOf = (parameter) => {
510
+ const verbs = new Map;
511
+ if (parameter && ts.isObjectBindingPattern(parameter.name))
512
+ for (const element of parameter.name.elements) {
513
+ const verb = element.propertyName ?? element.name;
514
+ if (ts.isIdentifier(verb) && ts.isIdentifier(element.name))
515
+ verbs.set(element.name.text, verb.text);
516
+ }
517
+ const holder = parameter && ts.isIdentifier(parameter.name) ? parameter.name.text : null;
518
+ return (callee) => {
519
+ if (callee && ts.isIdentifier(callee))
520
+ return verbs.get(callee.text) ?? null;
521
+ if (callee && ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && callee.expression.text === holder)
522
+ return callee.name.text;
523
+ return null;
524
+ };
525
+ };
526
+ const endpointKeysOf = (source, builder) => {
527
+ const verbOf = verbReaderOf(builder?.parameters[0]);
528
+ return (returnedObject(builder)?.properties ?? []).flatMap((property) => {
529
+ if (!ts.isPropertyAssignment(property))
530
+ return [];
531
+ const name = ast.nodeName(property.name);
532
+ if (!name)
533
+ return [];
534
+ const { root, methods } = chainOf(property.initializer);
535
+ return [
536
+ {
537
+ name,
538
+ span: spanOf(source, property.name),
539
+ extent: extentOf(source, property),
540
+ verb: root ? verbOf(root.expression) : null,
541
+ guards: root ? guardsIn(optionObjectOf(root)) : [],
542
+ argCount: methods.filter((method) => argMethods.has(method)).length
543
+ }
544
+ ];
545
+ });
546
+ };
547
+ const filterQueriesOf = (source, builder) => {
548
+ const query = returnedObject(builder)?.properties.find((property) => ts.isPropertyAssignment(property) && ast.nodeName(property.name) === "query")?.initializer;
549
+ return query && ts.isObjectLiteralExpression(query) ? objectKeys(source, query) : [];
550
+ };
551
+ const typeOf = (expression) => {
552
+ const value = expression && unwrap(expression);
553
+ if (value && ts.isArrayLiteralExpression(value))
554
+ return { type: typeOf(value.elements[0]).type, array: true };
555
+ return { type: value ? ast.expressionName(value) : null, array: false };
556
+ };
557
+ const fieldsOf = (source, object) => (object?.properties ?? []).flatMap((property) => {
558
+ const name = ast.propertyName(property);
559
+ const node = keyName(property);
560
+ if (!name || !node)
561
+ return [];
562
+ const { root, methods } = ts.isPropertyAssignment(property) ? chainOf(property.initializer) : { root: null, methods: [] };
563
+ return [
564
+ {
565
+ name,
566
+ span: spanOf(source, node),
567
+ extent: extentOf(source, property),
568
+ ...typeOf(root?.arguments[0]),
569
+ optional: methods.includes("optional")
570
+ }
571
+ ];
572
+ });
573
+ const constantOf = (source, name, call) => {
574
+ const parents = call.arguments.map(unwrap).filter((arg) => ts.isIdentifier(arg) || ts.isPropertyAccessExpression(arg)).map((arg) => ast.expressionName(arg)).filter((parent) => parent !== null);
575
+ const fields = call.arguments.flatMap((arg) => fieldsOf(source, ast.firstObjectReturnedByArrow(arg)));
576
+ return { ...name, parents, fields };
577
+ };
578
+ const enumValuesOf = (call) => {
579
+ const list = call.arguments[1] && unwrap(call.arguments[1]);
580
+ if (!list || !ts.isArrayLiteralExpression(list))
581
+ return [];
582
+ return list.elements.flatMap((element) => ts.isStringLiteralLike(element) ? [element.text] : []);
583
+ };
584
+ const methodsOf = (source, statement) => statement.members.flatMap((member) => {
585
+ if (!ts.isMethodDeclaration(member) || !member.body)
586
+ return [];
587
+ const name = ast.nodeName(member.name);
588
+ if (!name || ts.getModifiers(member)?.some(({ kind }) => kind === ts.SyntaxKind.StaticKeyword))
589
+ return [];
590
+ return [{ name, span: spanOf(source, member.name), extent: extentOf(source, member) }];
591
+ });
592
+ const lowerFirst = (text) => text.charAt(0).toLowerCase() + text.slice(1);
593
+ const read = (source, owner) => {
594
+ const facts = {
595
+ fileName: source.fileName,
596
+ owner,
597
+ constants: [],
598
+ enums: [],
599
+ filters: [],
600
+ models: [],
601
+ services: [],
602
+ slices: [],
603
+ endpoints: [],
604
+ stores: []
605
+ };
606
+ for (const statement of source.statements) {
607
+ if (!ts.isClassDeclaration(statement) || !statement.name)
608
+ continue;
609
+ const heritage = ast.heritageCallNamed(statement, moduleCallees);
610
+ if (!heritage)
611
+ continue;
612
+ const { callee, call } = heritage;
613
+ const name = { name: statement.name.text, span: spanOf(source, statement.name) };
614
+ const builder = builderOf(call);
615
+ if (callee === "via")
616
+ facts.constants.push(constantOf(source, name, call));
617
+ else if (callee === "enumOf")
618
+ facts.enums.push({ ...name, values: enumValuesOf(call) });
619
+ else if (callee === "from")
620
+ facts.filters.push({ ...name, queries: filterQueriesOf(source, builder) });
621
+ else if (callee === "into")
622
+ facts.models.push({ ...name, model: name.name.endsWith("Model") ? lowerFirst(name.name.slice(0, -5)) : null });
623
+ else if (callee === "serve")
624
+ facts.services.push({
625
+ ...name,
626
+ model: moduleRefOf(call.arguments[0], "db"),
627
+ methods: methodsOf(source, statement)
628
+ });
629
+ else if (callee === "slice")
630
+ facts.slices.push({
631
+ ...name,
632
+ model: moduleRefOf(call.arguments[0], "srv"),
633
+ guards: guardsIn(call.arguments.find(ts.isObjectLiteralExpression)),
634
+ keys: sliceKeysOf(source, builder)
635
+ });
636
+ else if (callee === "endpoint")
637
+ facts.endpoints.push({
638
+ ...name,
639
+ model: moduleRefOf(call.arguments[0], "srv"),
640
+ keys: endpointKeysOf(source, builder)
641
+ });
642
+ else if (callee === "store")
643
+ facts.stores.push({
644
+ ...name,
645
+ model: moduleRefOf(call.arguments[0], "sig"),
646
+ stateKeys: objectKeys(source, returnedObject(builder)),
647
+ actions: methodsOf(source, statement)
648
+ });
649
+ }
650
+ return facts;
651
+ };
652
+ return { read, spanOf, moduleRefOf, chainOf, unwrap };
653
+ };
654
+
655
+ // pkgs/akanjs/common/capitalize.ts
656
+ var capitalize2 = (str) => str.charAt(0).toUpperCase() + str.slice(1);
657
+ var lowerlize = (str) => str.charAt(0).toLowerCase() + str.slice(1);
658
+
659
+ // pkgs/akanjs/common/akanNames.ts
660
+ var sliceNames = (refName, suffix = "") => {
661
+ const [Model, Suffix] = [capitalize2(refName), capitalize2(suffix)];
662
+ const live = `${refName}Live${Suffix}`;
663
+ return {
664
+ slice: `${refName}${Suffix}`,
665
+ state: {
666
+ defaultModel: `default${Model}${Suffix}`,
667
+ modelInitList: `${refName}InitList${Suffix}`,
668
+ modelInsight: `${refName}Insight${Suffix}`,
669
+ modelList: `${refName}List${Suffix}`,
670
+ modelListLoading: `${refName}ListLoading${Suffix}`,
671
+ modelInitAt: `${refName}InitAt${Suffix}`,
672
+ modelStaleAt: `${refName}StaleAt${Suffix}`,
673
+ lastPageOfModel: `lastPageOf${Model}${Suffix}`,
674
+ pageOfModel: `pageOf${Model}${Suffix}`,
675
+ limitOfModel: `limitOf${Model}${Suffix}`,
676
+ hasMoreOfModel: `hasMoreOf${Model}${Suffix}`,
677
+ isCumulativeOfModel: `isCumulativeOf${Model}${Suffix}`,
678
+ hasInsightOfModel: `hasInsightOf${Model}${Suffix}`,
679
+ queryArgsOfModel: `queryArgsOf${Model}${Suffix}`,
680
+ sortOfModel: `sortOf${Model}${Suffix}`,
681
+ modelSelection: `${refName}Selection${Suffix}`
682
+ },
683
+ action: {
684
+ initModel: `init${Model}${Suffix}`,
685
+ refreshModel: `refresh${Model}${Suffix}`,
686
+ selectModel: `select${Model}${Suffix}`,
687
+ setPageOfModel: `setPageOf${Model}${Suffix}`,
688
+ loadMoreOfModel: `loadMoreOf${Model}${Suffix}`,
689
+ setLimitOfModel: `setLimitOf${Model}${Suffix}`,
690
+ setQueryArgsOfModel: `setQueryArgsOf${Model}${Suffix}`,
691
+ setSortOfModel: `setSortOf${Model}${Suffix}`,
692
+ applyLiveModel: `applyLive${Model}${Suffix}`,
693
+ watchLiveModel: `watchLive${Model}${Suffix}`
694
+ },
695
+ endpoint: {
696
+ list: `${refName}List${Suffix}`,
697
+ insight: `${refName}Insight${Suffix}`,
698
+ live,
699
+ subscribeLive: endpointNames(live).subscribe,
700
+ init: `init${Model}${Suffix}`,
701
+ getInit: `get${Model}Init${Suffix}`,
702
+ initResult: `${refName}Init${Suffix}`
703
+ }
704
+ };
705
+ };
706
+ var queryNames = (queryKey) => {
707
+ const Key = capitalize2(queryKey);
708
+ return {
709
+ list: `list${Key}`,
710
+ listIds: `listIds${Key}`,
711
+ find: `find${Key}`,
712
+ findId: `findId${Key}`,
713
+ pick: `pick${Key}`,
714
+ pickId: `pickId${Key}`,
715
+ exists: `exists${Key}`,
716
+ count: `count${Key}`,
717
+ insight: `insight${Key}`,
718
+ query: `query${Key}`,
719
+ remove: `remove${Key}`,
720
+ removeOne: `removeOne${Key}`,
721
+ purge: `purge${Key}`,
722
+ update: `update${Key}`,
723
+ updateOne: `updateOne${Key}`
724
+ };
725
+ };
726
+ var databaseStateNames = (refName) => {
727
+ const className = capitalize2(refName);
728
+ return {
729
+ model: refName,
730
+ modelLoading: `${refName}Loading`,
731
+ modelForm: `${refName}Form`,
732
+ modelFormLoading: `${refName}FormLoading`,
733
+ modelFormUploading: `${refName}FormUploading`,
734
+ modelSubmit: `${refName}Submit`,
735
+ modelViewAt: `${refName}ViewAt`,
736
+ modelModal: `${refName}Modal`,
737
+ modelDraft: `${refName}FormDraft`,
738
+ modelOperation: `${refName}Operation`,
739
+ defaultModel: `default${className}`
740
+ };
741
+ };
742
+ var modelNames = (refName) => {
743
+ const Model = capitalize2(refName);
744
+ return {
745
+ ...databaseStateNames(refName),
746
+ getModel: `get${Model}`,
747
+ loadModel: `load${Model}`,
748
+ loadModelMany: `load${Model}Many`,
749
+ createModel: `create${Model}`,
750
+ createModelMany: `create${Model}Many`,
751
+ updateModel: `update${Model}`,
752
+ removeModel: `remove${Model}`,
753
+ modelModel: `${refName}Model`,
754
+ modelLoader: `${refName}Loader`,
755
+ modelCache: `${refName}Cache`,
756
+ modelId: `${refName}Id`,
757
+ lightModel: `light${Model}`,
758
+ viewModel: `view${Model}`,
759
+ getModelView: `get${Model}View`,
760
+ modelView: `${refName}View`,
761
+ editModel: `edit${Model}`,
762
+ getModelEdit: `get${Model}Edit`,
763
+ modelEdit: `${refName}Edit`,
764
+ modelObj: `${refName}Obj`,
765
+ modelObjList: `${refName}ObjList`,
766
+ modelObjInsight: `${refName}ObjInsight`,
767
+ addModelFiles: `add${Model}Files`,
768
+ mergeModel: `merge${Model}`,
769
+ createModelInForm: `create${Model}InForm`,
770
+ updateModelInForm: `update${Model}InForm`,
771
+ checkModelSubmitable: `check${Model}Submitable`,
772
+ submitModel: `submit${Model}`,
773
+ newModel: `new${Model}`,
774
+ setModel: `set${Model}`,
775
+ resetModel: `reset${Model}`,
776
+ invalidateModel: `invalidate${Model}`,
777
+ loadModelFormDraft: `load${Model}FormDraft`,
778
+ restoreModelFormDraft: `restore${Model}FormDraft`,
779
+ discardModelFormDraft: `discard${Model}FormDraft`,
780
+ writeOnModel: `writeOn${Model}`,
781
+ setViewOfModel: `setViewOf${Model}`,
782
+ exportCsvOfModel: `exportCsvOf${Model}`,
783
+ exportJsonOfModel: `exportJsonOf${Model}`
784
+ };
785
+ };
786
+ var moduleNames = (refName) => {
787
+ const Model = capitalize2(refName);
788
+ return {
789
+ service: `${refName}Service`,
790
+ ServiceClass: `${Model}Service`,
791
+ SliceClass: `${Model}Slice`,
792
+ ModelClass: `${Model}Model`,
793
+ FilterClass: `${Model}Filter`,
794
+ SignalClass: `${Model}Signal`,
795
+ InternalClass: `${Model}Internal`,
796
+ EndpointClass: `${Model}Endpoint`
797
+ };
798
+ };
799
+ var formSetterNames = (className, key) => {
800
+ const classKeyName = capitalize2(key);
801
+ return {
802
+ field: lowerlize(key),
803
+ Field: classKeyName,
804
+ setFieldOnModel: `set${classKeyName}On${className}`,
805
+ addFieldOnModel: `add${classKeyName}On${className}`,
806
+ subFieldOnModel: `sub${classKeyName}On${className}`,
807
+ addOrSubFieldOnModel: `addOrSub${classKeyName}On${className}`,
808
+ moveFieldOnModel: `move${classKeyName}On${className}`,
809
+ uploadFieldOnModel: `upload${classKeyName}On${className}`,
810
+ postSetField: `_postSet${classKeyName}`
811
+ };
812
+ };
813
+ var stateSetterName = (key) => `set${capitalize2(key)}`;
814
+ var endpointNames = (key) => {
815
+ const Key = capitalize2(key);
816
+ return { subscribe: `subscribe${Key}`, listen: `listen${Key}` };
817
+ };
818
+
819
+ // pkgs/@akanjs/language/nameTable.ts
820
+ var capitalize3 = (text) => text.charAt(0).toUpperCase() + text.slice(1);
821
+
822
+ class NameTable {
823
+ #byName = new Map;
824
+ #byFile = new Map;
825
+ constructor(files) {
826
+ const all = [...files];
827
+ const constantsByOwner = new Map;
828
+ for (const facts of all) {
829
+ const constants = constantsByOwner.get(facts.owner) ?? [];
830
+ constants.push(...facts.constants);
831
+ constantsByOwner.set(facts.owner, constants);
832
+ }
833
+ const libConstants = [...constantsByOwner].filter(([owner]) => owner?.startsWith("libs/"));
834
+ const scope = (owner) => ({
835
+ own: constantsByOwner.get(owner) ?? [],
836
+ libs: libConstants.filter(([key]) => key !== owner).flatMap(([, constants]) => constants)
837
+ });
838
+ const scopes = new Map;
839
+ for (const group of NameTable.#groupsOf(all)) {
840
+ const constants = scopes.get(group.owner) ?? scope(group.owner);
841
+ scopes.set(group.owner, constants);
842
+ this.#addGroup(group, constants);
843
+ }
844
+ }
845
+ lookup(name) {
846
+ return this.#byName.get(name) ?? [];
847
+ }
848
+ entriesTargeting(fileName) {
849
+ return this.#byFile.get(fileName) ?? [];
850
+ }
851
+ static #groupsOf(files) {
852
+ const groups = new Map;
853
+ const groupOf = (owner, refName) => {
854
+ const key = `${owner ?? ""}:${refName}`;
855
+ const group = groups.get(key) ?? { owner, refName, constants: [], slices: [], facts: [] };
856
+ groups.set(key, group);
857
+ return group;
858
+ };
859
+ for (const facts of files) {
860
+ const refs = new Set;
861
+ for (const item of [...facts.services, ...facts.slices, ...facts.endpoints, ...facts.stores, ...facts.models])
862
+ if (item.model)
863
+ refs.add(item.model);
864
+ for (const filter of facts.filters)
865
+ if (filter.name.endsWith("Filter"))
866
+ refs.add(NameTable.#lowerFirst(filter.name.slice(0, -6)));
867
+ for (const constant of facts.constants)
868
+ refs.add(NameTable.#lowerFirst(constant.name));
869
+ for (const refName of refs)
870
+ groupOf(facts.owner, refName).facts.push(facts);
871
+ }
872
+ for (const group of groups.values()) {
873
+ group.constants = group.facts.flatMap((facts) => facts.constants);
874
+ group.slices = group.facts.flatMap((facts) => facts.slices.filter((slice) => slice.model === group.refName));
875
+ }
876
+ return [...groups.values()].filter((group) => group.facts.some((facts) => facts.services.some((item) => item.model === group.refName) || facts.slices.some((item) => item.model === group.refName) || facts.stores.some((item) => item.model === group.refName) || facts.models.some((item) => item.model === group.refName)));
877
+ }
878
+ static #lowerFirst(text) {
879
+ return text.charAt(0).toLowerCase() + text.slice(1);
880
+ }
881
+ #add(entry) {
882
+ if (entry.name === entry.sourceKey)
883
+ return;
884
+ const sameName = this.#byName.get(entry.name) ?? [];
885
+ if (sameName.some((other) => other.gate === entry.gate && other.span.fileName === entry.span.fileName && other.span.start === entry.span.start))
886
+ return;
887
+ sameName.push(entry);
888
+ this.#byName.set(entry.name, sameName);
889
+ const sameFile = this.#byFile.get(entry.span.fileName) ?? [];
890
+ sameFile.push(entry);
891
+ this.#byFile.set(entry.span.fileName, sameFile);
892
+ }
893
+ #addGroup(group, constants) {
894
+ const { owner, refName } = group;
895
+ const Model = capitalize3(refName);
896
+ const base = { owner, refName };
897
+ const modelClass = group.constants.find((constant) => constant.name === Model);
898
+ const facts = group.facts;
899
+ const names = moduleNames(refName);
900
+ const serviceClass = facts.flatMap((file) => file.services).find((item) => item.model === refName);
901
+ const sliceClass = group.slices[0];
902
+ const modelDoc = facts.flatMap((file) => file.models).find((item) => item.model === refName);
903
+ const filterClass = facts.flatMap((file) => file.filters).find((item) => item.name === names.FilterClass);
904
+ if (serviceClass) {
905
+ const target = { ...base, family: "module", sourceKey: serviceClass.name, span: serviceClass.span };
906
+ this.#add({ ...target, name: names.service, role: "service", gate: null, label: serviceClass.name, detail: [] });
907
+ this.#add({ ...target, name: refName, role: "srv", gate: "srv", label: serviceClass.name, detail: [] });
908
+ }
909
+ if (sliceClass)
910
+ this.#add({
911
+ ...base,
912
+ family: "module",
913
+ sourceKey: sliceClass.name,
914
+ span: sliceClass.span,
915
+ name: refName,
916
+ role: "sig",
917
+ gate: "sig",
918
+ label: sliceClass.name,
919
+ detail: sliceClass.guards.length ? [`guards: ${sliceClass.guards.join(", ")}`] : []
920
+ });
921
+ if (modelDoc)
922
+ this.#add({
923
+ ...base,
924
+ family: "module",
925
+ sourceKey: modelDoc.name,
926
+ span: modelDoc.span,
927
+ name: refName,
928
+ role: "db",
929
+ gate: "db",
930
+ label: modelDoc.name,
931
+ detail: []
932
+ });
933
+ const modelRoles = modelNames(refName);
934
+ const modelNameSet = new Set(Object.values(modelRoles));
935
+ if (modelClass) {
936
+ const target = { ...base, family: "model", sourceKey: modelClass.name, span: modelClass.span };
937
+ for (const [role, name] of Object.entries(modelRoles))
938
+ this.#add({
939
+ ...target,
940
+ name,
941
+ role,
942
+ gate: role === "model" ? "state" : null,
943
+ label: `model ${Model}`,
944
+ detail: []
945
+ });
946
+ for (const [role, name] of Object.entries(databaseStateNames(refName)))
947
+ this.#add({
948
+ ...target,
949
+ name: stateSetterName(name),
950
+ role: `set:${role}`,
951
+ gate: null,
952
+ label: `model ${Model}`,
953
+ detail: []
954
+ });
955
+ for (const field of NameTable.#fieldsOf(modelClass, constants)) {
956
+ const setters = formSetterNames(Model, field.name);
957
+ for (const role of [
958
+ "setFieldOnModel",
959
+ "addFieldOnModel",
960
+ "subFieldOnModel",
961
+ "addOrSubFieldOnModel",
962
+ "uploadFieldOnModel"
963
+ ])
964
+ this.#add({
965
+ ...base,
966
+ family: "formSetter",
967
+ sourceKey: field.name,
968
+ span: field.span,
969
+ name: setters[role],
970
+ role,
971
+ gate: null,
972
+ label: `field ${field.declaredIn}.${field.name}`,
973
+ detail: []
974
+ });
975
+ }
976
+ }
977
+ for (const slice of group.slices) {
978
+ const defaultTarget = {
979
+ ...base,
980
+ family: "slice",
981
+ sourceKey: slice.name,
982
+ span: slice.span,
983
+ label: `slice ${refName} (default)`,
984
+ detail: slice.guards.length ? [`guards: ${slice.guards.join(", ")}`] : []
985
+ };
986
+ this.#addSliceNames(defaultTarget, refName, "", modelNameSet);
987
+ for (const key of slice.keys)
988
+ this.#addSliceNames({
989
+ ...base,
990
+ family: "slice",
991
+ sourceKey: key.name,
992
+ span: key.span,
993
+ label: `slice ${key.name}`,
994
+ detail: [...key.guards.length ? [`guards: ${key.guards.join(", ")}`] : [], ...key.live ? ["live"] : []]
995
+ }, refName, key.name, modelNameSet, slice.name);
996
+ }
997
+ if (filterClass) {
998
+ const defaults = { ...base, family: "query", detail: [] };
999
+ for (const [role, name] of Object.entries(queryNames("any")))
1000
+ this.#add({
1001
+ ...defaults,
1002
+ sourceKey: filterClass.name,
1003
+ span: filterClass.span,
1004
+ name,
1005
+ role,
1006
+ gate: null,
1007
+ label: `query any (default) of ${filterClass.name}`
1008
+ });
1009
+ for (const query of filterClass.queries)
1010
+ for (const [role, name] of Object.entries(queryNames(query.name)))
1011
+ this.#add({
1012
+ ...defaults,
1013
+ sourceKey: query.name,
1014
+ span: query.span,
1015
+ name,
1016
+ role,
1017
+ gate: null,
1018
+ label: `query ${query.name}`,
1019
+ renamed: (key) => queryNames(key)[role],
1020
+ dictionary: { section: "query", className: filterClass.name }
1021
+ });
1022
+ }
1023
+ for (const store of facts.flatMap((file) => file.stores).filter((item) => item.model === refName))
1024
+ for (const key of store.stateKeys)
1025
+ this.#add({
1026
+ ...base,
1027
+ family: "storeState",
1028
+ sourceKey: key.name,
1029
+ span: key.span,
1030
+ name: stateSetterName(key.name),
1031
+ role: "set",
1032
+ gate: null,
1033
+ label: `store state ${key.name}`,
1034
+ detail: []
1035
+ });
1036
+ for (const endpoint of facts.flatMap((file) => file.endpoints).filter((item) => item.model === refName))
1037
+ for (const key of endpoint.keys) {
1038
+ const derived = endpointNames(key.name);
1039
+ const name = key.verb === "pubsub" ? derived.subscribe : key.verb === "message" ? derived.listen : null;
1040
+ if (!name)
1041
+ continue;
1042
+ this.#add({
1043
+ ...base,
1044
+ family: "endpoint",
1045
+ sourceKey: key.name,
1046
+ span: key.span,
1047
+ name,
1048
+ role: key.verb === "pubsub" ? "subscribe" : "listen",
1049
+ gate: null,
1050
+ label: `${key.verb} ${key.name}`,
1051
+ detail: key.guards.length ? [`guards: ${key.guards.join(", ")}`] : []
1052
+ });
1053
+ }
1054
+ }
1055
+ static #sliceRoles(refName, suffix) {
1056
+ const names = sliceNames(refName, suffix);
1057
+ return new Map([
1058
+ ["slice", names.slice],
1059
+ ...Object.entries(names.state),
1060
+ ...Object.entries(names.action),
1061
+ ...Object.entries(names.endpoint),
1062
+ ...Object.entries(names.state).map(([role, name]) => [`set:${role}`, stateSetterName(name)])
1063
+ ]);
1064
+ }
1065
+ #addSliceNames(target, refName, suffix, skip, className) {
1066
+ for (const [role, name] of NameTable.#sliceRoles(refName, suffix)) {
1067
+ if (!suffix && role !== "slice" && skip.has(name))
1068
+ continue;
1069
+ this.#add({
1070
+ ...target,
1071
+ name,
1072
+ role,
1073
+ gate: role === "slice" ? "slice" : null,
1074
+ ...suffix && className ? {
1075
+ renamed: (key) => NameTable.#sliceRoles(refName, key).get(role) ?? name,
1076
+ dictionary: { section: "slice", className }
1077
+ } : {}
1078
+ });
1079
+ }
1080
+ }
1081
+ static #fieldsOf(modelClass, { own, libs }) {
1082
+ const classNamed = (name, near) => own.find((constant) => constant.name === name && constant.span.fileName === near.span.fileName) ?? own.find((constant) => constant.name === name) ?? libs.find((constant) => constant.name === name);
1083
+ const fields = new Map;
1084
+ const seen = new Set;
1085
+ const visit = (constant) => {
1086
+ if (seen.has(constant))
1087
+ return;
1088
+ seen.add(constant);
1089
+ for (const field of constant.fields)
1090
+ if (!fields.has(field.name))
1091
+ fields.set(field.name, { ...field, declaredIn: constant.name });
1092
+ for (const parent of constant.parents) {
1093
+ const parentClass = classNamed(parent, constant);
1094
+ if (parentClass)
1095
+ visit(parentClass);
1096
+ }
1097
+ };
1098
+ visit(modelClass);
1099
+ return [...fields.values()];
1100
+ }
1101
+ }
1102
+
1103
+ // pkgs/@akanjs/language/akanIndex.ts
1104
+ var sourcePattern = /\.(constant|document|service|signal|store)\.ts$/;
1105
+ var dictionaryPattern = /\.dictionary\.ts$/;
1106
+ var wordPattern = /[A-Za-z_$][\w$]*/g;
1107
+ var identifierPattern = /^[A-Za-z_$][\w$]*$/;
1108
+ var regExpSpecials = /[\\^$.*+?()[\]{}|]/g;
1109
+ var stateReceivers = new Set(["use", "sel", "get", "do"]);
1110
+ var lensFamilies = new Set(["slice", "query", "formSetter", "storeState", "endpoint"]);
1111
+ var modellessFamilies = new Set(["query", "storeState", "endpoint"]);
1112
+ var gateWords = { srv: "srv", sig: "sig", db: "db", slice: "slice" };
1113
+ var parseCacheSize = 64;
1114
+ var pathOf = (fileName) => fileName.replace(/\\/g, "/");
1115
+ var escapeRegExp = (text) => text.replace(regExpSpecials, (special) => `\\${special}`);
1116
+ var receiverGap = String.raw`(?:\s|\)|\/\*[\s\S]*?\*\/)*`;
1117
+
1118
+ class AkanIndex {
1119
+ #ts;
1120
+ #root;
1121
+ #ast;
1122
+ #reader;
1123
+ #facts = new Map;
1124
+ #fileWords = new Map;
1125
+ #parsed = new Map;
1126
+ #table = null;
1127
+ constructor({ ts, root }) {
1128
+ this.#ts = ts;
1129
+ this.#root = pathOf(root).replace(/\/$/, "");
1130
+ this.#ast = createAst(ts);
1131
+ this.#reader = createFactReader(ts, this.#ast);
1132
+ }
1133
+ static isSourcePath(fileName) {
1134
+ return sourcePattern.test(fileName);
1135
+ }
1136
+ get fileCount() {
1137
+ return this.#fileWords.size;
1138
+ }
1139
+ setFile(givenName, text) {
1140
+ const fileName = pathOf(givenName);
1141
+ this.#fileWords.set(fileName, `
1142
+ ${[...new Set(text.match(wordPattern))].join(`
1143
+ `)}
1144
+ `);
1145
+ if (!AkanIndex.isSourcePath(fileName))
1146
+ return;
1147
+ const source = this.#parsed.get(fileName)?.text === text ? this.#parse(fileName, text) : this.#parseUncached(fileName, text);
1148
+ this.#facts.set(fileName, this.#reader.read(source, this.#ownerOf(fileName)));
1149
+ this.#table = null;
1150
+ }
1151
+ removeFile(givenName) {
1152
+ const fileName = pathOf(givenName);
1153
+ this.#fileWords.delete(fileName);
1154
+ this.#parsed.delete(fileName);
1155
+ if (this.#facts.delete(fileName))
1156
+ this.#table = null;
1157
+ }
1158
+ definitionAt(givenName, text, offset) {
1159
+ const fileName = pathOf(givenName);
1160
+ const site = this.#useAt(this.#parse(fileName, text), offset);
1161
+ return site ? this.#resolve(fileName, site) : [];
1162
+ }
1163
+ hoverAt(givenName, text, offset) {
1164
+ const fileName = pathOf(givenName);
1165
+ const site = this.#useAt(this.#parse(fileName, text), offset);
1166
+ if (!site)
1167
+ return null;
1168
+ const targets = this.#resolve(fileName, site);
1169
+ return targets.length ? { name: site.identifier.text, targets } : null;
1170
+ }
1171
+ sourceKeysOf(givenName) {
1172
+ const keys = new Map;
1173
+ for (const entry of this.#nameTable().entriesTargeting(pathOf(givenName))) {
1174
+ if (!lensFamilies.has(entry.family) || keys.has(entry.span.start))
1175
+ continue;
1176
+ keys.set(entry.span.start, AkanIndex.#sourceKeyOf(entry));
1177
+ }
1178
+ return [...keys.values()].sort((a, b) => a.span.start - b.span.start);
1179
+ }
1180
+ sourceKeyAt(givenName, offset) {
1181
+ const entries = this.#sourceEntriesAt(pathOf(givenName), offset);
1182
+ const entry = entries.find((candidate) => lensFamilies.has(candidate.family)) ?? entries.at(0);
1183
+ return entry ? AkanIndex.#sourceKeyOf(entry) : null;
1184
+ }
1185
+ referencesAt(givenName, offset, readText) {
1186
+ return this.#usesOf(this.#sourceEntriesAt(pathOf(givenName), offset), readText).map((use) => use.span);
1187
+ }
1188
+ graph(readText, { digests = false } = {}) {
1189
+ return new GraphBuilder({
1190
+ digests,
1191
+ ts: this.#ts,
1192
+ facts: [...this.#facts].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, facts]) => facts),
1193
+ files: [...this.#fileWords].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0),
1194
+ readText,
1195
+ parse: (fileName, text) => this.#parse(fileName, text),
1196
+ resolve: (fileName, identifier) => {
1197
+ if (!this.#nameTable().lookup(identifier.text).length)
1198
+ return [];
1199
+ const site = this.#siteOf(identifier);
1200
+ return site ? this.#resolve(fileName, site) : [];
1201
+ },
1202
+ relative: (fileName) => this.#relative(fileName),
1203
+ ownerOf: (fileName) => this.#ownerOf(fileName)
1204
+ }).build();
1205
+ }
1206
+ renameTargetAt(givenName, offset) {
1207
+ const source = this.#sourceEntriesAt(pathOf(givenName), offset).find((entry) => entry.renamed);
1208
+ return source ? { family: source.family, sourceKey: source.sourceKey, span: source.span } : null;
1209
+ }
1210
+ renameAt(givenName, offset, newKey, readText) {
1211
+ const sources = this.#sourceEntriesAt(pathOf(givenName), offset).filter((entry) => entry.renamed);
1212
+ if (!sources.length || !identifierPattern.test(newKey))
1213
+ return null;
1214
+ return [
1215
+ { span: sources[0].span, newText: newKey },
1216
+ ...this.#usesOf(sources, readText).map(({ span, entry, shorthand }) => {
1217
+ const renamed = entry.renamed?.(newKey) ?? entry.name;
1218
+ return { span, newText: shorthand ? `${renamed}: ${entry.name}` : renamed };
1219
+ }),
1220
+ ...this.#dictionaryKeysOf(sources[0], readText).map(({ span, quote }) => ({
1221
+ span,
1222
+ newText: `${quote}${newKey}${quote}`
1223
+ }))
1224
+ ];
1225
+ }
1226
+ static #sourceKeyOf({ family, sourceKey, label, detail, span }) {
1227
+ return { family, sourceKey, label, detail, span };
1228
+ }
1229
+ #usesOf(sources, readText) {
1230
+ if (!sources.length)
1231
+ return [];
1232
+ const ts = this.#ts;
1233
+ const isSource = (target) => sources.some((source) => source.span.fileName === target.span.fileName && source.span.start === target.span.start);
1234
+ const refNames = new Set(sources.map((source) => source.refName));
1235
+ const byName = new Map(sources.map((source) => [source.name, source]));
1236
+ const naming = new RegExp(`\\n(?:${[...byName.keys()].map(escapeRegExp).join("|")})\\n`);
1237
+ const gateWordsOf = sources.map((source) => source.gate ? gateWords[source.gate] : undefined);
1238
+ const receiverPatterns = sources.map((source, at) => {
1239
+ const gateWord = gateWordsOf[at];
1240
+ return gateWord ? new RegExp(String.raw`(?<![\w$])${gateWord}${receiverGap}[?!]?\.${receiverGap}${escapeRegExp(source.name)}(?![\w$])`) : null;
1241
+ });
1242
+ const named = (words, at) => words.includes(`
1243
+ ${sources[at].name}
1244
+ `) && (!gateWordsOf[at] || words.includes(`
1245
+ ${gateWordsOf[at]}
1246
+ `));
1247
+ const candidates = [...this.#fileWords].filter(([, words]) => naming.test(words) && sources.some((_, at) => named(words, at)));
1248
+ const found = [];
1249
+ for (const [file, words] of candidates.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
1250
+ const text = readText(file);
1251
+ if (text === undefined)
1252
+ continue;
1253
+ if (!sources.some((_, at) => named(words, at) && (receiverPatterns[at]?.test(text) ?? true)))
1254
+ continue;
1255
+ const source = this.#parse(file, text);
1256
+ const visit = (node) => {
1257
+ const entry = ts.isIdentifier(node) ? byName.get(node.text) : undefined;
1258
+ const site = entry && ts.isIdentifier(node) ? this.#siteOf(node) : null;
1259
+ const targets = site ? this.#resolve(file, site) : [];
1260
+ if (entry && site && targets.some(isSource) && targets.every((target) => refNames.has(target.refName))) {
1261
+ const parent = site.identifier.parent;
1262
+ const shorthand = ts.isBindingElement(parent) && !parent.propertyName;
1263
+ found.push({ span: this.#reader.spanOf(source, site.identifier), entry, shorthand });
1264
+ }
1265
+ ts.forEachChild(node, visit);
1266
+ };
1267
+ visit(source);
1268
+ }
1269
+ return found;
1270
+ }
1271
+ #dictionaryKeysOf(source, readText) {
1272
+ const { dictionary } = source;
1273
+ if (!dictionary)
1274
+ return [];
1275
+ const ts = this.#ts;
1276
+ const keys = [];
1277
+ const moduleDir = source.span.fileName.slice(0, source.span.fileName.lastIndexOf("/"));
1278
+ for (const [file, words] of this.#fileWords) {
1279
+ if (!dictionaryPattern.test(file) || this.#ownerOf(file) !== source.owner)
1280
+ continue;
1281
+ const sameModule = file.slice(0, file.lastIndexOf("/")) === moduleDir;
1282
+ if (!words.includes(`
1283
+ ${dictionary.section}
1284
+ `))
1285
+ continue;
1286
+ if (!sameModule && !words.includes(`
1287
+ ${dictionary.className}
1288
+ `))
1289
+ continue;
1290
+ const text = readText(file);
1291
+ if (text === undefined)
1292
+ continue;
1293
+ const parsed = this.#parse(file, text);
1294
+ const visit = (node) => {
1295
+ const typeArgument = ts.isCallExpression(node) ? node.typeArguments?.[0] : undefined;
1296
+ const builder = ts.isCallExpression(node) ? node.arguments.at(-1) : undefined;
1297
+ const typed = !!typeArgument && ts.isTypeReferenceNode(typeArgument) && ts.isIdentifier(typeArgument.typeName) && typeArgument.typeName.text === dictionary.className;
1298
+ const untyped = !typeArgument && sameModule;
1299
+ const object = ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === dictionary.section && (typed || untyped) && builder ? this.#ast.firstObjectReturnedByArrow(builder) : null;
1300
+ for (const property of object?.properties ?? [])
1301
+ if (ts.isPropertyAssignment(property) && this.#ast.nodeName(property.name) === source.sourceKey)
1302
+ keys.push({
1303
+ span: this.#reader.spanOf(parsed, property.name),
1304
+ quote: ts.isStringLiteral(property.name) ? parsed.text.charAt(property.name.getStart(parsed)) : ""
1305
+ });
1306
+ ts.forEachChild(node, visit);
1307
+ };
1308
+ visit(parsed);
1309
+ }
1310
+ return keys;
1311
+ }
1312
+ #sourceEntriesAt(fileName, offset) {
1313
+ return this.#nameTable().entriesTargeting(fileName).filter((entry) => entry.span.start <= offset && offset <= entry.span.end);
1314
+ }
1315
+ #nameTable() {
1316
+ this.#table ??= new NameTable(this.#facts.values());
1317
+ return this.#table;
1318
+ }
1319
+ #relative(fileName) {
1320
+ return fileName.startsWith(`${this.#root}/`) ? fileName.slice(this.#root.length + 1) : fileName;
1321
+ }
1322
+ #ownerOf(fileName) {
1323
+ return ownerOf(this.#relative(fileName));
1324
+ }
1325
+ #parseUncached(fileName, text) {
1326
+ const kind = fileName.endsWith(".tsx") ? this.#ts.ScriptKind.TSX : this.#ts.ScriptKind.TS;
1327
+ return this.#ast.sourceFileFor(fileName, text, kind);
1328
+ }
1329
+ #parse(fileName, text) {
1330
+ const cached = this.#parsed.get(fileName);
1331
+ if (cached?.text === text)
1332
+ return cached.source;
1333
+ const source = this.#parseUncached(fileName, text);
1334
+ this.#parsed.delete(fileName);
1335
+ this.#parsed.set(fileName, { text, source });
1336
+ if (this.#parsed.size > parseCacheSize) {
1337
+ const oldest = this.#parsed.keys().next().value;
1338
+ if (oldest !== undefined)
1339
+ this.#parsed.delete(oldest);
1340
+ }
1341
+ return source;
1342
+ }
1343
+ #useAt(source, offset) {
1344
+ const ts = this.#ts;
1345
+ let found = null;
1346
+ const visit = (node) => {
1347
+ if (offset < node.getStart(source) || offset > node.getEnd())
1348
+ return;
1349
+ if (ts.isIdentifier(node))
1350
+ found = node;
1351
+ ts.forEachChild(node, visit);
1352
+ };
1353
+ visit(source);
1354
+ return found ? this.#siteOf(found) : null;
1355
+ }
1356
+ #siteOf(identifier) {
1357
+ const ts = this.#ts;
1358
+ const parent = identifier.parent;
1359
+ let chain;
1360
+ if (ts.isPropertyAccessExpression(parent) && parent.name === identifier)
1361
+ chain = this.#chainOf(parent.expression);
1362
+ else if (ts.isBindingElement(parent) && !parent.dotDotDotToken && ts.isObjectBindingPattern(parent.parent) && (parent.propertyName === identifier || !parent.propertyName && parent.name === identifier))
1363
+ chain = null;
1364
+ else
1365
+ return null;
1366
+ const { model, inStore } = this.#classContextOf(identifier);
1367
+ return { identifier, chain, classModel: model, inStore };
1368
+ }
1369
+ #chainOf(expression) {
1370
+ const ts = this.#ts;
1371
+ if (ts.isNonNullExpression(expression) || ts.isParenthesizedExpression(expression))
1372
+ return this.#chainOf(expression.expression);
1373
+ if (ts.isIdentifier(expression))
1374
+ return [expression.text];
1375
+ if (expression.kind === ts.SyntaxKind.ThisKeyword)
1376
+ return ["this"];
1377
+ if (ts.isPropertyAccessExpression(expression))
1378
+ return [...this.#chainOf(expression.expression), expression.name.text];
1379
+ return ["?"];
1380
+ }
1381
+ #classContextOf(node) {
1382
+ const ts = this.#ts;
1383
+ let current = node.parent;
1384
+ while (current && !ts.isClassDeclaration(current) && !ts.isClassExpression(current))
1385
+ current = current.parent;
1386
+ if (!current)
1387
+ return { model: null, inStore: false };
1388
+ const className = current.name?.text;
1389
+ const heritage = current.heritageClauses?.flatMap((clause) => [...clause.types]) ?? [];
1390
+ for (const { expression } of heritage) {
1391
+ if (!ts.isCallExpression(expression))
1392
+ continue;
1393
+ const callee = this.#ast.expressionName(expression.expression);
1394
+ if (callee === "into" && className?.endsWith("Model"))
1395
+ return { model: className.charAt(0).toLowerCase() + className.slice(1, -5), inStore: false };
1396
+ const holder = callee === "serve" ? "db" : callee === "store" ? "sig" : callee === "slice" || callee === "endpoint" || callee === "internal" ? "srv" : null;
1397
+ if (!holder)
1398
+ continue;
1399
+ return { model: this.#reader.moduleRefOf(expression.arguments[0], holder), inStore: callee === "store" };
1400
+ }
1401
+ return { model: null, inStore: false };
1402
+ }
1403
+ #modelHintOf(site) {
1404
+ const { chain } = site;
1405
+ if (!chain)
1406
+ return null;
1407
+ if (chain.length === 1 && chain[0] === "this")
1408
+ return site.classModel;
1409
+ const holder = chain.at(-1)?.replace(/^#/, "");
1410
+ const suffix = holder?.match(/.(Service|Model)$/)?.[1];
1411
+ if (holder && suffix)
1412
+ return holder.slice(0, -suffix.length);
1413
+ if (chain.length === 2 && (chain[0] === "db" || chain[0] === "srv"))
1414
+ return chain[1];
1415
+ return null;
1416
+ }
1417
+ #passesGate(entry, site) {
1418
+ const { chain } = site;
1419
+ const last = chain?.at(-1);
1420
+ switch (entry.gate) {
1421
+ case "srv":
1422
+ case "sig":
1423
+ case "db":
1424
+ return chain?.length === 1 && last === entry.gate;
1425
+ case "slice":
1426
+ return last === "slice";
1427
+ case "state":
1428
+ return !!last && stateReceivers.has(last) || site.inStore && chain?.length === 1 && last === "this";
1429
+ default:
1430
+ return true;
1431
+ }
1432
+ }
1433
+ #resolve(fileName, site) {
1434
+ const owner = this.#ownerOf(fileName);
1435
+ const visible = this.#nameTable().lookup(site.identifier.text).filter((entry) => this.#passesGate(entry, site) && (!owner || !entry.owner || entry.owner === owner || entry.owner.startsWith("libs/")));
1436
+ const hint = this.#modelHintOf(site);
1437
+ const hinted = hint ? visible.filter((entry) => entry.refName === hint) : [];
1438
+ const chosen = hinted.length ? hinted : hint ? visible.filter((entry) => !modellessFamilies.has(entry.family)) : visible;
1439
+ return chosen.map(({ family, refName, owner: entryOwner, sourceKey, label, detail, span }) => ({
1440
+ family,
1441
+ refName,
1442
+ owner: entryOwner,
1443
+ sourceKey,
1444
+ label,
1445
+ detail,
1446
+ span
1447
+ })).sort((a, b) => Number(b.owner === owner) - Number(a.owner === owner));
1448
+ }
1449
+ }
1450
+
1451
+ // pkgs/@akanjs/language/lspConnection.ts
1452
+ var lspErrors = {
1453
+ parseError: -32700,
1454
+ invalidRequest: -32600,
1455
+ methodNotFound: -32601,
1456
+ internalError: -32603,
1457
+ serverNotInitialized: -32002
1458
+ };
1459
+ var headerEnd = Buffer.from(`\r
1460
+ \r
1461
+ `);
1462
+ var contentLength = /^content-length:\s*(\d+)\s*$/im;
1463
+
1464
+ class LspConnection {
1465
+ #output;
1466
+ #onMessage;
1467
+ #buffer = Buffer.alloc(0);
1468
+ #nextId = 0;
1469
+ constructor(input, output, onMessage) {
1470
+ this.#output = output;
1471
+ this.#onMessage = onMessage;
1472
+ input.on("data", (chunk) => this.#read(typeof chunk === "string" ? Buffer.from(chunk) : chunk));
1473
+ }
1474
+ #read(chunk) {
1475
+ this.#buffer = Buffer.concat([this.#buffer, chunk]);
1476
+ for (;; ) {
1477
+ const end = this.#buffer.indexOf(headerEnd);
1478
+ if (end < 0)
1479
+ return;
1480
+ const length = this.#buffer.subarray(0, end).toString("ascii").match(contentLength)?.[1];
1481
+ const start = end + headerEnd.length;
1482
+ if (length === undefined) {
1483
+ this.#buffer = this.#buffer.subarray(start);
1484
+ continue;
1485
+ }
1486
+ if (this.#buffer.length < start + Number(length))
1487
+ return;
1488
+ const body = this.#buffer.subarray(start, start + Number(length)).toString("utf8");
1489
+ this.#buffer = this.#buffer.subarray(start + Number(length));
1490
+ this.#dispatch(body);
1491
+ }
1492
+ }
1493
+ #dispatch(body) {
1494
+ let message;
1495
+ try {
1496
+ message = JSON.parse(body);
1497
+ } catch {
1498
+ this.fail(null, lspErrors.parseError, "The message is not JSON.");
1499
+ return;
1500
+ }
1501
+ if (typeof message === "object" && message !== null && !Array.isArray(message))
1502
+ this.#onMessage(message);
1503
+ else
1504
+ this.fail(null, lspErrors.invalidRequest, "The message is not a JSON-RPC object.");
1505
+ }
1506
+ send(message) {
1507
+ const body = Buffer.from(JSON.stringify(message), "utf8");
1508
+ this.#output.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r
1509
+ \r
1510
+ `, "ascii"), body]));
1511
+ }
1512
+ respond(id, result) {
1513
+ this.send({ jsonrpc: "2.0", id, result: result ?? null });
1514
+ }
1515
+ fail(id, code, message) {
1516
+ this.send({ jsonrpc: "2.0", id, error: { code, message } });
1517
+ }
1518
+ notify(method, params) {
1519
+ this.send({ jsonrpc: "2.0", method, params });
1520
+ }
1521
+ request(method, params) {
1522
+ this.send({ jsonrpc: "2.0", id: `akan-${++this.#nextId}`, method, params });
1523
+ }
1524
+ }
1525
+
1526
+ // pkgs/@akanjs/language/akanLanguageServer.ts
1527
+ var systemKinds = ["apps", "libs"];
1528
+ var isSkippedDir = (name) => name === "node_modules" || name === "dist" || name.startsWith(".");
1529
+ var indexedPath = /^(apps|libs)\/(?!(?:.*\/)?(?:node_modules|dist|\.[^/]*)\/).*\.tsx?$/;
1530
+ var sourceGlob = "{apps,libs}/**/*.{ts,tsx}";
1531
+ var editDelayMs = 150;
1532
+ var filesPerYield = 200;
1533
+ var infoMessage = 3;
1534
+ var unknownMethod = Symbol("unknownMethod");
1535
+ var isDirectory = (dir) => {
1536
+ try {
1537
+ return statSync(dir).isDirectory();
1538
+ } catch {
1539
+ return false;
1540
+ }
1541
+ };
1542
+ var fileOf = (uri) => {
1543
+ try {
1544
+ return fileURLToPath(uri);
1545
+ } catch {
1546
+ return null;
1547
+ }
1548
+ };
1549
+ var isAkanRoot = (dir) => systemKinds.some((kind) => {
1550
+ try {
1551
+ return readdirSync(path.join(dir, kind)).some((system) => existsSync(path.join(dir, kind, system, "akan.config.ts")));
1552
+ } catch {
1553
+ return false;
1554
+ }
1555
+ });
1556
+ var workspaceRootOf = (dir) => {
1557
+ const parent = path.dirname(dir);
1558
+ if (isAkanRoot(dir))
1559
+ return dir;
1560
+ return parent === dir ? null : workspaceRootOf(parent);
1561
+ };
1562
+ var caseOf = (fileName) => process.platform === "win32" ? fileName.toLowerCase() : fileName;
1563
+ var sourceFilesOf = (root) => {
1564
+ const found = [];
1565
+ const visited = new Set;
1566
+ const walk = (dir) => {
1567
+ let entries;
1568
+ try {
1569
+ const real = realpathSync(dir);
1570
+ if (visited.has(real))
1571
+ return;
1572
+ visited.add(real);
1573
+ entries = readdirSync(dir, { withFileTypes: true });
1574
+ } catch {
1575
+ return;
1576
+ }
1577
+ for (const entry of entries) {
1578
+ const at = path.join(dir, entry.name);
1579
+ const isDir = entry.isDirectory() || entry.isSymbolicLink() && isDirectory(at);
1580
+ if (isDir && !isSkippedDir(entry.name))
1581
+ walk(at);
1582
+ else if (!isDir && /\.tsx?$/.test(entry.name))
1583
+ found.push(at);
1584
+ }
1585
+ };
1586
+ for (const kind of systemKinds)
1587
+ walk(path.join(root, kind));
1588
+ return found;
1589
+ };
1590
+ var offsetAt = (text, { line, character }) => {
1591
+ const breaks = [...text.matchAll(/\r\n|\r|\n/g)];
1592
+ if (line > breaks.length)
1593
+ return text.length;
1594
+ const start = line === 0 ? 0 : breaks[line - 1].index + breaks[line - 1][0].length;
1595
+ const end = line < breaks.length ? breaks[line].index : text.length;
1596
+ return Math.min(start + character, end);
1597
+ };
1598
+ var positionAt = (text, offset) => {
1599
+ const breaks = [...text.slice(0, offset).matchAll(/\r\n|\r|\n/g)];
1600
+ const last = breaks.at(-1);
1601
+ return { line: breaks.length, character: last ? offset - last.index - last[0].length : offset };
1602
+ };
1603
+ var escapeMarkdown = (text) => text.replace(/[\\`*_{}[\]()#+\-.!|<>]/g, "\\$&");
1604
+ var messageOf = (error) => error instanceof Error ? error.message : String(error);
1605
+ var yieldToLoop = () => new Promise((resolve) => setImmediate(resolve));
1606
+
1607
+ class AkanLanguageServer {
1608
+ #ts;
1609
+ #connection;
1610
+ #exit;
1611
+ #open = new Map;
1612
+ #pendingEdits = new Map;
1613
+ #roots = [];
1614
+ #ready = Promise.resolve();
1615
+ #queue = Promise.resolve();
1616
+ #watchesFiles = false;
1617
+ #watchesRelative = false;
1618
+ #hoversMarkdown = true;
1619
+ #isInitialized = false;
1620
+ #isShutdown = false;
1621
+ constructor({ ts, input, output, exit }) {
1622
+ this.#ts = ts;
1623
+ this.#exit = exit;
1624
+ this.#connection = new LspConnection(input, output, (message) => this.#handle(message));
1625
+ input.on("end", () => this.#stop());
1626
+ }
1627
+ #handle(message) {
1628
+ this.#queue = this.#queue.then(() => this.#process(message)).catch((error) => this.#log(messageOf(error)));
1629
+ }
1630
+ async#process({ id, method, params }) {
1631
+ if (method === undefined)
1632
+ return;
1633
+ if (id !== undefined && id !== null)
1634
+ return await this.#answer(id, method, params);
1635
+ if (this.#isInitialized || method === "exit")
1636
+ this.#notified(method, params);
1637
+ }
1638
+ async#answer(id, method, params) {
1639
+ if (!this.#isInitialized && method !== "initialize")
1640
+ return this.#connection.fail(id, lspErrors.serverNotInitialized, "The server is not initialized yet.");
1641
+ if (this.#isShutdown)
1642
+ return this.#connection.fail(id, lspErrors.invalidRequest, "The server is shutting down.");
1643
+ try {
1644
+ const result = await this.#result(method, params);
1645
+ if (result === unknownMethod)
1646
+ this.#connection.fail(id, lspErrors.methodNotFound, `${method} is not supported.`);
1647
+ else
1648
+ this.#connection.respond(id, result);
1649
+ } catch (error) {
1650
+ this.#connection.fail(id, lspErrors.internalError, messageOf(error));
1651
+ }
1652
+ }
1653
+ async#result(method, params) {
1654
+ switch (method) {
1655
+ case "initialize":
1656
+ return this.#initialize(params);
1657
+ case "shutdown":
1658
+ this.#isShutdown = true;
1659
+ return null;
1660
+ case "textDocument/definition":
1661
+ return await this.#definition(params);
1662
+ case "textDocument/references":
1663
+ return await this.#references(params);
1664
+ case "textDocument/hover":
1665
+ return await this.#hover(params);
1666
+ default:
1667
+ return unknownMethod;
1668
+ }
1669
+ }
1670
+ #notified(method, params) {
1671
+ switch (method) {
1672
+ case "initialized":
1673
+ return this.#watch();
1674
+ case "exit":
1675
+ return this.#stop();
1676
+ case "textDocument/didOpen": {
1677
+ const { textDocument } = params;
1678
+ return this.#opened(textDocument.uri, textDocument.text);
1679
+ }
1680
+ case "textDocument/didChange": {
1681
+ const { textDocument, contentChanges } = params;
1682
+ const text = contentChanges.at(-1)?.text;
1683
+ return text === undefined ? undefined : this.#changed(textDocument.uri, text);
1684
+ }
1685
+ case "textDocument/didClose":
1686
+ return this.#closed(params.textDocument.uri);
1687
+ case "workspace/didChangeWatchedFiles":
1688
+ for (const { uri } of params.changes)
1689
+ this.#changedOnDisk(uri);
1690
+ return;
1691
+ default:
1692
+ return;
1693
+ }
1694
+ }
1695
+ #initialize(params) {
1696
+ this.#isInitialized = true;
1697
+ const watched = params.capabilities?.workspace?.didChangeWatchedFiles;
1698
+ this.#watchesFiles = watched?.dynamicRegistration === true;
1699
+ this.#watchesRelative = watched?.relativePatternSupport === true;
1700
+ this.#hoversMarkdown = params.capabilities?.textDocument?.hover?.contentFormat?.includes("markdown") ?? true;
1701
+ const given = params.workspaceFolders?.length ? params.workspaceFolders.map((folder) => fileOf(folder.uri)) : [params.rootUri ? fileOf(params.rootUri) : params.rootPath ?? null];
1702
+ const roots = new Set(given.flatMap((dir) => dir ? [workspaceRootOf(path.resolve(dir))] : []));
1703
+ this.#roots = [...roots].flatMap((root) => root ? [{ root, index: new AkanIndex({ ts: this.#ts, root }) }] : []).sort((a, b) => b.root.length - a.root.length);
1704
+ this.#ready = yieldToLoop().then(() => this.#fill());
1705
+ return {
1706
+ capabilities: {
1707
+ positionEncoding: "utf-16",
1708
+ textDocumentSync: { openClose: true, change: 1 },
1709
+ definitionProvider: true,
1710
+ referencesProvider: true,
1711
+ hoverProvider: true
1712
+ },
1713
+ serverInfo: { name: "akan-language-server" }
1714
+ };
1715
+ }
1716
+ async#fill() {
1717
+ for (const entry of this.#roots) {
1718
+ const started = Date.now();
1719
+ const failures = [];
1720
+ for (const [at, fileName] of sourceFilesOf(entry.root).entries()) {
1721
+ if (at % filesPerYield === filesPerYield - 1)
1722
+ await yieldToLoop();
1723
+ const text = this.#readText(fileName);
1724
+ try {
1725
+ if (text !== undefined)
1726
+ entry.index.setFile(fileName, text);
1727
+ } catch (error) {
1728
+ failures.push(error);
1729
+ }
1730
+ }
1731
+ const skipped = failures.length ? `; skipped ${failures.length}: ${messageOf(failures[0])}` : "";
1732
+ this.#log(`akan: indexed ${entry.index.fileCount} files in ${Date.now() - started}ms at ${entry.root}${skipped}`);
1733
+ }
1734
+ }
1735
+ #watch() {
1736
+ if (!this.#watchesFiles || !this.#roots.length)
1737
+ return;
1738
+ const watchers = this.#watchesRelative ? this.#roots.map(({ root }) => ({ globPattern: { baseUri: pathToFileURL(root).href, pattern: sourceGlob } })) : [{ globPattern: `**/${sourceGlob}` }];
1739
+ this.#connection.request("client/registerCapability", {
1740
+ registrations: [
1741
+ { id: "akan-source-files", method: "workspace/didChangeWatchedFiles", registerOptions: { watchers } }
1742
+ ]
1743
+ });
1744
+ }
1745
+ #stop() {
1746
+ for (const timer of this.#pendingEdits.values())
1747
+ clearTimeout(timer);
1748
+ this.#pendingEdits.clear();
1749
+ this.#exit(this.#isShutdown ? 0 : 1);
1750
+ }
1751
+ #log(message) {
1752
+ this.#connection.notify("window/logMessage", { type: infoMessage, message });
1753
+ }
1754
+ #readText = (fileName) => {
1755
+ const open = this.#open.get(path.resolve(fileName));
1756
+ if (open !== undefined)
1757
+ return open;
1758
+ try {
1759
+ return readFileSync(fileName, "utf8");
1760
+ } catch {
1761
+ return;
1762
+ }
1763
+ };
1764
+ #rootOf(fileName) {
1765
+ return this.#roots.find(({ root }) => caseOf(fileName).startsWith(caseOf(`${root}${path.sep}`))) ?? null;
1766
+ }
1767
+ #locationsOf(spans) {
1768
+ const texts = new Map;
1769
+ return spans.map(({ fileName, start, end, line, character, endLine, endCharacter }) => {
1770
+ if (!texts.has(fileName))
1771
+ texts.set(fileName, this.#readText(fileName));
1772
+ const text = texts.get(fileName);
1773
+ return {
1774
+ uri: pathToFileURL(fileName).href,
1775
+ range: text === undefined ? { start: { line, character }, end: { line: endLine, character: endCharacter } } : { start: positionAt(text, start), end: positionAt(text, end) }
1776
+ };
1777
+ });
1778
+ }
1779
+ #update(fileName) {
1780
+ const entry = this.#rootOf(fileName);
1781
+ const relative = entry ? path.relative(entry.root, fileName).split(path.sep).join("/") : "";
1782
+ if (!entry || !indexedPath.test(relative))
1783
+ return;
1784
+ const text = this.#readText(fileName);
1785
+ try {
1786
+ if (text === undefined)
1787
+ entry.index.removeFile(fileName);
1788
+ else
1789
+ entry.index.setFile(fileName, text);
1790
+ } catch (error) {
1791
+ this.#log(`akan: ${fileName}: ${messageOf(error)}`);
1792
+ }
1793
+ }
1794
+ #flush() {
1795
+ for (const [fileName, timer] of this.#pendingEdits) {
1796
+ clearTimeout(timer);
1797
+ this.#update(fileName);
1798
+ }
1799
+ this.#pendingEdits.clear();
1800
+ }
1801
+ #opened(uri, text) {
1802
+ const fileName = fileOf(uri);
1803
+ if (!fileName)
1804
+ return;
1805
+ this.#open.set(path.resolve(fileName), text);
1806
+ this.#update(path.resolve(fileName));
1807
+ }
1808
+ #changed(uri, text) {
1809
+ const fileName = fileOf(uri);
1810
+ if (!fileName)
1811
+ return;
1812
+ const key = path.resolve(fileName);
1813
+ this.#open.set(key, text);
1814
+ clearTimeout(this.#pendingEdits.get(key));
1815
+ this.#pendingEdits.set(key, setTimeout(() => {
1816
+ this.#pendingEdits.delete(key);
1817
+ this.#update(key);
1818
+ }, editDelayMs));
1819
+ }
1820
+ #closed(uri) {
1821
+ const fileName = fileOf(uri);
1822
+ if (!fileName)
1823
+ return;
1824
+ const key = path.resolve(fileName);
1825
+ clearTimeout(this.#pendingEdits.get(key));
1826
+ this.#pendingEdits.delete(key);
1827
+ this.#open.delete(key);
1828
+ this.#update(key);
1829
+ }
1830
+ #changedOnDisk(uri) {
1831
+ const fileName = fileOf(uri);
1832
+ if (fileName && !this.#open.has(path.resolve(fileName)))
1833
+ this.#update(path.resolve(fileName));
1834
+ }
1835
+ async#locate({ textDocument, position }) {
1836
+ await this.#ready;
1837
+ this.#flush();
1838
+ const given = fileOf(textDocument.uri);
1839
+ const fileName = given ? path.resolve(given) : null;
1840
+ const entry = fileName ? this.#rootOf(fileName) : null;
1841
+ const text = fileName ? this.#readText(fileName) : undefined;
1842
+ if (!fileName || !entry || text === undefined)
1843
+ return null;
1844
+ return { entry, fileName, text, offset: offsetAt(text, position) };
1845
+ }
1846
+ async#definition(params) {
1847
+ const at = await this.#locate(params);
1848
+ return at && this.#locationsOf(at.entry.index.definitionAt(at.fileName, at.text, at.offset).map(({ span }) => span));
1849
+ }
1850
+ async#references(params) {
1851
+ const at = await this.#locate(params);
1852
+ if (!at)
1853
+ return null;
1854
+ const uses = at.entry.index.referencesAt(at.fileName, at.offset, this.#readText);
1855
+ const key = params.context?.includeDeclaration && uses.length ? at.entry.index.sourceKeyAt(at.fileName, at.offset) : null;
1856
+ return this.#locationsOf(key ? [key.span, ...uses] : uses);
1857
+ }
1858
+ async#hover(params) {
1859
+ const at = await this.#locate(params);
1860
+ const hover = at?.entry.index.hoverAt(at.fileName, at.text, at.offset);
1861
+ if (!at || !hover)
1862
+ return null;
1863
+ const lines = this.#locationsOf(hover.targets.map(({ span }) => span)).map(({ range }) => range.start.line + 1);
1864
+ const lineOf = (target, idx) => {
1865
+ const summary = [target.label, ...target.detail].join(" · ");
1866
+ const where = `${path.relative(at.entry.root, target.span.fileName).split(path.sep).join("/")}:${lines[idx]}`;
1867
+ return this.#hoversMarkdown ? `**akan** · ${escapeMarkdown(summary)} — \`${where}\`` : `akan · ${summary} — ${where}`;
1868
+ };
1869
+ return {
1870
+ contents: {
1871
+ kind: this.#hoversMarkdown ? "markdown" : "plaintext",
1872
+ value: hover.targets.map(lineOf).join(`
1873
+
1874
+ `)
1875
+ }
1876
+ };
1877
+ }
1878
+ }
1879
+
1880
+ // pkgs/@akanjs/language/server.ts
1881
+ if (!process.argv.includes("--stdio")) {
1882
+ process.stderr.write("akan-language-server speaks LSP over stdio: run it as `akan-language-server --stdio`.\n");
1883
+ process.exit(2);
1884
+ }
1885
+ var ts = await import("typescript").then((loaded) => loaded.default ?? loaded, () => null);
1886
+ if (!ts) {
1887
+ process.stderr.write("akan-language-server needs the `typescript` package installed next to @akanjs/language.\n");
1888
+ process.exit(1);
1889
+ }
1890
+ new AkanLanguageServer({ ts, input: process.stdin, output: process.stdout, exit: (code) => process.exit(code) });