@cratis/screenplay-language 4.50.0 → 4.51.0

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.
Files changed (81) hide show
  1. package/DestinationHint.ts +8 -0
  2. package/ProductionSymbol.ts +11 -0
  3. package/completion-items.ts +14 -0
  4. package/completion-planner.ts +6 -0
  5. package/completions.ts +4 -2
  6. package/diagnostic-codes.ts +9 -0
  7. package/dist/DestinationHint.d.ts +6 -0
  8. package/dist/DestinationHint.d.ts.map +1 -0
  9. package/dist/DestinationHint.js +4 -0
  10. package/dist/DestinationHint.js.map +1 -0
  11. package/dist/ProductionSymbol.d.ts +13 -0
  12. package/dist/ProductionSymbol.d.ts.map +1 -0
  13. package/dist/ProductionSymbol.js +4 -0
  14. package/dist/ProductionSymbol.js.map +1 -0
  15. package/dist/completion-items.d.ts +2 -0
  16. package/dist/completion-items.d.ts.map +1 -1
  17. package/dist/completion-items.js +12 -0
  18. package/dist/completion-items.js.map +1 -1
  19. package/dist/completion-planner.d.ts.map +1 -1
  20. package/dist/completion-planner.js +7 -0
  21. package/dist/completion-planner.js.map +1 -1
  22. package/dist/completions.d.ts.map +1 -1
  23. package/dist/completions.js +4 -1
  24. package/dist/completions.js.map +1 -1
  25. package/dist/diagnostic-codes.d.ts +9 -0
  26. package/dist/diagnostic-codes.d.ts.map +1 -1
  27. package/dist/diagnostic-codes.js +9 -0
  28. package/dist/diagnostic-codes.js.map +1 -1
  29. package/dist/event-analysis-source.d.ts +2 -0
  30. package/dist/event-analysis-source.d.ts.map +1 -0
  31. package/dist/event-analysis-source.js +19 -0
  32. package/dist/event-analysis-source.js.map +1 -0
  33. package/dist/hover-content.d.ts.map +1 -1
  34. package/dist/hover-content.js +9 -1
  35. package/dist/hover-content.js.map +1 -1
  36. package/dist/index.d.ts +3 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +3 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/inlay-hints.d.ts +3 -0
  41. package/dist/inlay-hints.d.ts.map +1 -0
  42. package/dist/inlay-hints.js +15 -0
  43. package/dist/inlay-hints.js.map +1 -0
  44. package/dist/inline-event-validation.d.ts +4 -0
  45. package/dist/inline-event-validation.d.ts.map +1 -0
  46. package/dist/inline-event-validation.js +131 -0
  47. package/dist/inline-event-validation.js.map +1 -0
  48. package/dist/keyword-docs.d.ts.map +1 -1
  49. package/dist/keyword-docs.js +5 -3
  50. package/dist/keyword-docs.js.map +1 -1
  51. package/dist/production-destinations.d.ts +8 -0
  52. package/dist/production-destinations.d.ts.map +1 -0
  53. package/dist/production-destinations.js +32 -0
  54. package/dist/production-destinations.js.map +1 -0
  55. package/dist/symbols.d.ts +5 -0
  56. package/dist/symbols.d.ts.map +1 -1
  57. package/dist/symbols.js +68 -20
  58. package/dist/symbols.js.map +1 -1
  59. package/dist/tokens.d.ts.map +1 -1
  60. package/dist/tokens.js +13 -4
  61. package/dist/tokens.js.map +1 -1
  62. package/dist/validation.d.ts.map +1 -1
  63. package/dist/validation.js +11 -32
  64. package/dist/validation.js.map +1 -1
  65. package/event-analysis-source.ts +18 -0
  66. package/for_inlineEvents/when_analyzing_many_inline_events.ts +59 -0
  67. package/for_inlineEvents/when_authoring_inline_events.ts +149 -0
  68. package/for_inlineEvents/when_completing_many_events.ts +49 -0
  69. package/for_inlineEvents/when_indexing_command_production_ownership.ts +79 -0
  70. package/for_tokens/when_highlighting_event_metadata.ts +63 -0
  71. package/for_validateLines/when_validating_a_document/with_a_problem_of_every_coded_kind.ts +14 -0
  72. package/hover-content.ts +9 -1
  73. package/index.ts +5 -0
  74. package/inlay-hints.ts +17 -0
  75. package/inline-event-validation.ts +115 -0
  76. package/keyword-docs.ts +5 -3
  77. package/package.json +1 -1
  78. package/production-destinations.ts +32 -0
  79. package/symbols.ts +70 -19
  80. package/tokens.ts +14 -4
  81. package/validation.ts +13 -28
package/index.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  import { createTokensProvider } from './tokens';
11
11
  import { CompletionOptions, createCompletionProvider } from './completions';
12
12
  import { createHoverProvider } from './hover';
13
+ import { createInlayHintsProvider } from './inlay-hints';
13
14
  import { attachDiagnostics } from './diagnostics';
14
15
  import {
15
16
  getSubLanguage,
@@ -53,6 +54,7 @@ export function register(monaco: Monaco, options: LanguageServiceOptions = {}):
53
54
  applyTokensProvider(monaco);
54
55
  monaco.languages.registerCompletionItemProvider(languageId, createCompletionProvider(monaco, options));
55
56
  monaco.languages.registerHoverProvider(languageId, createHoverProvider());
57
+ monaco.languages.registerInlayHintsProvider(languageId, createInlayHintsProvider());
56
58
  monaco.editor.defineTheme(screenplayDarkThemeName, screenplayDark);
57
59
  monaco.editor.defineTheme(screenplayLightThemeName, screenplayLight);
58
60
  attachDiagnostics(monaco);
@@ -115,6 +117,9 @@ export { completionEntriesFor, planCompletions } from './completion-planner';
115
117
  export type { CompletionPlan } from './completion-planner';
116
118
  export { hoverContent } from './hover-content';
117
119
  export { validateLines } from './validation';
120
+ export { destinationHints, productionDestinations } from './production-destinations';
121
+ export type { DestinationHint } from './DestinationHint';
122
+ export type { ProductionSymbol } from './ProductionSymbol';
118
123
  export type { ValidationContext, ValidationIssue, ValidationSeverity } from './validation';
119
124
  export { diagnosticCodes } from './diagnostic-codes';
120
125
  export type { DiagnosticCode } from './diagnostic-codes';
package/inlay-hints.ts ADDED
@@ -0,0 +1,17 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { languages } from 'monaco-editor';
5
+ import { destinationHints } from './production-destinations';
6
+
7
+ export function createInlayHintsProvider(): languages.InlayHintsProvider {
8
+ return {
9
+ provideInlayHints(model, range) {
10
+ const hints = destinationHints(model.getLinesContent()).filter(hint => hint.line + 1 >= range.startLineNumber && hint.line + 1 <= range.endLineNumber);
11
+ return {
12
+ hints: hints.map(hint => ({ position: { lineNumber: hint.line + 1, column: hint.column }, label: hint.label, paddingLeft: true })),
13
+ dispose() {},
14
+ };
15
+ },
16
+ };
17
+ }
@@ -0,0 +1,115 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { DiagnosticCode, diagnosticCodes } from './diagnostic-codes';
5
+ import { fenceMap, indentOf } from './document-context';
6
+ import { productionDestinations } from './production-destinations';
7
+ import { eventAnalysisSource } from './event-analysis-source';
8
+ import { directBody, DocumentSymbols } from './symbols';
9
+ import type { ValidationIssue, ValidationSeverity } from './validation';
10
+
11
+ const reserved = new Set(['namespace', 'sequence', 'correlation', 'causation', 'causedBy', 'occurred']);
12
+ const quotedId = /^id\s+"((?:[^"\\]|\\.)*)"$/;
13
+
14
+ export function validateInlineEvents(lines: string[], symbols: DocumentSymbols, application: DocumentSymbols): ValidationIssue[] {
15
+ lines = eventAnalysisSource(lines);
16
+ const issues: ValidationIssue[] = [];
17
+ const fences = fenceMap(lines);
18
+ const documentationBlocks = nonemptyMarkdownBlocks(lines, fences);
19
+ const commandProductions = new Set(symbols.commands.flatMap(command => command.productionHeaders ?? []));
20
+ const eventCounts = new Map<string, number>();
21
+ const importedNames = new Set<string>();
22
+ for (const document of [symbols, application]) {
23
+ for (const event of document.events) eventCounts.set(event.name, (eventCounts.get(event.name) ?? 0) + 1);
24
+ for (const imported of document.imports) importedNames.add(imported.shortName);
25
+ }
26
+ const report = (line: number, code: DiagnosticCode, message: string, severity: ValidationSeverity = 'error') => {
27
+ issues.push({ line, startColumn: indentOf(lines[line]) + 1, endColumn: lines[line].length + 1, code, message, severity });
28
+ };
29
+ for (const event of symbols.events) {
30
+ const body = directBody(lines, fences, event.line, indentOf(lines[event.line]));
31
+ if (event.inline) {
32
+ const properties = new Set<string>();
33
+ for (const property of event.properties) {
34
+ if (properties.has(property.name)) report(property.line, diagnosticCodes.duplicateDeclaration, `Event '${event.name}' already declares property '${property.name}'.`);
35
+ properties.add(property.name);
36
+ }
37
+ if (!commandProductions.has(event.line)) report(event.line, diagnosticCodes.inlineEventOutsideCommand, 'Inline events can only be declared inside commands.');
38
+ if (event.generation !== undefined) report(event.line, diagnosticCodes.inlineEventGeneration, 'Inline events are generation 1; extract the event before declaring generations.');
39
+ if ((eventCounts.get(event.name) ?? 0) > 1 || importedNames.has(event.name)) {
40
+ report(event.line, diagnosticCodes.inlineEventCollision, `Inline event '${event.name}' collides with another declaration or import.`);
41
+ }
42
+ }
43
+ let hasId = false;
44
+ let hasDocumentation = false;
45
+ for (const index of body) {
46
+ const text = lines[index].trim();
47
+ const keyword = text.split(/\s+/)[0];
48
+ if (event.inline && keyword === 'generation') report(index, diagnosticCodes.inlineEventGeneration, 'Inline events are generation 1; extract the event before declaring generations.');
49
+ if (event.inline && keyword === 'origin') report(index, diagnosticCodes.reservedProductionMetadata, 'An inline event is local to its command and cannot declare origin.');
50
+ // Property-shaped metadata names stay properties, whether standalone or typed mappings.
51
+ if (/^(?:id|description|documentation)\s+[\w.]+(?:\[\])?\??(?:\s*=.*)?$/.test(text)) continue;
52
+ if (keyword === 'id') {
53
+ const match = text.match(quotedId);
54
+ if (hasId || match === null || match[1].trim().length === 0) report(index, diagnosticCodes.invalidEventId, 'Expected one nonempty id "<old-name>".');
55
+ else if (match[1] === event.name) report(index, diagnosticCodes.redundantEventId, 'This id repeats the event name; remove it.', 'information');
56
+ hasId = true;
57
+ }
58
+ if (keyword === 'documentation') {
59
+ let next = index + 1;
60
+ while (next < lines.length && lines[next].trim().length === 0) next++;
61
+ if (hasDocumentation || text !== 'documentation' || lines[next]?.trim() !== '```markdown' || indentOf(lines[next]) <= indentOf(lines[index]) ||
62
+ !documentationBlocks.has(next)) {
63
+ report(index, diagnosticCodes.invalidEventDocumentation, 'Expected one nonempty fenced markdown documentation block.');
64
+ }
65
+ hasDocumentation = true;
66
+ }
67
+ }
68
+ }
69
+ // Also cover reaction productions without a backward ancestry walk per metadata line.
70
+ const productionIndents: number[] = [];
71
+ for (let index = 0; index < lines.length; index++) {
72
+ if (fences[index] || lines[index].trim().length === 0) continue;
73
+ const indent = indentOf(lines[index]);
74
+ while (productionIndents.length > 0 && productionIndents[productionIndents.length - 1] >= indent) productionIndents.pop();
75
+ const keyword = lines[index].trim().split(/\s+/)[0];
76
+ if (reserved.has(keyword) && productionIndents.length > 0) {
77
+ report(index, diagnosticCodes.reservedProductionMetadata, `'${keyword}' is system-assigned production metadata.`);
78
+ }
79
+ if (keyword === 'produces') productionIndents.push(indent);
80
+ }
81
+ for (const command of symbols.commands) {
82
+ const { identifier, mixed } = productionDestinations(command);
83
+ for (const production of command.produces ?? []) {
84
+ if (mixed && production.target === undefined) report(production.line, diagnosticCodes.explicitProducesTargetsRequired, `Production '${production.name}' must state for explicitly when destinations differ.`);
85
+ const destination = production.target ?? (production.inline ? identifier : undefined);
86
+ if (identifier === undefined || destination !== identifier) continue;
87
+ for (const mapping of production.mappings.filter(mapping => mapping.source === identifier)) {
88
+ report(mapping.line, diagnosticCodes.eventSourceIdInPayload, `The payload copies '${identifier}', which already identifies the event source.`, production.inline ? 'warning' : 'information');
89
+ }
90
+ }
91
+ }
92
+ return issues;
93
+ }
94
+
95
+ // Record complete, nonempty Markdown fences once. Validation must not scan a suffix
96
+ // for every documentation directive, especially while its opener is still being typed.
97
+ function nonemptyMarkdownBlocks(lines: string[], fences: boolean[]): Set<number> {
98
+ const blocks = new Set<number>();
99
+ let opening: number | undefined;
100
+ let content = false;
101
+ for (let index = 0; index < lines.length; index++) {
102
+ if (!fences[index]) continue;
103
+ const text = lines[index].trim();
104
+ if (opening === undefined) {
105
+ opening = index;
106
+ content = false;
107
+ } else if (text === '```') {
108
+ if (content && lines[opening].trim() === '```markdown') blocks.add(opening);
109
+ opening = undefined;
110
+ } else if (text.length > 0) {
111
+ content = true;
112
+ }
113
+ }
114
+ return blocks;
115
+ }
package/keyword-docs.ts CHANGED
@@ -20,7 +20,9 @@ export const keywordDocs: Record<string, string> = {
20
20
  template: 'Declares the named slots of a layout.',
21
21
  feature: 'A vertical slice grouping. Features nest arbitrarily deep.',
22
22
  slice: 'The atomic unit of behavior, aligned with Event Modeling. Has a type and a name.',
23
- event: 'An event type — an immutable, past-tense fact. Properties use concepts or primitives.',
23
+ event: 'An immutable, past-tense fact. Declare it in a slice or inline with `produces event <Name>` in a command. Inline properties are typed mappings; inline tags belong to the event type.',
24
+ documentation: 'Authoring-only event documentation in a fenced ```markdown block. It does not change executable model bytes.',
25
+ id: 'Preserves the previous persisted event name after a rename. Leave absent on new events; repeating the current name is redundant.',
24
26
  command: 'An imperative intent. Declares authorization, validation, and what events it produces — declaratively, or via a full handler.',
25
27
  query: 'A read-side entry point mapping to a return type, with an optional description, parameters and performer.',
26
28
  observable: 'Qualifies a query return type as a live read — `query <Name> => observable <ReadModel>` keeps pushing as the read model changes, instead of answering once.',
@@ -38,7 +40,7 @@ export const keywordDocs: Record<string, string> = {
38
40
  constraint: 'A server-side rule enforced in the Chronicle kernel before events are committed.',
39
41
  authorize: 'References the policies that must all pass for the construct to execute.',
40
42
  validate: 'Declarative validation rules, or `validate` followed by ```csharp for imperative rules — on commands and concepts.',
41
- produces: 'Declares the events a command emits — single, multiple, or conditional.',
43
+ produces: 'References a declared event with `produces <Name>`, or declares one inline with `produces event <Name>`. An inline omitted `for` uses the command identifier only when all destinations are the same source; legacy plain omission allocates an identity.',
42
44
  reads: 'Declares a view consulted by a command or reaction trigger: `reads <View> [as <alias>] [by <value>]`. A reaction `by` names a value taken by its trigger; clock triggers cannot use `by`. Repeated views require unique aliases. Runtime binding is not yet supported for command or reaction reads.',
43
45
  as: 'Names an instance of a view in a command or reaction trigger reads declaration, for example `reads Account as source by sourceId`.',
44
46
  handler: 'A fully imperative command implementation — a `file <Path>` reference or an inline `csharp` block, instead of `produces`.',
@@ -67,7 +69,7 @@ export const keywordDocs: Record<string, string> = {
67
69
  streamId: 'Concurrency dimension — scope the check to an event stream id.',
68
70
  tag: 'Attaches a tag to appended events — a static identifier or string, or a `$context.` expression resolved at append time.',
69
71
  seed: 'Declares events to seed into the event store per event source id — multiple blocks accumulate.',
70
- for: 'Introduces a seed group — the events to seed for one event source id.',
72
+ for: 'Names the event source of a production or seed group. Inside `produces event`, omission uses the command identifier unless another production targets a different source.',
71
73
  readmodel: 'Read model state in a specification — `given readmodel` establishes it, `then readmodel` asserts it, `then no readmodel <View> for <key>` asserts keyed absence.',
72
74
  no: 'A keyed absence assertion: `then no readmodel <View> for <key>`.',
73
75
  arguments: 'The values supplied to a query asserted by `then query`.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/screenplay-language",
3
- "version": "4.50.0",
3
+ "version": "4.51.0",
4
4
  "description": "Monaco language service for the Cratis Screenplay DSL — syntax highlighting, IntelliSense, hover and diagnostics for .play files",
5
5
  "keywords": [
6
6
  "cratis",
@@ -0,0 +1,32 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { DestinationHint } from './DestinationHint';
5
+ import { eventAnalysisSource } from './event-analysis-source';
6
+ import { CommandSymbol, scanDocument } from './symbols';
7
+
8
+ export function productionDestinations(command: CommandSymbol): { identifier?: string; mixed: boolean } {
9
+ const identifiers = command.properties.filter(property => property.isIdentifier && !property.type.includes('?') && !property.type.includes('[]'));
10
+ const identifier = identifiers.length === 1 ? identifiers[0].name : undefined;
11
+ const productions = command.produces ?? [];
12
+ const mixed = productions.some(production => production.target !== undefined && production.target !== identifier) ||
13
+ (productions.some(production => production.inline && production.target === undefined) &&
14
+ productions.some(production => !production.inline && production.target === undefined));
15
+ return { identifier, mixed };
16
+ }
17
+
18
+ // Shared by both editor adapters. Never suggest that a legacy allocated source is the command identifier.
19
+ export function destinationHints(lines: string[]): DestinationHint[] {
20
+ const source = eventAnalysisSource(lines);
21
+ return scanDocument(source).commands.flatMap(command => {
22
+ const { identifier, mixed } = productionDestinations(command);
23
+ if (mixed || command.productionHeaders?.length !== command.produces?.length) return [];
24
+ const hasPromotedDestination = command.produces?.some(sibling => sibling.target !== undefined || sibling.inline);
25
+ return (command.produces ?? []).flatMap(production => {
26
+ if (production.target !== undefined || (production.inline && (identifier === undefined || /\bgeneration\b/.test(source[production.line])))) return [];
27
+ // A sibling destination can promote the command default in the legacy binder.
28
+ if (!production.inline && hasPromotedDestination) return [];
29
+ return [{ line: production.line, column: source[production.line].length + 1, label: production.inline ? `for ${identifier}` : 'for <new event source>' }];
30
+ });
31
+ });
32
+ }
package/symbols.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  // Copyright (c) Cratis. All rights reserved.
2
2
  // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
3
 
4
- import { fenceMap, indentOf, withoutComment } from './document-context';
4
+ import { fenceMap, indentOf } from './document-context';
5
+ import { eventAnalysisSource } from './event-analysis-source';
5
6
  import { clauseKeywords } from './language';
7
+ import { ProductionSymbol } from './ProductionSymbol';
6
8
 
7
9
  export interface PropertySymbol {
8
10
  name: string;
@@ -35,6 +37,7 @@ export interface PolicySymbol {
35
37
  export interface EventSymbol {
36
38
  name: string;
37
39
  generation?: number;
40
+ inline?: boolean;
38
41
  properties: PropertySymbol[];
39
42
  line: number;
40
43
  }
@@ -42,6 +45,8 @@ export interface EventSymbol {
42
45
  export interface CommandSymbol extends NamedSymbol {
43
46
  properties: PropertySymbol[];
44
47
  reads?: ReadSymbol[];
48
+ produces?: ProductionSymbol[];
49
+ productionHeaders?: number[];
45
50
  }
46
51
 
47
52
  export interface ReadSymbol {
@@ -83,6 +88,10 @@ const conceptPattern = /^concept\s+(\w+)\s*:\s*(\w+)((?:\s+@\w+)*)\s*$/;
83
88
  const propertyPattern = /^\s*(@?[a-z_]\w*)\s+([\w.]+(?:\[\])?\??)(\s+identifier)?\s*$/;
84
89
  const attributeReasonPattern = /^([a-z_]\w*)\s+reason\s+"((?:[^"\\]|\\.)*)"\s*$/;
85
90
  const readPattern = /^\s*reads\s+([A-Z]\w*)(?:\s+as\s+([a-z_]\w*))?(?:\s+by\s+([a-z_]\w*))?\s*$/;
91
+ const commandReserved = ['authorize', 'produces', 'reads'];
92
+ // AuthorizeParser's continuation pattern, including the compiler's Unicode word characters.
93
+ const authorizationContinuation = /^(?:(?:or|and)\s+)?[A-Za-z_(][\p{L}\p{Mn}\p{Nd}\p{Pc}\s()]*$/u;
94
+ const eventReserved = clauseKeywords.filter(keyword => !['id', 'description', 'documentation'].includes(keyword));
86
95
  const queryParameterPattern =
87
96
  /^\s*(?:by|filter)\s+([a-z_]\w*)\s+([\w.]+(?:\[\])?\??)(?:\s+from\s+.+)?\s*$/;
88
97
 
@@ -116,6 +125,29 @@ function collectBody(lines: string[], fences: boolean[], start: number, indent:
116
125
  return body;
117
126
  }
118
127
 
128
+ // Event/production parsers accept every greater indent, not just the smallest child indent.
129
+ // Command block directives own their nested lines; properties do not. Fenced prose is never syntax.
130
+ export function directBody(lines: string[], fences: boolean[], start: number, indent: number): number[] {
131
+ const body = collectBody(lines, fences, start, indent).filter(index => !fences[index] && !/^\s*(?:\/\/|#)/.test(lines[index]));
132
+ if (!/^\s*command\b/.test(lines[start])) return body;
133
+ let blockIndent: number | undefined;
134
+ let authorization = false;
135
+ return body.filter(index => {
136
+ const childIndent = indentOf(lines[index]);
137
+ const text = lines[index].trim();
138
+ // AuthorizeParser owns only consecutive deeper lines with requirement shape.
139
+ // Unlike opaque blocks, a nonmatching line returns control to CommandParser.
140
+ if (blockIndent !== undefined && childIndent > blockIndent &&
141
+ (!authorization || authorizationContinuation.test(text))) return false;
142
+ const property = text !== 'validate csharp' && propertiesIn(lines, [index], commandReserved).length > 0;
143
+ // Description consumes only a quoted value or a fence (already excluded above).
144
+ const leaf = property || /^description(?:\s|$)/.test(text);
145
+ blockIndent = leaf ? undefined : childIndent;
146
+ authorization = /^authorize(?:\s|$)/.test(text);
147
+ return true;
148
+ });
149
+ }
150
+
119
151
  export function scanDocument(lines: string[]): DocumentSymbols {
120
152
  const symbols: DocumentSymbols = {
121
153
  imports: [],
@@ -128,9 +160,14 @@ export function scanDocument(lines: string[]): DocumentSymbols {
128
160
  screens: [],
129
161
  triggers: [],
130
162
  };
163
+ // One normalization pass for every declaration, including comments on fence openers.
164
+ lines = eventAnalysisSource(lines);
131
165
  const fences = fenceMap(lines);
132
- // Normalize only structural lines; quoted strings and fenced code retain their contents.
133
- lines = lines.map((line, index) => fences[index] ? line : withoutComment(line));
166
+ const eventLines = lines;
167
+ const eventFences = fences;
168
+ // Typed inline mappings share property syntax once their source expression is removed.
169
+ // Do this once, never once per inline event.
170
+ const eventPropertyLines = lines.map(line => line.replace(/\s*=(?!=|>).*/, ''));
134
171
 
135
172
  for (let index = 0; index < lines.length; index++) {
136
173
  if (fences[index]) continue;
@@ -138,7 +175,7 @@ export function scanDocument(lines: string[]): DocumentSymbols {
138
175
  const trimmed = line.trim();
139
176
  const indent = indentOf(line);
140
177
 
141
- const importMatch = trimmed.match(/^import\s+([\w.]+)\s*$/);
178
+ const importMatch = eventLines[index].trim().match(/^import\s+([\w.]+)\s*$/);
142
179
  if (importMatch && indent === 0) {
143
180
  const qualifiedName = importMatch[1];
144
181
  const shortName = qualifiedName.split('.').pop() ?? qualifiedName;
@@ -190,33 +227,47 @@ export function scanDocument(lines: string[]): DocumentSymbols {
190
227
  continue;
191
228
  }
192
229
 
193
- const eventMatch = trimmed.match(/^event\s+(\w+)(?:\s+generation\s+(\d+))?\s*$/);
230
+ const eventMatch = eventLines[index].trim().match(/^(?:produces\s+)?event\s+(\w+)(?:\s+generation\s+(\d+))?\s*$/);
194
231
  if (eventMatch) {
195
232
  symbols.events.push({
196
233
  name: eventMatch[1],
197
234
  ...(eventMatch[2] ? { generation: Number(eventMatch[2]) } : {}),
198
- properties: propertiesIn(lines, collectBody(lines, fences, index, indent), clauseKeywords),
235
+ inline: trimmed.startsWith('produces '),
236
+ properties: propertiesIn(trimmed.startsWith('produces ') ? eventPropertyLines : eventLines,
237
+ directBody(eventLines, eventFences, index, indent), eventReserved),
199
238
  line: index,
200
239
  });
201
240
  continue;
202
241
  }
203
242
 
204
- const commandMatch = trimmed.match(/^command\s+(\w+)\s*$/);
243
+ const commandMatch = eventLines[index].trim().match(/^command\s+(\w+)\s*$/);
205
244
  if (commandMatch) {
206
- const body = collectBody(lines, fences, index, indent);
207
- // The body is already comment-normalized and fence-free. Track indentation once,
208
- // rather than walking back to the document root for every property-shaped line.
209
- const ancestors = [indent];
210
- const directChildren = body.filter(line => {
211
- const childIndent = indentOf(lines[line]);
212
- while (ancestors[ancestors.length - 1] >= childIndent) ancestors.pop();
213
- const direct = ancestors.length === 1;
214
- ancestors.push(childIndent);
215
- return direct && lines[line].trim() !== 'validate csharp';
216
- });
245
+ // A command property is a leaf, not an indentation owner. Share the parser-shaped
246
+ // body with properties, productions, advice and destination hints.
247
+ const body = directBody(lines, fences, index, indent);
248
+ const productionHeaders = body.filter(line => /^\s*produces\b/.test(lines[line]));
217
249
  symbols.commands.push({
218
250
  name: commandMatch[1],
219
- properties: propertiesIn(lines, directChildren, ['authorize', 'produces', 'reads']),
251
+ properties: propertiesIn(lines, body.filter(line => lines[line].trim() !== 'validate csharp'), commandReserved),
252
+ productionHeaders,
253
+ produces: productionHeaders.flatMap(line => {
254
+ const header = eventLines[line].trim();
255
+ const inline = /^produces\s+event\b/.test(header);
256
+ const conditional = /^produces\s+when\b/.test(header);
257
+ const eventLine = conditional ? directBody(eventLines, eventFences, line, indentOf(eventLines[line]))[0] : line;
258
+ if (eventLine === undefined) return [];
259
+ const name = conditional ? eventLines[eventLine].trim() : header.match(inline ? /^produces\s+event\s+([A-Za-z_]\w*)(?:\s+generation\s+\d+)?\s*$/ : /^produces\s+([A-Z]\w*)\s*$/)?.[1];
260
+ if (name === undefined || !/^[A-Za-z_]\w*$/.test(name)) return [];
261
+ const children = directBody(eventLines, eventFences, eventLine, indentOf(eventLines[eventLine]));
262
+ const targets = children.map(index => eventLines[index].trim().match(/^for(?:\s+(.*))?$/)).filter(match => match !== null);
263
+ // Empty or repeated targets are uncertain, not implicit destinations.
264
+ const target = targets.length === 0 ? undefined : targets.length === 1 ? targets[0][1] ?? '' : '';
265
+ const mappings = children.flatMap(index => {
266
+ const match = eventLines[index].trim().match(inline ? /^(@?[a-z_]\w*)\s+[\w.[\]?]+\s*=(?!=|>)\s*(.+)$/ : /^(@?[\w.]+)\s*=(?!=|>)\s*(.+)$/);
267
+ return match === null ? [] : [{ name: match[1].replace(/^@/, ''), source: match[2], line: index }];
268
+ });
269
+ return [{ name, inline, conditional, line, target, mappings }];
270
+ }),
220
271
  reads: body.filter((line) => !fences[line])
221
272
  .map((line) => ({ line, match: lines[line].match(readPattern) }))
222
273
  .filter((entry): entry is { line: number; match: RegExpMatchArray } => entry.match !== null)
package/tokens.ts CHANGED
@@ -59,9 +59,11 @@ export function createTokensProvider(subLanguages: SubLanguage[]): languages.IMo
59
59
  [/^(\s*)(then)(\s+)(result|no\s+result)\b/, ['white', 'keyword', 'white', 'keyword']],
60
60
  // A quoted import names .play files rather than a qualified name - the path reads as a link.
61
61
  [/^(\s*)(import)(\s+)("[^"\\]*")/, ['white', 'keyword', 'white', 'string.link']],
62
- // Only an event header reserves 'generation'; properties and context paths do not.
63
- [/^(\s*)(event)(\s+)([A-Za-z_]\w*)(\s+)(generation)(?=\s+\d+\s*$)/,
64
- ['white', 'keyword', 'white', 'type.identifier', 'white', 'keyword']],
62
+ // Retain the header indent so event metadata stops at the enclosing block boundary.
63
+ [/^(\s*)((?:produces\s+)?event)(\s+)([A-Za-z_]\w*)(\s+)(generation)(\s+)(\d+)(?=\s*(?:\/\/.*)?$)/,
64
+ ['white', 'keyword', 'white', 'type.identifier', 'white', 'keyword', 'white', { token: 'number', next: '@eventBody.$1' }]],
65
+ [/^(\s*)((?:produces\s+)?event)(\s+)([A-Za-z_]\w*)(?=\s*(?:\/\/.*)?$)/,
66
+ ['white', 'keyword', 'white', { token: 'type.identifier', next: '@eventBody.$1' }]],
65
67
  // A tagged opening fence carries the embedded language; legacy tag lines still highlight.
66
68
  ...codeBlockTags.map(
67
69
  (tag): MonarchTokenRules[number] => [
@@ -111,6 +113,13 @@ export function createTokensProvider(subLanguages: SubLanguage[]): languages.IMo
111
113
  { include: '@common' },
112
114
  ],
113
115
 
116
+ eventBody: [
117
+ [/^(?!$S2[ \t]+|\s*$)/, { token: '@rematch', next: '@pop' }],
118
+ [/^(\s*)(id)(?=\s+")/, ['white', 'keyword']],
119
+ [/^(\s*)(documentation)(?=\s*(?:\/\/.*)?$)/, ['white', { token: 'keyword', next: '@descriptionBlockPending' }]],
120
+ { include: '@root' },
121
+ ],
122
+
114
123
  common: commonTokenRules,
115
124
 
116
125
  // After a code tag, the only thing allowed before the opening fence is whitespace.
@@ -131,7 +140,8 @@ export function createTokensProvider(subLanguages: SubLanguage[]): languages.IMo
131
140
 
132
141
  // After a bare description, the only thing allowed before the opening fence is whitespace.
133
142
  descriptionBlockPending: [
134
- [/^\s*```(?:text)?\s*$/, { token: 'string.quote', switchTo: '@descriptionBlock' }],
143
+ [/\/\/.*$/, 'comment'],
144
+ [/^\s*```(?:text|markdown)?\s*$/, { token: 'string.quote', switchTo: '@descriptionBlock' }],
135
145
  [/^\s*[^\s`].*$/, { token: '@rematch', next: '@pop' }],
136
146
  [/\s+/, 'white'],
137
147
  ],
package/validation.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  // Copyright (c) Cratis. All rights reserved.
2
2
  // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
3
 
4
+ import { validateInlineEvents } from './inline-event-validation';
4
5
  import { causedByProperties, contextRoots, identityProperties, primitiveTypes, sliceTypes } from './language';
5
6
  import { DiagnosticCode, diagnosticCodes } from './diagnostic-codes';
6
- import { enclosingChain, fenceMap, indentOf, withoutComment } from './document-context';
7
+ import { enclosingChain, fenceMap, indentOf } from './document-context';
8
+ import { eventAnalysisSource } from './event-analysis-source';
7
9
  import { resolveEventContextPath } from './event-context';
8
10
  import {
9
11
  DocumentSymbols,
@@ -139,7 +141,7 @@ export function validateLines(lines: string[], context: ValidationContext = {}):
139
141
  const events = new Set([...knownEventNames(symbols), ...knownEventNames(application)]);
140
142
  const policies = new Set([...symbols.policies, ...application.policies].map((policy) => policy.name));
141
143
  const issues: ValidationIssue[] = validateDeclarations(lines, symbols, application);
142
- issues.push(...validateProductionDestinations(lines, fences, symbols));
144
+ issues.push(...validateProductionDestinations(lines, symbols));
143
145
 
144
146
  const checkEvent = (line: number, text: string, name: string) => {
145
147
  if (!events.has(name)) {
@@ -326,6 +328,7 @@ export function validateLines(lines: string[], context: ValidationContext = {}):
326
328
  }
327
329
 
328
330
  issues.push(...validateEventContextPaths(lines, fences));
331
+ issues.push(...validateInlineEvents(lines, symbols, application));
329
332
 
330
333
  const fenceLines = lines
331
334
  .map((line, index) => ({ line, index }))
@@ -348,36 +351,18 @@ export function validateLines(lines: string[], context: ValidationContext = {}):
348
351
  }
349
352
 
350
353
  // This is advice, not a semantic default: accepting the typed workspace repair changes routing.
351
- function validateProductionDestinations(lines: string[], fences: boolean[], symbols: DocumentSymbols): ValidationIssue[] {
354
+ function validateProductionDestinations(lines: string[], symbols: DocumentSymbols): ValidationIssue[] {
352
355
  const issues: ValidationIssue[] = [];
353
- lines = lines.map((line, index) => fences[index] ? line : withoutComment(line));
356
+ lines = eventAnalysisSource(lines);
354
357
  for (const command of symbols.commands) {
355
358
  const identifiers = command.properties.filter(property => property.isIdentifier && !property.type.endsWith('?') && !property.type.endsWith('[]'));
356
359
  if (identifiers.length !== 1) continue;
357
- const commandIndent = indentOf(lines[command.line]);
358
- const ancestors = [commandIndent];
359
- for (let line = command.line + 1; line < lines.length; line++) {
360
- const text = lines[line].trim();
361
- if (fences[line] || text.length === 0) continue;
362
- const indent = indentOf(lines[line]);
363
- if (indent <= commandIndent) break;
364
- while (ancestors[ancestors.length - 1] >= indent) ancestors.pop();
365
- const direct = ancestors.length === 1;
366
- ancestors.push(indent);
367
- const produces = text.match(/^produces\s+([A-Z]\w*)$/);
368
- if (!produces || !direct) continue;
369
- let explicit = false;
370
- for (let child = line + 1; child < lines.length; child++) {
371
- const body = lines[child].trim();
372
- if (fences[child] || body.length === 0) continue;
373
- if (indentOf(lines[child]) <= indent) break;
374
- if (/^for\s+/.test(body)) explicit = true;
375
- }
376
- if (!explicit) {
377
- issues.push(issue('information', line, indent + 1, text.length,
378
- `Plain 'produces ${produces[1]}' omits its destination — use 'for ${identifiers[0].name}' to explicitly select the command's identifier.`,
379
- diagnosticCodes.omittedProductionDestination));
380
- }
360
+ for (const production of command.produces ?? []) {
361
+ if (production.inline || production.conditional || production.target !== undefined) continue;
362
+ const line = production.line;
363
+ issues.push(issue('information', line, indentOf(lines[line]) + 1, lines[line].trim().length,
364
+ `Plain 'produces ${production.name}' omits its destination — use 'for ${identifiers[0].name}' to explicitly select the command's identifier.`,
365
+ diagnosticCodes.omittedProductionDestination));
381
366
  }
382
367
  }
383
368
  return issues;