@cratis/screenplay-language 4.255.0 → 4.257.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 (49) hide show
  1. package/dist/bundles/compiler/Authoring/QuickFixes.js +2 -2
  2. package/dist/bundles/compiler/Authoring/QuickFixes.js.map +1 -1
  3. package/dist/bundles/compiler/Diagnostics/DiagnosticCodes.js +1 -1
  4. package/dist/bundles/compiler/Diagnostics/DiagnosticCodes.js.map +1 -1
  5. package/dist/bundles/compiler/Files/PlayApplicationAssembly.js +1 -1
  6. package/dist/bundles/compiler/Files/PlayApplicationAssembly.js.map +1 -1
  7. package/dist/bundles/compiler/Files/PlayFolderMerge.js +1 -1
  8. package/dist/bundles/compiler/Parsing/AuthorizeParser.js +1 -1
  9. package/dist/bundles/compiler/Parsing/AuthorizeParser.js.map +1 -1
  10. package/dist/bundles/compiler/Parsing/CaptureParser.js +1 -1
  11. package/dist/bundles/compiler/Parsing/CommandHandlerValidator.js +1 -1
  12. package/dist/bundles/compiler/Parsing/CommandHandlerValidator.js.map +1 -1
  13. package/dist/bundles/compiler/Parsing/CommandParser.js +1 -1
  14. package/dist/bundles/compiler/Parsing/CommandParser.js.map +1 -1
  15. package/dist/bundles/compiler/Parsing/FeatureBody.js +1 -1
  16. package/dist/bundles/compiler/Parsing/ImplementationParser.js +2 -2
  17. package/dist/bundles/compiler/Parsing/ImplementationParser.js.map +1 -1
  18. package/dist/bundles/compiler/Parsing/ModuleBody.js +1 -1
  19. package/dist/bundles/compiler/Parsing/PossibleEventsParser.js +2 -0
  20. package/dist/bundles/compiler/Parsing/PossibleEventsParser.js.map +1 -0
  21. package/dist/bundles/compiler/Parsing/ProducesParser.js +1 -1
  22. package/dist/bundles/compiler/Parsing/ProjectionParser.js +1 -1
  23. package/dist/bundles/compiler/Parsing/ProjectionParser.js.map +1 -1
  24. package/dist/bundles/compiler/Parsing/QueryParser.js +1 -1
  25. package/dist/bundles/compiler/Parsing/ReadModelMemberTypeValidator.js +2 -0
  26. package/dist/bundles/compiler/Parsing/ReadModelMemberTypeValidator.js.map +1 -0
  27. package/dist/bundles/compiler/Parsing/ScreenParser.js +1 -1
  28. package/dist/bundles/compiler/Parsing/ScreenplayParser.js +1 -1
  29. package/dist/bundles/compiler/Parsing/ScreenplayParser.js.map +1 -1
  30. package/dist/bundles/compiler/Parsing/SliceParser.js +1 -1
  31. package/dist/bundles/compiler/ScreenplayCompiler.js +1 -1
  32. package/dist/bundles/compiler/ScreenplayCompiler.js.map +1 -1
  33. package/dist/bundles/compiler/Syntax/ScreenplaySyntaxWalker.js +1 -1
  34. package/dist/bundles/compiler/Syntax/ScreenplaySyntaxWalker.js.map +1 -1
  35. package/dist/bundles/compiler/Syntax/SyntaxCollections.js +1 -1
  36. package/dist/bundles/compiler/Syntax/SyntaxCollections.js.map +1 -1
  37. package/dist/bundles/compiler/Syntax/SyntaxJson.js +1 -1
  38. package/dist/bundles/compiler/Syntax/SyntaxJson.js.map +1 -1
  39. package/dist/bundles/compiler/index.js +1 -1
  40. package/dist/bundles/diagnostic-codes.js +1 -1
  41. package/dist/bundles/diagnostic-codes.js.map +1 -1
  42. package/dist/bundles/keyword-docs.js +1 -1
  43. package/dist/bundles/keyword-docs.js.map +1 -1
  44. package/dist/bundles/validation.js +1 -1
  45. package/dist/bundles/validation.js.map +1 -1
  46. package/dist/diagnostic-codes.d.ts +1 -0
  47. package/dist/diagnostic-codes.d.ts.map +1 -1
  48. package/dist/validation.d.ts.map +1 -1
  49. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"PlayApplicationAssembly.js","names":["rootPaths","roots","resolveImports","source","languages","merged","documents","imports","document","discoverImports","orderingRoot","presentationRoot","selectOrderingRoot","recordAuthoredOrder","syntax","timeline","timelineOrderDiagnostics","all","diagnostics","diagnostic","deferImportedExampleTypes","candidates","CommandStreamCandidates","splitLines","physical","parseForAuthoring","physicalEventSources","result","index","sourceInventoryComplete","EventSourceReadConfidence","parsed","mergeDocuments","context","ParserContext","LineReader","effectiveStructuralInteractions","site","ancestor","validateSpecificationCases","validateSpecificationExampleTypes","effective","expandSpecificationExamples","validateEventSources","validateOperations","validatePublicEventUsage","validateInlineEvents","validateConstraintProperties","validateResponses","validateProjectionTargets","validateIdentifierCompliance","validateEventSubjects","validateReadModelKeys","validateReactionRefusals","validateSpecificationRedelivery","validateGuardedActions","validatePersonaCallers","validatePurposes","value","validateDependencyDeclarations","DeclaredDependencies","productionDestinationDiagnostics","existing","reported","normalized","path","normalizePlayPath","inMemoryDocumentSource"],"sources":["../../../../../../Compiler/Files/PlayApplicationAssembly.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Diagnostic } from '../Diagnostics/Diagnostic';\nimport { validateSpecificationCases } from '../Parsing/SpecificationCaseValidator';\nimport { expandSpecificationExamples, validateSpecificationExampleTypes } from '../Parsing/SpecificationCommandExamples';\nimport { productionDestinationDiagnostics } from '../Diagnostics/ProductionDestinationDiagnostics';\nimport { validateConstraintProperties } from '../Parsing/ConstraintPropertyValidator';\nimport { validateDependencyDeclarations } from '../Dependencies/DeclaredDependencyTargets';\nimport { DeclaredDependencies } from '../Dependencies/DeclaredDependencies';\nimport { validateInlineEvents } from '../Parsing/InlineEventValidator';\nimport { LineReader } from '../Parsing/LineReader';\nimport { CommandStreamCandidates } from '../Parsing/CommandStreamCandidates';\nimport { validateEventSources } from '../Parsing/EventSourceValidator';\nimport { validateProjectionTargets } from '../Parsing/ProjectionTargetValidator';\nimport { validateIdentifierCompliance } from '../Parsing/IdentifierComplianceValidator';\nimport { validateEventSubjects } from '../Parsing/EventSubjectValidator';\nimport { validateReadModelKeys } from '../Parsing/ReadModelKeyValidator';\nimport { validateReactionRefusals } from '../Parsing/ReactionRefusalValidator';\nimport { validateSpecificationRedelivery } from '../Parsing/SpecificationRedeliveryValidator';\nimport { effectiveStructuralInteractions } from '../Parsing/StructuralInteractionSites';\nimport { validateGuardedActions } from '../Parsing/GuardedActionValidator';\nimport { validatePersonaCallers } from '../Parsing/PersonaCallerValidator';\nimport { validatePurposes } from '../Parsing/PurposeValidator';\nimport { splitLines } from '../Parsing/SourceLineSplitter';\nimport { ParserContext } from '../Parsing/ParserContext';\nimport { validateResponses } from '../Parsing/ResponseValidator';\nimport { validatePublicEventUsage } from '../Parsing/PublicEventUsageValidator';\nimport { validateOperations } from '../Parsing/OperationValidator';\nimport { CompilationResult, discoverImports, parseForAuthoring } from '../ScreenplayCompiler';\nimport { ApplicationSyntax } from '../Syntax/Structure';\nimport { EventSourceSyntax } from '../Syntax/EventSources';\nimport { EventSourceReadConfidence } from '../Syntax/EventSourceReadConfidence';\nimport { mergeDocuments } from './PlayFolderMerge';\nimport { inMemoryDocumentSource, PlacedPlayDocument, PlayDocumentSource } from './PlayDocumentSource';\nimport { normalizePlayPath } from './PlayGlob';\nimport { resolveImports } from './PlayImports';\nimport { recordAuthoredOrder } from './AuthoredOrder';\nimport { selectOrderingRoot } from './OrderingRoot';\nimport { timelineOrderDiagnostics } from './TimelineOrder';\n\n// One .play document of a folder: its path relative to the folder, and its text.\nexport interface PlayFileSource {\n readonly path: string;\n readonly source: string;\n}\n\n// One application compiled from documents: the documents that make it up, each with where its top level\n// belongs, and the merged syntax with every diagnostic - resolving, parsing and merging.\nexport interface ApplicationCompilation extends CompilationResult<ApplicationSyntax> {\n readonly documents: readonly PlacedPlayDocument[];\n}\n\n// Assembles one application from documents - following their imports from the roots, parsing each where it is\n// placed, and merging the lot. The port of the C# PlayApplicationAssembly.Compile.\nexport function assembleApplication(roots: Iterable<string>, source: PlayDocumentSource, languages?: ReadonlySet<string>, presentationRoot?: string | null): ApplicationCompilation {\n const rootPaths = [...roots];\n const { documents, diagnostics } = resolveImports(rootPaths, source, languages);\n const { result: merged, syntax } = parsePlacedDocumentsWithSyntax(documents, languages);\n // Resolution owns its import inventory; share one discovery between the presentation passes.\n const imports = new Map(documents.map(document => [document.path, discoverImports(document.source, document.path, languages)]));\n const orderingRoot = presentationRoot === null ? undefined : selectOrderingRoot(presentationRoot === undefined ? rootPaths : [presentationRoot], documents, languages, imports);\n if (orderingRoot !== undefined) recordAuthoredOrder(merged.value, [orderingRoot], documents, languages, syntax, imports);\n const timeline = orderingRoot === undefined ? [] : timelineOrderDiagnostics(merged.value);\n const all = [...diagnostics, ...merged.diagnostics, ...timeline];\n return { ...merged, documents, diagnostics: all, success: !all.some(diagnostic => diagnostic.severity === 'error') };\n}\n\n// Parses documents whose source identities and placements are already known (for example unsaved\n// editor buffers), then validates contracts against the merged declaration inventory. Editor callers may\n// defer example types whose imports are not in that inventory; resolved types are still checked.\nexport function parsePlacedDocuments(documents: readonly PlacedPlayDocument[], languages?: ReadonlySet<string>, deferImportedExampleTypes = false): CompilationResult<ApplicationSyntax> & {\n readonly physicalEventSources: readonly { source: EventSourceSyntax; placementResolved: boolean }[];\n readonly sourceInventoryComplete: boolean;\n readonly continuationValues: ReturnType<typeof parseForAuthoring>['continuationValues'];\n} {\n return parsePlacedDocumentsWithSyntax(documents, languages, deferImportedExampleTypes).result;\n}\n\nfunction parsePlacedDocumentsWithSyntax(documents: readonly PlacedPlayDocument[], languages?: ReadonlySet<string>, deferImportedExampleTypes = false) {\n const candidates = CommandStreamCandidates.capturePlaced(documents.filter(document => document.isPlacementResolved !== false).map(document => ({ lines: splitLines(document.source, false, document.path), placement: document.placement })), languages);\n const physical = documents.map(document => parseForAuthoring(document.source, document.path, document.isPlacementResolved === false ? [] : document.placement, false, candidates, languages));\n const physicalEventSources = physical.flatMap((result, index) => (result.value.eventSources ?? []).map(source => ({ source, placementResolved: documents[index].isPlacementResolved !== false })));\n const sourceInventoryComplete = documents.every(document => document.isPlacementResolved !== false) && physical.every(result => !EventSourceReadConfidence.hasUnknownExtent(result.diagnostics));\n const parsed = physical.map((result, index) => documents[index].isPlacementResolved === false ? { ...result, value: { ...result.value, eventSources: [] } } : result);\n const merged = mergeDocuments(parsed);\n const context = new ParserContext(new LineReader([]), undefined, languages);\n if (merged.value.sourceOptions !== undefined) context.sourceOptions = merged.value.sourceOptions;\n context.guardedInteractions.push(...parsed.flatMap(document => document.guardedInteractions));\n context.interactionBehaviors.push(...parsed.flatMap(document => document.interactionBehaviors));\n context.interactionUses.push(...effectiveStructuralInteractions(merged.value).filter(site => 'behavior' in site),\n ...parsed.flatMap(document => document.interactionUses).filter(site => site.ancestors.some(ancestor => ancestor.keyword === 'screen')));\n context.continuationValues.push(...parsed.flatMap(document => document.continuationValues));\n validateSpecificationCases(merged.value, context);\n validateSpecificationExampleTypes(merged.value, context, deferImportedExampleTypes);\n const effective = expandSpecificationExamples(merged.value);\n validateEventSources(merged.value, context);\n validateOperations(merged.value, context);\n validatePublicEventUsage(merged.value, context);\n validateInlineEvents(merged.value, context);\n validateConstraintProperties(merged.value, context);\n validateResponses(effective, context, parsed.flatMap(document => document.inputUses));\n validateProjectionTargets(merged.value, context);\n validateIdentifierCompliance(effective, context);\n validateEventSubjects(merged.value, context);\n validateReadModelKeys(merged.value, context);\n validateReactionRefusals(merged.value, context);\n validateSpecificationRedelivery(merged.value, context);\n validateGuardedActions(merged.value, context);\n validatePersonaCallers(merged.value, context);\n validatePurposes(merged.value, context);\n const value = validateDependencyDeclarations(merged.value, context);\n DeclaredDependencies.validate(value, context);\n for (const diagnostic of productionDestinationDiagnostics(value)) context.information(diagnostic.code, diagnostic.message, diagnostic.location);\n const existing = merged.diagnostics;\n const reported = new Set(existing.map(diagnosticKey));\n const all = [...existing, ...context.diagnostics.filter(diagnostic => !reported.has(diagnosticKey(diagnostic)))];\n return {\n result: { ...merged, value, diagnostics: all, success: !all.some(diagnostic => diagnostic.severity === 'error'), physicalEventSources, sourceInventoryComplete, continuationValues: context.continuationValues },\n syntax: new Map(parsed.map((result, index) => [documents[index].path, result.value])),\n };\n}\n\nfunction diagnosticKey(diagnostic: Diagnostic): string {\n return JSON.stringify([diagnostic.code, diagnostic.location.path, diagnostic.location.line, diagnostic.location.column]);\n}\n\n// Compiles documents held in memory, keyed by portable path, as one application. Without roots every\n// document is a root, in ordinal order of its path - a folder compiled as one application, where a file an\n// import places in a module or feature is placed there. With roots, only those documents and what they import\n// make up the application - a single file compiled with its imports followed. The default sort compares\n// UTF-16 code units, which is the C# ordinal order.\nexport function compileApplication(documents: ReadonlyMap<string, string>, roots?: readonly string[], languages?: ReadonlySet<string>, presentationRoot?: string | null): ApplicationCompilation {\n const normalized = new Map([...documents].map(([path, source]) => [normalizePlayPath(path), source]));\n return assembleApplication(roots ?? [...normalized.keys()].sort(), inMemoryDocumentSource(normalized), languages, presentationRoot);\n}\n\n// Compiles the documents of a folder as one application - the counterpart of the C# CompileFolder. Every\n// document is a root, read in ordinal order of its relative path as the C# compiler reads them, so a merge\n// keeps the same first declaration in either language; one an import places in a module or feature is\n// placed there.\nexport function parseFolder(files: readonly PlayFileSource[], languages?: ReadonlySet<string>): ApplicationCompilation {\n return compileApplication(new Map(files.map(file => [file.path, file.source])), undefined, languages);\n}\n\n"],"mappings":"ykFAuDA,SAAgB,oBAAoB,EAAyB,EAA4B,EAAiC,EAA0D,CAChL,IAAMA,EAAY,CAAC,GAAGC,CAAK,EACrB,CAAE,YAAW,eAAgBC,EAAeF,EAAWG,EAAQC,CAAS,EACxE,CAAE,OAAQC,EAAQ,UAAW,+BAA+BC,EAAWF,CAAS,EAEhFG,EAAU,IAAI,IAAID,EAAU,IAAI,GAAY,CAACE,EAAS,KAAMC,EAAgBD,EAAS,OAAQA,EAAS,KAAMJ,CAAS,CAAC,CAAC,CAAC,EACxHM,EAAeC,IAAqB,KAAO,IAAA,GAAYC,EAAmBD,IAAqB,IAAA,GAAYX,EAAY,CAACW,CAAgB,EAAGL,EAAWF,EAAWG,CAAO,EAC1KG,IAAiB,IAAA,IAAWG,EAAoBR,EAAO,MAAO,CAACK,CAAY,EAAGJ,EAAWF,EAAWU,EAAQP,CAAO,EACvH,IAAMQ,EAAWL,IAAiB,IAAA,GAAY,CAAC,EAAIM,EAAyBX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{"version":3,"file":"PlayApplicationAssembly.js","names":["rootPaths","roots","resolveImports","source","languages","merged","documents","imports","document","discoverImports","orderingRoot","presentationRoot","selectOrderingRoot","recordAuthoredOrder","syntax","timeline","timelineOrderDiagnostics","all","diagnostics","diagnostic","deferImportedExampleTypes","candidates","CommandStreamCandidates","splitLines","physical","parseForAuthoring","physicalEventSources","result","index","sourceInventoryComplete","EventSourceReadConfidence","parsed","mergeDocuments","context","ParserContext","LineReader","effectiveStructuralInteractions","site","ancestor","validateSpecificationCases","validateSpecificationExampleTypes","effective","expandSpecificationExamples","validateEventSources","validateOperations","validatePublicEventUsage","validateInlineEvents","validateConstraintProperties","validateResponses","validateProjectionTargets","validateIdentifierCompliance","validateEventSubjects","validateReadModelKeys","validateReadModelMemberTypes","validateReactionRefusals","validateSpecificationRedelivery","validateGuardedActions","validatePersonaCallers","validatePurposes","value","validateDependencyDeclarations","DeclaredDependencies","productionDestinationDiagnostics","existing","reported","normalized","path","normalizePlayPath","inMemoryDocumentSource"],"sources":["../../../../../../Compiler/Files/PlayApplicationAssembly.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Diagnostic } from '../Diagnostics/Diagnostic';\nimport { validateSpecificationCases } from '../Parsing/SpecificationCaseValidator';\nimport { expandSpecificationExamples, validateSpecificationExampleTypes } from '../Parsing/SpecificationCommandExamples';\nimport { productionDestinationDiagnostics } from '../Diagnostics/ProductionDestinationDiagnostics';\nimport { validateConstraintProperties } from '../Parsing/ConstraintPropertyValidator';\nimport { validateDependencyDeclarations } from '../Dependencies/DeclaredDependencyTargets';\nimport { DeclaredDependencies } from '../Dependencies/DeclaredDependencies';\nimport { validateInlineEvents } from '../Parsing/InlineEventValidator';\nimport { LineReader } from '../Parsing/LineReader';\nimport { CommandStreamCandidates } from '../Parsing/CommandStreamCandidates';\nimport { validateEventSources } from '../Parsing/EventSourceValidator';\nimport { validateProjectionTargets } from '../Parsing/ProjectionTargetValidator';\nimport { validateIdentifierCompliance } from '../Parsing/IdentifierComplianceValidator';\nimport { validateEventSubjects } from '../Parsing/EventSubjectValidator';\nimport { validateReadModelKeys } from '../Parsing/ReadModelKeyValidator';\nimport { validateReadModelMemberTypes } from '../Parsing/ReadModelMemberTypeValidator';\nimport { validateReactionRefusals } from '../Parsing/ReactionRefusalValidator';\nimport { validateSpecificationRedelivery } from '../Parsing/SpecificationRedeliveryValidator';\nimport { effectiveStructuralInteractions } from '../Parsing/StructuralInteractionSites';\nimport { validateGuardedActions } from '../Parsing/GuardedActionValidator';\nimport { validatePersonaCallers } from '../Parsing/PersonaCallerValidator';\nimport { validatePurposes } from '../Parsing/PurposeValidator';\nimport { splitLines } from '../Parsing/SourceLineSplitter';\nimport { ParserContext } from '../Parsing/ParserContext';\nimport { validateResponses } from '../Parsing/ResponseValidator';\nimport { validatePublicEventUsage } from '../Parsing/PublicEventUsageValidator';\nimport { validateOperations } from '../Parsing/OperationValidator';\nimport { CompilationResult, discoverImports, parseForAuthoring } from '../ScreenplayCompiler';\nimport { ApplicationSyntax } from '../Syntax/Structure';\nimport { EventSourceSyntax } from '../Syntax/EventSources';\nimport { EventSourceReadConfidence } from '../Syntax/EventSourceReadConfidence';\nimport { mergeDocuments } from './PlayFolderMerge';\nimport { inMemoryDocumentSource, PlacedPlayDocument, PlayDocumentSource } from './PlayDocumentSource';\nimport { normalizePlayPath } from './PlayGlob';\nimport { resolveImports } from './PlayImports';\nimport { recordAuthoredOrder } from './AuthoredOrder';\nimport { selectOrderingRoot } from './OrderingRoot';\nimport { timelineOrderDiagnostics } from './TimelineOrder';\n\n// One .play document of a folder: its path relative to the folder, and its text.\nexport interface PlayFileSource {\n readonly path: string;\n readonly source: string;\n}\n\n// One application compiled from documents: the documents that make it up, each with where its top level\n// belongs, and the merged syntax with every diagnostic - resolving, parsing and merging.\nexport interface ApplicationCompilation extends CompilationResult<ApplicationSyntax> {\n readonly documents: readonly PlacedPlayDocument[];\n}\n\n// Assembles one application from documents - following their imports from the roots, parsing each where it is\n// placed, and merging the lot. The port of the C# PlayApplicationAssembly.Compile.\nexport function assembleApplication(roots: Iterable<string>, source: PlayDocumentSource, languages?: ReadonlySet<string>, presentationRoot?: string | null): ApplicationCompilation {\n const rootPaths = [...roots];\n const { documents, diagnostics } = resolveImports(rootPaths, source, languages);\n const { result: merged, syntax } = parsePlacedDocumentsWithSyntax(documents, languages);\n // Resolution owns its import inventory; share one discovery between the presentation passes.\n const imports = new Map(documents.map(document => [document.path, discoverImports(document.source, document.path, languages)]));\n const orderingRoot = presentationRoot === null ? undefined : selectOrderingRoot(presentationRoot === undefined ? rootPaths : [presentationRoot], documents, languages, imports);\n if (orderingRoot !== undefined) recordAuthoredOrder(merged.value, [orderingRoot], documents, languages, syntax, imports);\n const timeline = orderingRoot === undefined ? [] : timelineOrderDiagnostics(merged.value);\n const all = [...diagnostics, ...merged.diagnostics, ...timeline];\n return { ...merged, documents, diagnostics: all, success: !all.some(diagnostic => diagnostic.severity === 'error') };\n}\n\n// Parses documents whose source identities and placements are already known (for example unsaved\n// editor buffers), then validates contracts against the merged declaration inventory. Editor callers may\n// defer example types whose imports are not in that inventory; resolved types are still checked.\nexport function parsePlacedDocuments(documents: readonly PlacedPlayDocument[], languages?: ReadonlySet<string>, deferImportedExampleTypes = false): CompilationResult<ApplicationSyntax> & {\n readonly physicalEventSources: readonly { source: EventSourceSyntax; placementResolved: boolean }[];\n readonly sourceInventoryComplete: boolean;\n readonly continuationValues: ReturnType<typeof parseForAuthoring>['continuationValues'];\n} {\n return parsePlacedDocumentsWithSyntax(documents, languages, deferImportedExampleTypes).result;\n}\n\nfunction parsePlacedDocumentsWithSyntax(documents: readonly PlacedPlayDocument[], languages?: ReadonlySet<string>, deferImportedExampleTypes = false) {\n const candidates = CommandStreamCandidates.capturePlaced(documents.filter(document => document.isPlacementResolved !== false).map(document => ({ lines: splitLines(document.source, false, document.path), placement: document.placement })), languages);\n const physical = documents.map(document => parseForAuthoring(document.source, document.path, document.isPlacementResolved === false ? [] : document.placement, false, candidates, languages));\n const physicalEventSources = physical.flatMap((result, index) => (result.value.eventSources ?? []).map(source => ({ source, placementResolved: documents[index].isPlacementResolved !== false })));\n const sourceInventoryComplete = documents.every(document => document.isPlacementResolved !== false) && physical.every(result => !EventSourceReadConfidence.hasUnknownExtent(result.diagnostics));\n const parsed = physical.map((result, index) => documents[index].isPlacementResolved === false ? { ...result, value: { ...result.value, eventSources: [] } } : result);\n const merged = mergeDocuments(parsed);\n const context = new ParserContext(new LineReader([]), undefined, languages);\n if (merged.value.sourceOptions !== undefined) context.sourceOptions = merged.value.sourceOptions;\n context.guardedInteractions.push(...parsed.flatMap(document => document.guardedInteractions));\n context.interactionBehaviors.push(...parsed.flatMap(document => document.interactionBehaviors));\n context.interactionUses.push(...effectiveStructuralInteractions(merged.value).filter(site => 'behavior' in site),\n ...parsed.flatMap(document => document.interactionUses).filter(site => site.ancestors.some(ancestor => ancestor.keyword === 'screen')));\n context.continuationValues.push(...parsed.flatMap(document => document.continuationValues));\n validateSpecificationCases(merged.value, context);\n validateSpecificationExampleTypes(merged.value, context, deferImportedExampleTypes);\n const effective = expandSpecificationExamples(merged.value);\n validateEventSources(merged.value, context);\n validateOperations(merged.value, context);\n validatePublicEventUsage(merged.value, context);\n validateInlineEvents(merged.value, context);\n validateConstraintProperties(merged.value, context);\n validateResponses(effective, context, parsed.flatMap(document => document.inputUses));\n validateProjectionTargets(merged.value, context);\n validateIdentifierCompliance(effective, context);\n validateEventSubjects(merged.value, context);\n validateReadModelKeys(merged.value, context);\n validateReadModelMemberTypes(merged.value, context);\n validateReactionRefusals(merged.value, context);\n validateSpecificationRedelivery(merged.value, context);\n validateGuardedActions(merged.value, context);\n validatePersonaCallers(merged.value, context);\n validatePurposes(merged.value, context);\n const value = validateDependencyDeclarations(merged.value, context);\n DeclaredDependencies.validate(value, context);\n for (const diagnostic of productionDestinationDiagnostics(value)) context.information(diagnostic.code, diagnostic.message, diagnostic.location);\n const existing = merged.diagnostics;\n const reported = new Set(existing.map(diagnosticKey));\n const all = [...existing, ...context.diagnostics.filter(diagnostic => !reported.has(diagnosticKey(diagnostic)))];\n return {\n result: { ...merged, value, diagnostics: all, success: !all.some(diagnostic => diagnostic.severity === 'error'), physicalEventSources, sourceInventoryComplete, continuationValues: context.continuationValues },\n syntax: new Map(parsed.map((result, index) => [documents[index].path, result.value])),\n };\n}\n\nfunction diagnosticKey(diagnostic: Diagnostic): string {\n return JSON.stringify([diagnostic.code, diagnostic.location.path, diagnostic.location.line, diagnostic.location.column]);\n}\n\n// Compiles documents held in memory, keyed by portable path, as one application. Without roots every\n// document is a root, in ordinal order of its path - a folder compiled as one application, where a file an\n// import places in a module or feature is placed there. With roots, only those documents and what they import\n// make up the application - a single file compiled with its imports followed. The default sort compares\n// UTF-16 code units, which is the C# ordinal order.\nexport function compileApplication(documents: ReadonlyMap<string, string>, roots?: readonly string[], languages?: ReadonlySet<string>, presentationRoot?: string | null): ApplicationCompilation {\n const normalized = new Map([...documents].map(([path, source]) => [normalizePlayPath(path), source]));\n return assembleApplication(roots ?? [...normalized.keys()].sort(), inMemoryDocumentSource(normalized), languages, presentationRoot);\n}\n\n// Compiles the documents of a folder as one application - the counterpart of the C# CompileFolder. Every\n// document is a root, read in ordinal order of its relative path as the C# compiler reads them, so a merge\n// keeps the same first declaration in either language; one an import places in a module or feature is\n// placed there.\nexport function parseFolder(files: readonly PlayFileSource[], languages?: ReadonlySet<string>): ApplicationCompilation {\n return compileApplication(new Map(files.map(file => [file.path, file.source])), undefined, languages);\n}\n\n"],"mappings":"mqFAwDA,SAAgB,oBAAoB,EAAyB,EAA4B,EAAiC,EAA0D,CAChL,IAAMA,EAAY,CAAC,GAAGC,CAAK,EACrB,CAAE,YAAW,eAAgBC,EAAeF,EAAWG,EAAQC,CAAS,EACxE,CAAE,OAAQC,EAAQ,UAAW,+BAA+BC,EAAWF,CAAS,EAEhFG,EAAU,IAAI,IAAID,EAAU,IAAI,GAAY,CAAC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KAAMA,EAAW,SAAS,KAAMA,EAAW,SAAS,MAAM,CAAC,CAC3H,CAOA,SAAgB,mBAAmB,EAAwC,EAA2B,EAAiC,EAA0D,CAC7L,IAAM8C,EAAa,IAAI,IAAI,CAAC,GAAG3D,CAAS,CAAC,CAAC,KAAK,CAAC4D,EAAM/D,KAAY,CAACgE,EAAkBD,CAAI,EAAG/D,CAAM,CAAC,CAAC,EACpG,OAAO,oBAAoBF,GAAS,CAAC,GAAGgE,EAAW,KAAK,CAAC,CAAC,CAAC,KAAK,EAAGG,EAAuBH,CAAU,EAAG7D,EAAWO,CAAgB,CACtI"}
@@ -1,2 +1,2 @@
1
- import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";import{validateIdentity as t}from"../Parsing/IdentityValidator.js";import{validateApplicationHandlers as n}from"../Parsing/CommandHandlerValidator.js";import{mergeStructuralInteractions as r}from"../Parsing/StructuralInteractionSites.js";import{combineAuthorize as i}from"../Parsing/AuthorizeParser.js";import{LineReader as a}from"../Parsing/LineReader.js";import{InvalidSyntaxJson as o}from"../Syntax/InvalidSyntaxJson.js";import{invalidSourceOptions as s,isAuthoredDocument as c,legacySourceOptions as l,validatedSourceOptions as u}from"../Syntax/SourceOptions.js";import{ParserContext as d}from"../Parsing/ParserContext.js";import{toSyntaxJson as f}from"../Syntax/SyntaxJson.js";function mergeDocuments(i){let c=[],f=i.map(e=>e.value),p=/* @__PURE__ */ new Map,m=!1;for(let t of f)try{p.set(t,Object.hasOwn(t,`sourceOptions`)?u(t.sourceOptions):l)}catch(n){if(!(n instanceof o))throw n;m=!0,c.push(error(e.IncompatibleNumericSource,n.message,t.location))}let h=f.filter(e=>p.get(e)?.numericMode===`exact`||hasDeclarations(e)),g=p.get(h[0])??l;for(let t of h.slice(1))p.get(t)?.numericMode!==g.numericMode&&(m=!0,c.push(error(e.MixedNumericModes,`Declaration-bearing documents and marked import barrels must independently select the same numeric mode.`,t.location)));m&&(g=s);let _=/* @__PURE__ */ new Map,v=declaredInOneFile(f.flatMap(e=>e.concepts),`declaration of`,c,void 0,_),y=declaredInOneFile(f.flatMap(e=>e.types),`declaration of`,c,void 0,_),b=f.flatMap(e=>e.identity==null?[]:[e.identity]);for(let t of b.slice(1))c.push(error(e.RepeatedSingularDeclarationAcrossFiles,`The folder already declares an identity block in '${describe(b[0].location.path)}' - a folder compiles to one application, which can have at most one`,t.location));let x=f.filter(e=>e.commandReadMode!=null);for(let t of x.slice(1))c.push(error(e.InvalidCommandReadsDeclaration,`Declare 'command reads protected' once at the application root.`,t.location));let S=f.filter(e=>e.timeZone!=null);for(let t of S.slice(1))c.push(error(e.InvalidTimeZoneDeclaration,`Declare 'time zone' once at the application root.`,t.location));let C=f.filter(e=>e.reactionProductionMode!=null);for(let t of C.slice(1))c.push(error(e.InvalidReactionBatchesDeclaration,`Declare 'reaction batches atomic' once at the application root.`,t.location));let w=f.map(e=>e.domain).filter(e=>e!==null);for(let t of w.slice(1))c.push(error(e.RepeatedSingularDeclarationAcrossFiles,`The folder already declares a domain in '${describe(w[0].location.path)}' - a folder compiles to one application, which can have at most one`,t.location));let T=mergeModules(f.flatMap(e=>e.modules),c),E=declaredInOneFile(f.flatMap(e=>e.personas),`persona`,c),D=f.flatMap(e=>e.policies??[]),O=declaredInOneFile(D,`policy`,c),k=D.filter(e=>!O.includes(e)).map(e=>e.location),A={kind:`ApplicationSyntax`,sourceOptions:g,...C.length===0?{}:{reactionProductionMode:C[0].reactionProductionMode},...x.length===0?{}:{commandReadMode:x[0].commandReadMode},...S.length===0?{}:{timeZone:S[0].timeZone},...b.length===0?{}:{identity:b[0]},domain:w[0]??null,imports:firstOfEach(f.flatMap(e=>e.imports),e=>e.qualifiedName),concepts:v,types:y,examples:f.flatMap(e=>e.examples??[]),systems:f.flatMap(e=>e.systems??[]),purposes:declaredInOneFile(f.flatMap(e=>e.purposes??[]),`purpose`,c),eventSources:f.flatMap(e=>e.eventSources??[]),declaredTriggers:f.flatMap(e=>e.declaredTriggers??[]),modules:T,personas:E,policies:O,seeds:f.flatMap(e=>e.seeds??[]),fileImports:f.flatMap(e=>e.fileImports),...presentOnly(`stickyNotes`,f.flatMap(e=>e.stickyNotes??[])),...presentOnly(`exposures`,f.flatMap(e=>e.exposures??[])),...presentOnly(`instanceContributions`,f.flatMap(e=>e.instanceContributions??[])),location:f[0]?.location??{line:1,column:1}};r(A,f);let j=new d(new a([]));n(A,j),t(A,j),c.push(...j.diagnostics);let M=[...i.flatMap(e=>e.diagnostics).filter(t=>t.code!==e.DuplicateDeclaration||!k.some(e=>sameLocation(e,t.location))),...c];return{value:A,diagnostics:M,success:!M.some(e=>e.severity===`error`)}}function hasDeclarations(e){if(c(e)||e.identity!=null||e.domain!==null||e.concepts.length>0||e.types.length>0||e.personas.length>0||(e.policies?.length??0)>0||(e.purposes?.length??0)>0||(e.seeds?.length??0)>0||(e.systems?.length??0)>0||(e.eventSources?.length??0)>0||(e.examples?.length??0)>0||(e.stickyNotes?.length??0)>0)return!0;let feature=e=>!e.isPlacement||(e.examples?.length??0)>0||e.slices.length>0||e.features.some(feature);return e.modules.some(e=>!e.isPlacement||(e.examples?.length??0)>0||e.features.some(feature))}function mergeModules(e,t){return groupByName(e).map(placedLast).map(e=>{if(e.length===1)return r({...e[0],isPlacement:!1,features:e[0].features.map(unplaced)},e);let n=r({...e[0],isPlacement:!1,fileImports:e.flatMap(e=>e.fileImports),examples:e.flatMap(e=>e.examples??[]),purposes:firstOfEach(e.flatMap(e=>e.purposes??[]),e=>e.name),description:firstDescription(e,`module '${e[0].name}'`,t),documentation:firstDocumentation(e,`module '${e[0].name}'`,t),authorize:combineAuthorization(e.map(e=>e.authorize),`module '${e[0].name}'`,t),dependsOn:groupDependencies(e)},e,t);return r({...n,features:mergeFeatures(e.flatMap(e=>e.features),t)},[n])})}function mergeFeatures(e,t){return groupByName(e).map(placedLast).map(e=>{if(e.length===1)return unplaced(e[0]);let n=r({...e[0],isPlacement:!1,fileImports:e.flatMap(e=>e.fileImports),examples:e.flatMap(e=>e.examples??[]),purposes:firstOfEach(e.flatMap(e=>e.purposes??[]),e=>e.name),description:firstDescription(e,`feature '${e[0].name}'`,t),documentation:firstDocumentation(e,`feature '${e[0].name}'`,t),authorize:combineAuthorization(e.map(e=>e.authorize),`feature '${e[0].name}'`,t),dependsOn:groupDependencies(e)},e,t);return r({...n,features:mergeFeatures(e.flatMap(e=>e.features),t),slices:declaredInOneFile(e.flatMap(e=>e.slices),`slice`,t,`feature '${e[0].name}'`)},[n])})}function groupDependencies(e){return[...e].sort((e,t)=>(e.location.path??``)<(t.location.path??``)?-1:+((e.location.path??``)>(t.location.path??``))).flatMap(e=>e.dependsOn??[])}function placedLast(e){return[...e.filter(e=>!e.isPlacement),...e.filter(e=>e.isPlacement)]}function unplaced(e){return r({...e,isPlacement:!1,features:e.features.map(unplaced)},[e])}function combineAuthorization(t,n,r){let a=[];for(let i of t.filter(e=>e!==null)){let t=a.find(e=>e.location.path!==i.location.path&&JSON.stringify(f(e))===JSON.stringify(f(i)));t===void 0?a.push(i):r.push(warning(e.DuplicateAuthorizationAcrossFiles,`An identical authorization is already declared on the ${n} in '${describe(t.location.path)}' - this repeated gate is ignored`,i.location))}return a.reduce((e,t)=>i(e,t),null)}function firstOfEach(e,t){let n=/* @__PURE__ */ new Set;return e.filter(e=>!n.has(t(e))&&n.add(t(e))!==void 0)}function groupByName(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.name,[...t.get(n.name)??[],n]);return[...t.values()]}function firstDocumentation(t,n,r){let i=t.filter(e=>e.documentation!=null);for(let t of i.slice(1).filter(e=>e.documentation!==i[0].documentation))r.push(warning(e.ConflictingDocumentationAcrossFiles,`The ${n} is already documented in '${describe(i[0].location.path)}' - keeping that documentation`,t.location));return i[0]?.documentation??null}function firstDescription(t,n,r){let i=t.filter(e=>e.description!==null);for(let t of i.slice(1).filter(e=>e.description!==i[0].description))r.push(warning(e.ConflictingDescriptionAcrossFiles,`The ${n} is already described in '${describe(i[0].location.path)}' - keeping that description`,t.location));return i[0]?.description??null}function declaredInOneFile(t,n,r,i,a=/* @__PURE__ */ new Map){let o=[];for(let s of t){let t=a.get(s.name);t!==void 0&&t.path!==s.location.path?r.push(error(e.RepeatedDeclarationAcrossFiles,`Duplicate ${n} '${s.name}'${i===void 0?``:` in ${i}`} - already declared in '${describe(t.path)}'`,s.location)):(t===void 0&&a.set(s.name,s.location),o.push(s))}return o}const describe=e=>e??`another file`,sameLocation=(e,t)=>e.path===t.path&&e.line===t.line&&e.column===t.column,error=(e,t,n)=>({severity:`error`,code:e,message:t,location:n}),warning=(e,t,n)=>({severity:`warning`,code:e,message:t,location:n});function presentOnly(e,t){return t.length===0?{}:{[e]:t}}export{mergeDocuments};
1
+ import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";import{combineAuthorize as t}from"../Parsing/AuthorizeParser.js";import{validateIdentity as n}from"../Parsing/IdentityValidator.js";import{validateApplicationHandlers as r}from"../Parsing/CommandHandlerValidator.js";import{mergeStructuralInteractions as i}from"../Parsing/StructuralInteractionSites.js";import{LineReader as a}from"../Parsing/LineReader.js";import{InvalidSyntaxJson as o}from"../Syntax/InvalidSyntaxJson.js";import{invalidSourceOptions as s,isAuthoredDocument as c,legacySourceOptions as l,validatedSourceOptions as u}from"../Syntax/SourceOptions.js";import{ParserContext as d}from"../Parsing/ParserContext.js";import{toSyntaxJson as f}from"../Syntax/SyntaxJson.js";function mergeDocuments(t){let c=[],f=t.map(e=>e.value),p=/* @__PURE__ */ new Map,m=!1;for(let t of f)try{p.set(t,Object.hasOwn(t,`sourceOptions`)?u(t.sourceOptions):l)}catch(n){if(!(n instanceof o))throw n;m=!0,c.push(error(e.IncompatibleNumericSource,n.message,t.location))}let h=f.filter(e=>p.get(e)?.numericMode===`exact`||hasDeclarations(e)),g=p.get(h[0])??l;for(let t of h.slice(1))p.get(t)?.numericMode!==g.numericMode&&(m=!0,c.push(error(e.MixedNumericModes,`Declaration-bearing documents and marked import barrels must independently select the same numeric mode.`,t.location)));m&&(g=s);let _=/* @__PURE__ */ new Map,v=declaredInOneFile(f.flatMap(e=>e.concepts),`declaration of`,c,void 0,_),y=declaredInOneFile(f.flatMap(e=>e.types),`declaration of`,c,void 0,_),b=f.flatMap(e=>e.identity==null?[]:[e.identity]);for(let t of b.slice(1))c.push(error(e.RepeatedSingularDeclarationAcrossFiles,`The folder already declares an identity block in '${describe(b[0].location.path)}' - a folder compiles to one application, which can have at most one`,t.location));let x=f.filter(e=>e.commandReadMode!=null);for(let t of x.slice(1))c.push(error(e.InvalidCommandReadsDeclaration,`Declare 'command reads protected' once at the application root.`,t.location));let S=f.filter(e=>e.timeZone!=null);for(let t of S.slice(1))c.push(error(e.InvalidTimeZoneDeclaration,`Declare 'time zone' once at the application root.`,t.location));let C=f.filter(e=>e.reactionProductionMode!=null);for(let t of C.slice(1))c.push(error(e.InvalidReactionBatchesDeclaration,`Declare 'reaction batches atomic' once at the application root.`,t.location));let w=f.map(e=>e.domain).filter(e=>e!==null);for(let t of w.slice(1))c.push(error(e.RepeatedSingularDeclarationAcrossFiles,`The folder already declares a domain in '${describe(w[0].location.path)}' - a folder compiles to one application, which can have at most one`,t.location));let T=mergeModules(f.flatMap(e=>e.modules),c),E=declaredInOneFile(f.flatMap(e=>e.personas),`persona`,c),D=f.flatMap(e=>e.policies??[]),O=declaredInOneFile(D,`policy`,c),k=D.filter(e=>!O.includes(e)).map(e=>e.location),A={kind:`ApplicationSyntax`,sourceOptions:g,...C.length===0?{}:{reactionProductionMode:C[0].reactionProductionMode},...x.length===0?{}:{commandReadMode:x[0].commandReadMode},...S.length===0?{}:{timeZone:S[0].timeZone},...b.length===0?{}:{identity:b[0]},domain:w[0]??null,imports:firstOfEach(f.flatMap(e=>e.imports),e=>e.qualifiedName),concepts:v,types:y,examples:f.flatMap(e=>e.examples??[]),systems:f.flatMap(e=>e.systems??[]),purposes:declaredInOneFile(f.flatMap(e=>e.purposes??[]),`purpose`,c),eventSources:f.flatMap(e=>e.eventSources??[]),declaredTriggers:f.flatMap(e=>e.declaredTriggers??[]),modules:T,personas:E,policies:O,seeds:f.flatMap(e=>e.seeds??[]),fileImports:f.flatMap(e=>e.fileImports),...presentOnly(`stickyNotes`,f.flatMap(e=>e.stickyNotes??[])),...presentOnly(`exposures`,f.flatMap(e=>e.exposures??[])),...presentOnly(`instanceContributions`,f.flatMap(e=>e.instanceContributions??[])),location:f[0]?.location??{line:1,column:1}};i(A,f);let j=new d(new a([]));r(A,j),n(A,j),c.push(...j.diagnostics);let M=[...t.flatMap(e=>e.diagnostics).filter(t=>t.code!==e.DuplicateDeclaration||!k.some(e=>sameLocation(e,t.location))),...c];return{value:A,diagnostics:M,success:!M.some(e=>e.severity===`error`)}}function hasDeclarations(e){if(c(e)||e.identity!=null||e.domain!==null||e.concepts.length>0||e.types.length>0||e.personas.length>0||(e.policies?.length??0)>0||(e.purposes?.length??0)>0||(e.seeds?.length??0)>0||(e.systems?.length??0)>0||(e.eventSources?.length??0)>0||(e.examples?.length??0)>0||(e.stickyNotes?.length??0)>0)return!0;let feature=e=>!e.isPlacement||(e.examples?.length??0)>0||e.slices.length>0||e.features.some(feature);return e.modules.some(e=>!e.isPlacement||(e.examples?.length??0)>0||e.features.some(feature))}function mergeModules(e,t){return groupByName(e).map(placedLast).map(e=>{if(e.length===1)return i({...e[0],isPlacement:!1,features:e[0].features.map(unplaced)},e);let n=i({...e[0],isPlacement:!1,fileImports:e.flatMap(e=>e.fileImports),examples:e.flatMap(e=>e.examples??[]),purposes:firstOfEach(e.flatMap(e=>e.purposes??[]),e=>e.name),description:firstDescription(e,`module '${e[0].name}'`,t),documentation:firstDocumentation(e,`module '${e[0].name}'`,t),authorize:combineAuthorization(e.map(e=>e.authorize),`module '${e[0].name}'`,t),dependsOn:groupDependencies(e)},e,t);return i({...n,features:mergeFeatures(e.flatMap(e=>e.features),t)},[n])})}function mergeFeatures(e,t){return groupByName(e).map(placedLast).map(e=>{if(e.length===1)return unplaced(e[0]);let n=i({...e[0],isPlacement:!1,fileImports:e.flatMap(e=>e.fileImports),examples:e.flatMap(e=>e.examples??[]),purposes:firstOfEach(e.flatMap(e=>e.purposes??[]),e=>e.name),description:firstDescription(e,`feature '${e[0].name}'`,t),documentation:firstDocumentation(e,`feature '${e[0].name}'`,t),authorize:combineAuthorization(e.map(e=>e.authorize),`feature '${e[0].name}'`,t),dependsOn:groupDependencies(e)},e,t);return i({...n,features:mergeFeatures(e.flatMap(e=>e.features),t),slices:declaredInOneFile(e.flatMap(e=>e.slices),`slice`,t,`feature '${e[0].name}'`)},[n])})}function groupDependencies(e){return[...e].sort((e,t)=>(e.location.path??``)<(t.location.path??``)?-1:+((e.location.path??``)>(t.location.path??``))).flatMap(e=>e.dependsOn??[])}function placedLast(e){return[...e.filter(e=>!e.isPlacement),...e.filter(e=>e.isPlacement)]}function unplaced(e){return i({...e,isPlacement:!1,features:e.features.map(unplaced)},[e])}function combineAuthorization(n,r,i){let a=[];for(let t of n.filter(e=>e!==null)){let n=a.find(e=>e.location.path!==t.location.path&&JSON.stringify(f(e))===JSON.stringify(f(t)));n===void 0?a.push(t):i.push(warning(e.DuplicateAuthorizationAcrossFiles,`An identical authorization is already declared on the ${r} in '${describe(n.location.path)}' - this repeated gate is ignored`,t.location))}return a.reduce((e,n)=>t(e,n),null)}function firstOfEach(e,t){let n=/* @__PURE__ */ new Set;return e.filter(e=>!n.has(t(e))&&n.add(t(e))!==void 0)}function groupByName(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.name,[...t.get(n.name)??[],n]);return[...t.values()]}function firstDocumentation(t,n,r){let i=t.filter(e=>e.documentation!=null);for(let t of i.slice(1).filter(e=>e.documentation!==i[0].documentation))r.push(warning(e.ConflictingDocumentationAcrossFiles,`The ${n} is already documented in '${describe(i[0].location.path)}' - keeping that documentation`,t.location));return i[0]?.documentation??null}function firstDescription(t,n,r){let i=t.filter(e=>e.description!==null);for(let t of i.slice(1).filter(e=>e.description!==i[0].description))r.push(warning(e.ConflictingDescriptionAcrossFiles,`The ${n} is already described in '${describe(i[0].location.path)}' - keeping that description`,t.location));return i[0]?.description??null}function declaredInOneFile(t,n,r,i,a=/* @__PURE__ */ new Map){let o=[];for(let s of t){let t=a.get(s.name);t!==void 0&&t.path!==s.location.path?r.push(error(e.RepeatedDeclarationAcrossFiles,`Duplicate ${n} '${s.name}'${i===void 0?``:` in ${i}`} - already declared in '${describe(t.path)}'`,s.location)):(t===void 0&&a.set(s.name,s.location),o.push(s))}return o}const describe=e=>e??`another file`,sameLocation=(e,t)=>e.path===t.path&&e.line===t.line&&e.column===t.column,error=(e,t,n)=>({severity:`error`,code:e,message:t,location:n}),warning=(e,t,n)=>({severity:`warning`,code:e,message:t,location:n});function presentOnly(e,t){return t.length===0?{}:{[e]:t}}export{mergeDocuments};
2
2
  //# sourceMappingURL=PlayFolderMerge.js.map
@@ -1,2 +1,2 @@
1
- import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";import{pattern as t}from"../Text/patterns.js";import{locationOf as n}from"./SourceLine.js";const r=t(`^(?:(?:or|and)\\s+)?[A-Za-z_(][\\w\\s()]*$`),i=new RegExp(t(`\\(|\\)|[A-Za-z_]\\w*`).source,`gu`),a=t(`^[A-Z]\\w*$`);function parseAuthorize(t,i){let a=i.content.substring(9);for(let e=t.peekChild(i.indent);e!==void 0&&r.test(e.content);e=t.peekChild(i.indent))t.reader.takeSignificant(),a+=` ${e.content}`;let o=tokenize(a),s=n(i);if(o.length===0)return t.error(e.AuthorizeWithoutPolicy,`Expected at least one policy after 'authorize'`,s),null;let c=new RequirementParser(t,o,s).parse();return c===null?null:{kind:`AuthorizeSyntax`,requirement:c,location:s}}function combineAuthorize(e,t){return e===null?t:t===null?e:{kind:`AuthorizeSyntax`,requirement:{kind:`LogicalPolicyRequirementSyntax`,left:e.requirement,operator:`And`,right:t.requirement,location:e.location},location:e.location}}function tokenize(e){let t=[];for(let n of e.match(i)??[])t.length>0&&isOperandEnd(t[t.length-1])&&isOperandStart(n)&&t.push(`and`),t.push(n);return t}const isName=e=>e!==`(`&&e!==`)`&&e!==`and`&&e!==`or`,isOperandEnd=e=>e===`)`||isName(e),isOperandStart=e=>e===`(`||isName(e);var RequirementParser=class{context;tokens;location;#e=0;constructor(e,t,n){this.context=e,this.tokens=t,this.location=n}parse(){let t=this.#t();return t!==null&&this.#e<this.tokens.length&&this.context.error(e.UnexpectedTokenInAuthorize,`Unexpected '${this.tokens[this.#e]}' in authorize`,this.location),t}#t(){return this.#r(`or`,`Or`,()=>this.#n())}#n(){return this.#r(`and`,`And`,()=>this.#i())}#r(e,t,n){let r=n();for(;r!==null&&this.tokens[this.#e]===e;){this.#e++;let e=n();if(e===null)return null;r={kind:`LogicalPolicyRequirementSyntax`,left:r,operator:t,right:e,location:this.location}}return r}#i(){if(this.tokens[this.#e]!==`(`)return this.#a();this.#e++;let t=this.#t();return this.tokens[this.#e]===`)`?this.#e++:this.context.error(e.UnclosedAuthorizeGroup,`Expected ')' in authorize`,this.location),t}#a(){if(this.#e>=this.tokens.length)return this.context.error(e.AuthorizeWithoutPolicy,`Expected a policy name`,this.location),null;let t=this.tokens[this.#e++];return a.test(t)?{kind:`PolicyReferenceSyntax`,name:t,location:this.location}:(this.context.error(e.InvalidPolicyReference,`Invalid policy reference '${t}' - policy names are PascalCase identifiers`,this.location),null)}};export{combineAuthorize,parseAuthorize};
1
+ import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";import{pattern as t}from"../Text/patterns.js";import{locationOf as n}from"./SourceLine.js";const r=t(`^(?:(?:or|and)\\s+)?[A-Za-z_(][\\w\\s()]*$`),i=new RegExp(t(`\\(|\\)|[A-Za-z_]\\w*`).source,`gu`),a=t(`^[A-Z]\\w*$`);function parseAuthorize(t,i){let a=i.content.substring(9);for(let e=t.peekChild(i.indent);e!==void 0&&r.test(e.content);e=t.peekChild(i.indent))t.reader.takeSignificant(),a+=` ${e.content}`;let o=tokenize(a),s=n(i);if(o.length===0)return t.error(e.AuthorizeWithoutPolicy,`Expected at least one policy after 'authorize'`,s),null;hasImplicitConjunction(a)&&t.information(e.ImplicitAuthorizationConjunction,`Write 'and' between adjacent policies in 'authorize'.`,s);let c=new RequirementParser(t,o,s).parse();return c===null?null:{kind:`AuthorizeSyntax`,requirement:c,location:s}}function combineAuthorize(e,t){return e===null?t:t===null?e:{kind:`AuthorizeSyntax`,requirement:{kind:`LogicalPolicyRequirementSyntax`,left:e.requirement,operator:`And`,right:t.requirement,location:e.location},location:e.location}}function tokenize(e){let t=[];for(let n of e.match(i)??[])t.length>0&&isOperandEnd(t[t.length-1])&&isOperandStart(n)&&t.push(`and`),t.push(n);return t}function isAuthorizeContinuation(e){return r.test(e)}function implicitConjunctionTokens(e,t){let n=[];for(let r of e.matchAll(i))t!==void 0&&isOperandEnd(t)&&isOperandStart(r[0])&&n.push({index:r.index,length:r[0].length}),t=r[0];return{tokens:n,previous:t}}function hasImplicitConjunction(e){return implicitConjunctionTokens(e,void 0).tokens.length>0}const isName=e=>e!==`(`&&e!==`)`&&e!==`and`&&e!==`or`,isOperandEnd=e=>e===`)`||isName(e),isOperandStart=e=>e===`(`||isName(e);var RequirementParser=class{context;tokens;location;#e=0;constructor(e,t,n){this.context=e,this.tokens=t,this.location=n}parse(){let t=this.#t();return t!==null&&this.#e<this.tokens.length&&this.context.error(e.UnexpectedTokenInAuthorize,`Unexpected '${this.tokens[this.#e]}' in authorize`,this.location),t}#t(){return this.#r(`or`,`Or`,()=>this.#n())}#n(){return this.#r(`and`,`And`,()=>this.#i())}#r(e,t,n){let r=n();for(;r!==null&&this.tokens[this.#e]===e;){this.#e++;let e=n();if(e===null)return null;r={kind:`LogicalPolicyRequirementSyntax`,left:r,operator:t,right:e,location:this.location}}return r}#i(){if(this.tokens[this.#e]!==`(`)return this.#a();this.#e++;let t=this.#t();return this.tokens[this.#e]===`)`?this.#e++:this.context.error(e.UnclosedAuthorizeGroup,`Expected ')' in authorize`,this.location),t}#a(){if(this.#e>=this.tokens.length)return this.context.error(e.AuthorizeWithoutPolicy,`Expected a policy name`,this.location),null;let t=this.tokens[this.#e++];return a.test(t)?{kind:`PolicyReferenceSyntax`,name:t,location:this.location}:(this.context.error(e.InvalidPolicyReference,`Invalid policy reference '${t}' - policy names are PascalCase identifiers`,this.location),null)}};export{combineAuthorize,implicitConjunctionTokens,isAuthorizeContinuation,parseAuthorize};
2
2
  //# sourceMappingURL=AuthorizeParser.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AuthorizeParser.js","names":["continuationPattern","pattern","tokenPattern","namePattern","text","line","child","context","tokens","location","locationOf","DiagnosticCodes","requirement","first","next","token","#or","#position","#chain","#and","#groupOrReference","left","operand","right","#reference"],"sources":["../../../../../../Compiler/Parsing/AuthorizeParser.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { DiagnosticCodes } from '../Diagnostics/DiagnosticCodes';\nimport { SourceLocation } from '../Diagnostics/SourceLocation';\nimport { AuthorizeSyntax, LogicalOperator, PolicyRequirementSyntax } from '../Syntax/Authorization';\nimport { pattern } from '../Text/patterns';\nimport { ParserContext } from './ParserContext';\nimport { locationOf, SourceLine } from './SourceLine';\n\nconst continuationPattern = pattern('^(?:(?:or|and)\\\\s+)?[A-Za-z_(][\\\\w\\\\s()]*$');\nconst tokenPattern = new RegExp(pattern('\\\\(|\\\\)|[A-Za-z_]\\\\w*').source, 'gu');\nconst namePattern = pattern('^[A-Z]\\\\w*$');\n\n// The port of the C# AuthorizeParser: the requirement may continue on the lines below the 'authorize', and\n// two operands written side by side are joined by an implicit 'and'.\nexport function parseAuthorize(context: ParserContext, line: SourceLine): AuthorizeSyntax | null {\n let text = line.content.substring('authorize'.length);\n for (let child = context.peekChild(line.indent); child !== undefined && continuationPattern.test(child.content); child = context.peekChild(line.indent)) {\n context.reader.takeSignificant();\n text += ` ${child.content}`;\n }\n const tokens = tokenize(text);\n const location = locationOf(line);\n if (tokens.length === 0) {\n context.error(DiagnosticCodes.AuthorizeWithoutPolicy, 'Expected at least one policy after \\'authorize\\'', location);\n return null;\n }\n const parser = new RequirementParser(context, tokens, location);\n const requirement = parser.parse();\n return requirement === null ? null : { kind: 'AuthorizeSyntax', requirement, location };\n}\n\n// Several 'authorize' lines on one construct all have to hold, so they combine with 'and'.\nexport function combineAuthorize(first: AuthorizeSyntax | null, next: AuthorizeSyntax | null): AuthorizeSyntax | null {\n if (first === null) return next;\n if (next === null) return first;\n return {\n kind: 'AuthorizeSyntax',\n requirement: { kind: 'LogicalPolicyRequirementSyntax', left: first.requirement, operator: 'And', right: next.requirement, location: first.location },\n location: first.location,\n };\n}\n\nfunction tokenize(text: string): string[] {\n const tokens: string[] = [];\n for (const token of text.match(tokenPattern) ?? []) {\n if (tokens.length > 0 && isOperandEnd(tokens[tokens.length - 1]) && isOperandStart(token)) {\n tokens.push('and');\n }\n tokens.push(token);\n }\n return tokens;\n}\n\nconst isName = (token: string): boolean => token !== '(' && token !== ')' && token !== 'and' && token !== 'or';\nconst isOperandEnd = (token: string): boolean => token === ')' || isName(token);\nconst isOperandStart = (token: string): boolean => token === '(' || isName(token);\n\n// The port of the C# LogicalConditionParser: 'or' over 'and' over a group or a policy name.\nclass RequirementParser {\n #position = 0;\n\n constructor(private readonly context: ParserContext, private readonly tokens: readonly string[], private readonly location: SourceLocation) {}\n\n parse(): PolicyRequirementSyntax | null {\n const requirement = this.#or();\n if (requirement !== null && this.#position < this.tokens.length) {\n this.context.error(DiagnosticCodes.UnexpectedTokenInAuthorize, `Unexpected '${this.tokens[this.#position]}' in authorize`, this.location);\n }\n return requirement;\n }\n\n #or(): PolicyRequirementSyntax | null {\n return this.#chain('or', 'Or', () => this.#and());\n }\n\n #and(): PolicyRequirementSyntax | null {\n return this.#chain('and', 'And', () => this.#groupOrReference());\n }\n\n #chain(token: string, operator: LogicalOperator, operand: () => PolicyRequirementSyntax | null): PolicyRequirementSyntax | null {\n let left = operand();\n while (left !== null && this.tokens[this.#position] === token) {\n this.#position++;\n const right = operand();\n if (right === null) {\n return null;\n }\n left = { kind: 'LogicalPolicyRequirementSyntax', left, operator, right, location: this.location };\n }\n return left;\n }\n\n #groupOrReference(): PolicyRequirementSyntax | null {\n if (this.tokens[this.#position] !== '(') {\n return this.#reference();\n }\n this.#position++;\n const requirement = this.#or();\n if (this.tokens[this.#position] === ')') {\n this.#position++;\n } else {\n this.context.error(DiagnosticCodes.UnclosedAuthorizeGroup, 'Expected \\')\\' in authorize', this.location);\n }\n return requirement;\n }\n\n #reference(): PolicyRequirementSyntax | null {\n if (this.#position >= this.tokens.length) {\n this.context.error(DiagnosticCodes.AuthorizeWithoutPolicy, 'Expected a policy name', this.location);\n return null;\n }\n const token = this.tokens[this.#position++];\n if (!namePattern.test(token)) {\n this.context.error(DiagnosticCodes.InvalidPolicyReference, `Invalid policy reference '${token}' - policy names are PascalCase identifiers`, this.location);\n return null;\n }\n return { kind: 'PolicyReferenceSyntax', name: token, location: this.location };\n }\n}\n"],"mappings":"oNAUA,MAAMA,EAAsBC,EAAQ,4CAA4C,EAC1EC,EAAe,IAAI,OAAOD,EAAQ,uBAAuB,CAAC,CAAC,OAAQ,IAAI,EACvEE,EAAcF,EAAQ,aAAa,EAIzC,SAAgB,eAAe,EAAwB,EAA0C,CAC7F,IAAIG,EAAOC,EAAK,QAAQ,UAAU,CAAkB,EACpD,IAAK,IAAIC,EAAQC,EAAQ,UAAUF,EAAK,MAAM,EAAGC,IAAU,IAAA,IAAaN,EAAoB,KAAKM,EAAM,OAAO,EAAG,EAAQC,EAAQ,UAAUF,EAAK,MAAM,EAClJE,EAAQ,OAAO,gBAAgB,EAC/B,GAAQ,IAAID,EAAM,UAEtB,IAAME,EAAS,SAASJ,CAAI,EACtBK,EAAWC,EAAWL,CAAI,EAChC,GAAIG,EAAO,SAAW,EAElB,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X,CAEA,IAAsC,CAClC,OAAO,KAAKM,GAAO,KAAM,SAAY,KAAKC,GAAK,CAAC,CACpD,CAEA,IAAuC,CACnC,OAAO,KAAKD,GAAO,MAAO,UAAa,KAAKE,GAAkB,CAAC,CACnE,CAEA,GAAO,EAAe,EAA2B,EAA+E,CAC5H,IAAIC,EAAOC,EAAQ,EACnB,KAAOD,IAAS,MAAQ,KAAK,OAAO,KAAKJ,MAAeF,GAAO,CAC3D,KAAKE,KACL,IAAMM,EAAQD,EAAQ,EACtB,GAAIC,IAAU,KACV,OAAO,KAEX,EAAO,CAAE,KAAM,iCAAkC,OAAM,WAAU,QAAO,SAAU,KAAK,QAAS,CACpG,CACA,OAAOF,CACX,CAEA,IAAoD,CAChD,GAAI,KAAK,OAAO,KAAKJ,MAAe,IAChC,OAAO,KAAKO,GAAW,EAE3B,KAAKP,KACL,IAAML,EAAc,KAAKI,GAAI,EAM7B,OALI,KAAK,OAAO,KAAKC,MAAe,IAChC,KAAKA,KAEL,KAAK,QAAQ,MAAMN,EAAgB,uBAAwB,4BAA+B,KAAK,QAAQ,EAEpGC,CACX,CAEA,IAA6C,CACzC,GAAI,KAAKK,IAAa,KAAK,OAAO,OAE9B,OADA,KAAK,QAAQ,MAAMN,EAAgB,uBAAwB,yBAA0B,KAAK,QAAQ,EAC3F,KAEX,IAAMI,EAAQ,KAAK,OAAO,KAAKE,MAK/B,OAJKd,EAAY,KAAKY,CAAK,EAIpB,CAAE,KAAM,wBAAyB,KAAMA,EAAO,SAAU,KAAK,QAAS,GAHzE,KAAK,QAAQ,MAAMJ,EAAgB,uBAAwB,6BAA6BI,EAAM,6CAA8C,KAAK,QAAQ,EAClJ,KAGf,CACJ"}
1
+ {"version":3,"file":"AuthorizeParser.js","names":["continuationPattern","pattern","tokenPattern","namePattern","text","line","child","context","tokens","location","locationOf","DiagnosticCodes","requirement","first","next","token","content","match","previous","#or","#position","#chain","#and","#groupOrReference","left","operand","right","#reference"],"sources":["../../../../../../Compiler/Parsing/AuthorizeParser.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { DiagnosticCodes } from '../Diagnostics/DiagnosticCodes';\nimport { SourceLocation } from '../Diagnostics/SourceLocation';\nimport { AuthorizeSyntax, LogicalOperator, PolicyRequirementSyntax } from '../Syntax/Authorization';\nimport { pattern } from '../Text/patterns';\nimport { ParserContext } from './ParserContext';\nimport { locationOf, SourceLine } from './SourceLine';\n\nconst continuationPattern = pattern('^(?:(?:or|and)\\\\s+)?[A-Za-z_(][\\\\w\\\\s()]*$');\nconst tokenPattern = new RegExp(pattern('\\\\(|\\\\)|[A-Za-z_]\\\\w*').source, 'gu');\nconst namePattern = pattern('^[A-Z]\\\\w*$');\n\n// The port of the C# AuthorizeParser: the requirement may continue on the lines below the 'authorize', and\n// two operands written side by side are joined by an implicit 'and'.\nexport function parseAuthorize(context: ParserContext, line: SourceLine): AuthorizeSyntax | null {\n let text = line.content.substring('authorize'.length);\n for (let child = context.peekChild(line.indent); child !== undefined && continuationPattern.test(child.content); child = context.peekChild(line.indent)) {\n context.reader.takeSignificant();\n text += ` ${child.content}`;\n }\n const tokens = tokenize(text);\n const location = locationOf(line);\n if (tokens.length === 0) {\n context.error(DiagnosticCodes.AuthorizeWithoutPolicy, 'Expected at least one policy after \\'authorize\\'', location);\n return null;\n }\n if (hasImplicitConjunction(text)) context.information(DiagnosticCodes.ImplicitAuthorizationConjunction, 'Write \\'and\\' between adjacent policies in \\'authorize\\'.', location);\n const parser = new RequirementParser(context, tokens, location);\n const requirement = parser.parse();\n return requirement === null ? null : { kind: 'AuthorizeSyntax', requirement, location };\n}\n\n// Several 'authorize' lines on one construct all have to hold, so they combine with 'and'.\nexport function combineAuthorize(first: AuthorizeSyntax | null, next: AuthorizeSyntax | null): AuthorizeSyntax | null {\n if (first === null) return next;\n if (next === null) return first;\n return {\n kind: 'AuthorizeSyntax',\n requirement: { kind: 'LogicalPolicyRequirementSyntax', left: first.requirement, operator: 'And', right: next.requirement, location: first.location },\n location: first.location,\n };\n}\n\nfunction tokenize(text: string): string[] {\n const tokens: string[] = [];\n for (const token of text.match(tokenPattern) ?? []) {\n if (tokens.length > 0 && isOperandEnd(tokens[tokens.length - 1]) && isOperandStart(token)) {\n tokens.push('and');\n }\n tokens.push(token);\n }\n return tokens;\n}\n\nexport function isAuthorizeContinuation(content: string): boolean {\n return continuationPattern.test(content);\n}\n\n/** Finds each operand of one authorize line that sits directly after another operand, so an 'and' belongs before it. */\nexport function implicitConjunctionTokens(text: string, previous: string | undefined): { readonly tokens: readonly { readonly index: number; readonly length: number }[]; readonly previous: string | undefined } {\n const tokens: { index: number; length: number }[] = [];\n for (const match of text.matchAll(tokenPattern)) {\n if (previous !== undefined && isOperandEnd(previous) && isOperandStart(match[0])) tokens.push({ index: match.index, length: match[0].length });\n previous = match[0];\n }\n return { tokens, previous };\n}\n\nfunction hasImplicitConjunction(text: string): boolean {\n return implicitConjunctionTokens(text, undefined).tokens.length > 0;\n}\n\nconst isName = (token: string): boolean => token !== '(' && token !== ')' && token !== 'and' && token !== 'or';\nconst isOperandEnd = (token: string): boolean => token === ')' || isName(token);\nconst isOperandStart = (token: string): boolean => token === '(' || isName(token);\n\n// The port of the C# LogicalConditionParser: 'or' over 'and' over a group or a policy name.\nclass RequirementParser {\n #position = 0;\n\n constructor(private readonly context: ParserContext, private readonly tokens: readonly string[], private readonly location: SourceLocation) {}\n\n parse(): PolicyRequirementSyntax | null {\n const requirement = this.#or();\n if (requirement !== null && this.#position < this.tokens.length) {\n this.context.error(DiagnosticCodes.UnexpectedTokenInAuthorize, `Unexpected '${this.tokens[this.#position]}' in authorize`, this.location);\n }\n return requirement;\n }\n\n #or(): PolicyRequirementSyntax | null {\n return this.#chain('or', 'Or', () => this.#and());\n }\n\n #and(): PolicyRequirementSyntax | null {\n return this.#chain('and', 'And', () => this.#groupOrReference());\n }\n\n #chain(token: string, operator: LogicalOperator, operand: () => PolicyRequirementSyntax | null): PolicyRequirementSyntax | null {\n let left = operand();\n while (left !== null && this.tokens[this.#position] === token) {\n this.#position++;\n const right = operand();\n if (right === null) {\n return null;\n }\n left = { kind: 'LogicalPolicyRequirementSyntax', left, operator, right, location: this.location };\n }\n return left;\n }\n\n #groupOrReference(): PolicyRequirementSyntax | null {\n if (this.tokens[this.#position] !== '(') {\n return this.#reference();\n }\n this.#position++;\n const requirement = this.#or();\n if (this.tokens[this.#position] === ')') {\n this.#position++;\n } else {\n this.context.error(DiagnosticCodes.UnclosedAuthorizeGroup, 'Expected \\')\\' in authorize', this.location);\n }\n return requirement;\n }\n\n #reference(): PolicyRequirementSyntax | null {\n if (this.#position >= this.tokens.length) {\n this.context.error(DiagnosticCodes.AuthorizeWithoutPolicy, 'Expected a policy name', this.location);\n return null;\n }\n const token = this.tokens[this.#position++];\n if (!namePattern.test(token)) {\n this.context.error(DiagnosticCodes.InvalidPolicyReference, `Invalid policy reference '${token}' - policy names are PascalCase identifiers`, this.location);\n return null;\n }\n return { kind: 'PolicyReferenceSyntax', name: token, location: this.location };\n }\n}\n"],"mappings":"oNAUA,MAAMA,EAAsBC,EAAQ,4CAA4C,EAC1EC,EAAe,IAAI,OAAOD,EAAQ,uBAAuB,CAAC,CAAC,OAAQ,IAAI,EACvEE,EAAcF,EAAQ,aAAa,EAIzC,SAAgB,eAAe,EAAwB,EAA0C,CAC7F,IAAIG,EAAOC,EAAK,QAAQ,UAAU,CAAkB,EACpD,IAAK,IAAIC,EAAQC,EAAQ,UAAUF,EAAK,MAAM,EAAGC,IAAU,IAAA,IAAaN,EAAoB,KAAKM,EAAM,OAAO,EAAG,EAAQC,EAAQ,UAAUF,EAAK,MAAM,EAClJE,EAAQ,OAAO,gBAAgB,EAC/B,GAAQ,IAAID,EAAM,UAEtB,IAAME,EAAS,SAASJ,CAAI,EACtBK,EAAWC,EAAWL,CAAI,EAChC,GAAIG,EAAO,SAAW,EAElB,OADAD,EAAQ,MAAMI,EAAgB,uBAAwB,iDAAo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,KAAKQ,IAAa,KAAK,OAAO,OAE9B,OADA,KAAK,QAAQ,MAAMT,EAAgB,uBAAwB,yBAA0B,KAAK,QAAQ,EAC3F,KAEX,IAAMI,EAAQ,KAAK,OAAO,KAAKK,MAK/B,OAJKjB,EAAY,KAAKY,CAAK,EAIpB,CAAE,KAAM,wBAAyB,KAAMA,EAAO,SAAU,KAAK,QAAS,GAHzE,KAAK,QAAQ,MAAMJ,EAAgB,uBAAwB,6BAA6BI,EAAM,6CAA8C,KAAK,QAAQ,EAClJ,KAGf,CACJ"}
@@ -1,2 +1,2 @@
1
- import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";import{stringBodyPattern as t,unescapeString as n}from"../Text/StringLiteral.js";import{nativePattern as r,pattern as i}from"../Text/patterns.js";import{locationOf as a}from"./SourceLine.js";import{parseModeledMappingSource as o}from"./ExpressionParser.js";import{diagnosticText as s}from"../Diagnostics/DiagnosticArgument.js";import{firstWord as c,unescapeIdentifier as l}from"./LineText.js";import"../Syntax/CaptureEventsSource.js";import{parseTag as u}from"./DeclarationParsers.js";import{parseProjectionExpression as d}from"./ProjectionExpressionParser.js";const grammar=e=>({legacy:i(e),native:r(e)}),f=grammar(`^capture\\s+([A-Za-z_]\\w*)$`),p=/^[A-Za-z_][\w.]*$/,m=/\s+is\s+event\s+source$/,h=grammar(`^append\\s+([A-Z]\\w*)$`),g=grammar(`^children\\s+([a-z_]\\w*)\\s+identified\\s+by\\s+([\\w.]+)$`),_=grammar(`^nested\\s+([\\w.]+)$`),select=(e,t)=>e.sourceOptions.numericMode===`exact`?t.native:t.legacy,v=r(`^(@?[\\w.]+)\\s*=(?!=|>)\\s*(.+)$`),y=r(`^([a-z_]\\w*)\\s*=\\s*(.+)$`),b=r(`^"(${t})"\\s*=>\\s*(\\w+)$`),x=r(`^split\\s+(\\S+)\\s+by\\s+"(${t})"$`),S=new RegExp(r(`"${t}"|[\\w.]+`).source,`gu`),C=r(`^[\\w.]+$`);function parseCapture(t,n){let r=t;t=t.valueContext;let i=select(t,f).exec(n.content)?.[1]??``;i===``&&t.sourceOptions.numericMode===`exact`&&t.error(e.InvalidCaptureDeclaration,`Invalid capture declaration '${n.content}' - expected 'capture <Name>'`,a(n));let o=null,s=null,l=!1,u=[],d=[],p=[],m=[];for(let i=t.peekChild(n.indent);i!==void 0;i=t.peekChild(n.indent))switch(t.reader.takeSignificant(),c(i.content)){case`source`:o=parseSource(t,i,r);break;case`key`:[s,l]=parseKey(i.content.substring(3).trim(),l);break;case`map`:u.push(...parseMap(t,i));break;case`append`:pushAppend(t,i,d);break;case`children`:{let n=select(t,g).exec(i.content);if(n===null){t.error(e.InvalidChildrenDeclaration,`Invalid children declaration '${i.content}' - expected 'children <collection> identified by <key>'`,a(i)),t.skipOpaqueBlock(i.indent);break}let r=mapAndAppends(t,i);n!==null&&p.push({kind:`CaptureChildrenSyntax`,property:n[1],identifiedBy:n[2],...r,location:a(i)});break}case`nested`:{let n=select(t,_).exec(i.content);if(n===null){t.error(e.InvalidNestedDeclaration,`Invalid nested declaration '${i.content}' - expected 'nested <Property>'`,a(i)),t.skipOpaqueBlock(i.indent);break}let r=mapAndAppends(t,i);n!==null&&m.push({kind:`CaptureNestedSyntax`,property:n[1],...r,location:a(i)});break}default:t.error(e.UnknownCaptureDirective,`Unexpected '${i.content}' in capture body`,a(i)),t.skipOpaqueBlock(i.indent)}return{kind:`CaptureSyntax`,sourceOptions:t.sourceOptions,name:i,source:o,key:s,...eventSourceKeyMarker(l),map:u,appends:d,children:p,nested:m,location:a(n)}}function parseKey(e,t){let n=m.exec(e);return n===null?[e,t]:[e.substring(0,n.index),!0]}function eventSourceKeyMarker(e){return e?{keyIsEventSource:e}:{}}function parseSource(e,t,n){let r=[];for(let n=e.peekChild(t.indent);n!==void 0;n=e.peekChild(t.indent)){e.reader.takeSignificant();let t=c(n.content);r.push({kind:`CaptureSourceSettingSyntax`,name:t,value:n.content.substring(t.length).trim(),location:a(n)})}let i=t.content.substring(6).trim();return i===`events`&&validateEventsSource(n,t,r),{kind:`CaptureSourceSyntax`,syntaxKind:i,settings:r,location:a(t)}}function validateEventsSource(t,n,r){r.length===0&&t.error(e.InvalidCaptureEventsSource,`'source events' needs at least one 'from <Event>' line naming a public event to consume`,a(n));let i=/* @__PURE__ */ new Set;for(let n of r)n.name===`from`?p.test(n.value)?i.has(n.value)?t.error(e.InvalidCaptureEventsSource,`Event '${n.value}' is already consumed by this 'source events'`,n.location):i.add(n.value):t.error(e.InvalidCaptureEventsSource,`Invalid event '${n.value}' - expected 'from <Event>', optionally qualified with dots`,n.location):t.error(e.InvalidCaptureEventsSource,`'source events' accepts only 'from <Event>' lines, got '${n.name}'`,n.location)}function parseMap(t,r){let i=[];for(let o=t.peekChild(r.indent);o!==void 0;o=t.peekChild(r.indent)){t.reader.takeSignificant();let r=a(o);if(c(o.content)===`split`){let s=x.exec(o.content);if(s===null){t.error(e.InvalidSplitDeclaration,`Invalid split operation '${o.content}' - expected 'split <property> by "<separator>"'`,r),t.skipOpaqueBlock(o.indent);continue}let c=[];for(let n=t.peekChild(o.indent);n!==void 0;n=t.peekChild(o.indent))t.reader.takeSignificant(),C.test(n.content)?c.push(n.content):t.error(e.InvalidSplitTarget,`Invalid split target '${n.content}' - expected a property path`,a(n));s!==null&&i.push({kind:`CaptureSplitSyntax`,source:d(s[1],r,t),separator:n(s[2]),targets:c,location:r});continue}let s=y.exec(o.content);if(s===null){t.error(e.InvalidMapEntry,`Invalid map entry '${o.content}' - expected '<property> = <source> [translate]'`,r),t.skipOpaqueBlock(o.indent);continue}let l=s[2].trim(),u=l.startsWith("`")?l.indexOf("`",1):-1,f=l.startsWith("`")?u>=0&&l.substring(u+1).trim()===`translate`:l.endsWith(` translate`),p=l.startsWith("`")&&u>=0&&(t.sourceOptions.numericMode!==`exact`||f||l.substring(u+1).trim()===``)?l.substring(0,u+1):f?l.substring(0,l.length-10).trimEnd():l,m=[];if(f)for(let r=t.peekChild(o.indent);r!==void 0;r=t.peekChild(o.indent)){t.reader.takeSignificant();let i=b.exec(r.content);i===null?t.error(e.InvalidTranslation,`Invalid translation '${r.content}' - expected '"<source>" => <target>'`,a(r)):m.push({kind:`CaptureTranslationSyntax`,from:n(i[1]),to:i[2],location:a(r)})}i.push({kind:`CaptureMapEntrySyntax`,property:s[1],source:d(p,r,t),translations:m,location:r})}return i}function mapAndAppends(t,n){let r=[],i=[];for(let o=t.peekChild(n.indent);o!==void 0;o=t.peekChild(n.indent))t.reader.takeSignificant(),c(o.content)===`map`?r=parseMap(t,o):c(o.content)===`append`?pushAppend(t,o,i):(t.error(e.UnknownCaptureBlockDirective,`Unexpected '${o.content}' in ${c(n.content)} block - expected 'map' or 'append <EventType>'`,a(o)),t.skipOpaqueBlock(o.indent));return{map:r,appends:i}}function pushAppend(t,n,r){let i=select(t,h).exec(n.content);if(i===null){t.error(e.InvalidAppendDeclaration,`Invalid append declaration '${n.content}' - expected 'append <EventType>'`,a(n)),t.skipOpaqueBlock(n.indent);return}let d=[],f=[],p=null,mapping=(n,r=!1)=>{let i=a(n);if(c(n.content)===`tag`){let e=u(t.valueContext,n,!1);e!==void 0&&f.push(e);return}let p=v.exec(n.content);p===null?t.error(r?e.InvalidPropertyMapping:e.UnknownAppendDirective,`Unexpected '${n.content}' in append body`,i,r?s(`text`,n.content):{}):d.push({kind:`PropertyMappingSyntax`,property:l(p[1]),source:o(p[2],i,t.valueContext),location:i})};for(let e=t.peekChild(n.indent);e!==void 0;e=t.peekChild(n.indent))if(t.reader.takeSignificant(),c(e.content)===`when`){p=parseWhen(t,e);for(let n=t.peekChild(e.indent);n!==void 0;n=t.peekChild(e.indent))t.reader.takeSignificant(),mapping(n,!0)}else mapping(e);r.push({kind:`CaptureAppendSyntax`,event:i[1],when:p,mappings:d,tags:f,location:a(n)})}function parseWhen(t,r){let i=r.content.substring(4).trim(),o=a(r),value=(e,t=[],n=null,r=null,i=null)=>({kind:`CaptureWhenSyntax`,syntaxKind:e,properties:t,fromValue:n,toValue:r,expression:i,location:o});if(i===`added`)return value(`Added`);if(i===`removed`)return value(`Removed`);if(i.startsWith("`"))return(!i.endsWith("`")||i.length<2)&&t.error(e.UnterminatedTemplateExpression,`Unterminated template expression in 'when' - expected a closing backtick`,o),value(`Expression`,[],null,null,i);if(i.length===0)return t.error(e.WhenWithoutTrigger,`Expected a trigger after 'when'`,o),null;let s=[...i.match(t.sourceOptions.numericMode===`exact`?/* @__PURE__ */ RegExp(`"(?:[^"\\\\]|\\\\.)*"|[^\\s]+`,`gu`):S)??[]],unquote=e=>e.startsWith(`"`)&&e.endsWith(`"`)?n(e.substring(1,e.length-1)):e;if(s.length===0)return t.error(e.InvalidWhenClause,`Invalid 'when' clause '${r.content}'`,o),null;if(s.length===1)return value(`PropertyChanged`,[unquote(s[0])]);if(s[1]===`from`)return s.length===5&&s[3]===`to`?value(`ValueTransition`,[unquote(s[0])],unquote(s[2]),unquote(s[4])):(t.error(e.InvalidWhenTransitionClause,`Invalid 'when ... from ... to ...' clause '${r.content}'`,o),null);if(s[1]!==`or`&&s[1]!==`and`)return t.error(e.InvalidWhenClause,`Invalid 'when' clause '${r.content}'`,o),null;if(s.length%2==0)return t.error(e.WhenCombinatorWithoutProperty,`Expected a property after '${s[1]}'`,o),null;let c=[unquote(s[0])];for(let n=1;n<s.length-1;n+=2){if(s[n]!==s[1])return t.error(e.MixedWhenCombinators,`Cannot mix 'and' and 'or' in a single 'when' clause '${r.content}'`,o),null;c.push(unquote(s[n+1]))}return value(s[1]===`or`?`LogicalOr`:`LogicalAnd`,c)}export{parseCapture};
1
+ import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";import{stringBodyPattern as t,unescapeString as n}from"../Text/StringLiteral.js";import{nativePattern as r,pattern as i}from"../Text/patterns.js";import{locationOf as a}from"./SourceLine.js";import{parseModeledMappingSource as o}from"./ExpressionParser.js";import{diagnosticText as s}from"../Diagnostics/DiagnosticArgument.js";import{firstWord as c,unescapeIdentifier as l}from"./LineText.js";import{parseTag as u}from"./DeclarationParsers.js";import"../Syntax/CaptureEventsSource.js";import{parseProjectionExpression as d}from"./ProjectionExpressionParser.js";const grammar=e=>({legacy:i(e),native:r(e)}),f=grammar(`^capture\\s+([A-Za-z_]\\w*)$`),p=/^[A-Za-z_][\w.]*$/,m=/\s+is\s+event\s+source$/,h=grammar(`^append\\s+([A-Z]\\w*)$`),g=grammar(`^children\\s+([a-z_]\\w*)\\s+identified\\s+by\\s+([\\w.]+)$`),_=grammar(`^nested\\s+([\\w.]+)$`),select=(e,t)=>e.sourceOptions.numericMode===`exact`?t.native:t.legacy,v=r(`^(@?[\\w.]+)\\s*=(?!=|>)\\s*(.+)$`),y=r(`^([a-z_]\\w*)\\s*=\\s*(.+)$`),b=r(`^"(${t})"\\s*=>\\s*(\\w+)$`),x=r(`^split\\s+(\\S+)\\s+by\\s+"(${t})"$`),S=new RegExp(r(`"${t}"|[\\w.]+`).source,`gu`),C=r(`^[\\w.]+$`);function parseCapture(t,n){let r=t;t=t.valueContext;let i=select(t,f).exec(n.content)?.[1]??``;i===``&&t.sourceOptions.numericMode===`exact`&&t.error(e.InvalidCaptureDeclaration,`Invalid capture declaration '${n.content}' - expected 'capture <Name>'`,a(n));let o=null,s=null,l=!1,u=[],d=[],p=[],m=[];for(let i=t.peekChild(n.indent);i!==void 0;i=t.peekChild(n.indent))switch(t.reader.takeSignificant(),c(i.content)){case`source`:o=parseSource(t,i,r);break;case`key`:[s,l]=parseKey(i.content.substring(3).trim(),l);break;case`map`:u.push(...parseMap(t,i));break;case`append`:pushAppend(t,i,d);break;case`children`:{let n=select(t,g).exec(i.content);if(n===null){t.error(e.InvalidChildrenDeclaration,`Invalid children declaration '${i.content}' - expected 'children <collection> identified by <key>'`,a(i)),t.skipOpaqueBlock(i.indent);break}let r=mapAndAppends(t,i);n!==null&&p.push({kind:`CaptureChildrenSyntax`,property:n[1],identifiedBy:n[2],...r,location:a(i)});break}case`nested`:{let n=select(t,_).exec(i.content);if(n===null){t.error(e.InvalidNestedDeclaration,`Invalid nested declaration '${i.content}' - expected 'nested <Property>'`,a(i)),t.skipOpaqueBlock(i.indent);break}let r=mapAndAppends(t,i);n!==null&&m.push({kind:`CaptureNestedSyntax`,property:n[1],...r,location:a(i)});break}default:t.error(e.UnknownCaptureDirective,`Unexpected '${i.content}' in capture body`,a(i)),t.skipOpaqueBlock(i.indent)}return{kind:`CaptureSyntax`,sourceOptions:t.sourceOptions,name:i,source:o,key:s,...eventSourceKeyMarker(l),map:u,appends:d,children:p,nested:m,location:a(n)}}function parseKey(e,t){let n=m.exec(e);return n===null?[e,t]:[e.substring(0,n.index),!0]}function eventSourceKeyMarker(e){return e?{keyIsEventSource:e}:{}}function parseSource(e,t,n){let r=[];for(let n=e.peekChild(t.indent);n!==void 0;n=e.peekChild(t.indent)){e.reader.takeSignificant();let t=c(n.content);r.push({kind:`CaptureSourceSettingSyntax`,name:t,value:n.content.substring(t.length).trim(),location:a(n)})}let i=t.content.substring(6).trim();return i===`events`&&validateEventsSource(n,t,r),{kind:`CaptureSourceSyntax`,syntaxKind:i,settings:r,location:a(t)}}function validateEventsSource(t,n,r){r.length===0&&t.error(e.InvalidCaptureEventsSource,`'source events' needs at least one 'from <Event>' line naming a public event to consume`,a(n));let i=/* @__PURE__ */ new Set;for(let n of r)n.name===`from`?p.test(n.value)?i.has(n.value)?t.error(e.InvalidCaptureEventsSource,`Event '${n.value}' is already consumed by this 'source events'`,n.location):i.add(n.value):t.error(e.InvalidCaptureEventsSource,`Invalid event '${n.value}' - expected 'from <Event>', optionally qualified with dots`,n.location):t.error(e.InvalidCaptureEventsSource,`'source events' accepts only 'from <Event>' lines, got '${n.name}'`,n.location)}function parseMap(t,r){let i=[];for(let o=t.peekChild(r.indent);o!==void 0;o=t.peekChild(r.indent)){t.reader.takeSignificant();let r=a(o);if(c(o.content)===`split`){let s=x.exec(o.content);if(s===null){t.error(e.InvalidSplitDeclaration,`Invalid split operation '${o.content}' - expected 'split <property> by "<separator>"'`,r),t.skipOpaqueBlock(o.indent);continue}let c=[];for(let n=t.peekChild(o.indent);n!==void 0;n=t.peekChild(o.indent))t.reader.takeSignificant(),C.test(n.content)?c.push(n.content):t.error(e.InvalidSplitTarget,`Invalid split target '${n.content}' - expected a property path`,a(n));s!==null&&i.push({kind:`CaptureSplitSyntax`,source:d(s[1],r,t),separator:n(s[2]),targets:c,location:r});continue}let s=y.exec(o.content);if(s===null){t.error(e.InvalidMapEntry,`Invalid map entry '${o.content}' - expected '<property> = <source> [translate]'`,r),t.skipOpaqueBlock(o.indent);continue}let l=s[2].trim(),u=l.startsWith("`")?l.indexOf("`",1):-1,f=l.startsWith("`")?u>=0&&l.substring(u+1).trim()===`translate`:l.endsWith(` translate`),p=l.startsWith("`")&&u>=0&&(t.sourceOptions.numericMode!==`exact`||f||l.substring(u+1).trim()===``)?l.substring(0,u+1):f?l.substring(0,l.length-10).trimEnd():l,m=[];if(f)for(let r=t.peekChild(o.indent);r!==void 0;r=t.peekChild(o.indent)){t.reader.takeSignificant();let i=b.exec(r.content);i===null?t.error(e.InvalidTranslation,`Invalid translation '${r.content}' - expected '"<source>" => <target>'`,a(r)):m.push({kind:`CaptureTranslationSyntax`,from:n(i[1]),to:i[2],location:a(r)})}i.push({kind:`CaptureMapEntrySyntax`,property:s[1],source:d(p,r,t),translations:m,location:r})}return i}function mapAndAppends(t,n){let r=[],i=[];for(let o=t.peekChild(n.indent);o!==void 0;o=t.peekChild(n.indent))t.reader.takeSignificant(),c(o.content)===`map`?r=parseMap(t,o):c(o.content)===`append`?pushAppend(t,o,i):(t.error(e.UnknownCaptureBlockDirective,`Unexpected '${o.content}' in ${c(n.content)} block - expected 'map' or 'append <EventType>'`,a(o)),t.skipOpaqueBlock(o.indent));return{map:r,appends:i}}function pushAppend(t,n,r){let i=select(t,h).exec(n.content);if(i===null){t.error(e.InvalidAppendDeclaration,`Invalid append declaration '${n.content}' - expected 'append <EventType>'`,a(n)),t.skipOpaqueBlock(n.indent);return}let d=[],f=[],p=null,mapping=(n,r=!1)=>{let i=a(n);if(c(n.content)===`tag`){let e=u(t.valueContext,n,!1);e!==void 0&&f.push(e);return}let p=v.exec(n.content);p===null?t.error(r?e.InvalidPropertyMapping:e.UnknownAppendDirective,`Unexpected '${n.content}' in append body`,i,r?s(`text`,n.content):{}):d.push({kind:`PropertyMappingSyntax`,property:l(p[1]),source:o(p[2],i,t.valueContext),location:i})};for(let e=t.peekChild(n.indent);e!==void 0;e=t.peekChild(n.indent))if(t.reader.takeSignificant(),c(e.content)===`when`){p=parseWhen(t,e);for(let n=t.peekChild(e.indent);n!==void 0;n=t.peekChild(e.indent))t.reader.takeSignificant(),mapping(n,!0)}else mapping(e);r.push({kind:`CaptureAppendSyntax`,event:i[1],when:p,mappings:d,tags:f,location:a(n)})}function parseWhen(t,r){let i=r.content.substring(4).trim(),o=a(r),value=(e,t=[],n=null,r=null,i=null)=>({kind:`CaptureWhenSyntax`,syntaxKind:e,properties:t,fromValue:n,toValue:r,expression:i,location:o});if(i===`added`)return value(`Added`);if(i===`removed`)return value(`Removed`);if(i.startsWith("`"))return(!i.endsWith("`")||i.length<2)&&t.error(e.UnterminatedTemplateExpression,`Unterminated template expression in 'when' - expected a closing backtick`,o),value(`Expression`,[],null,null,i);if(i.length===0)return t.error(e.WhenWithoutTrigger,`Expected a trigger after 'when'`,o),null;let s=[...i.match(t.sourceOptions.numericMode===`exact`?/* @__PURE__ */ RegExp(`"(?:[^"\\\\]|\\\\.)*"|[^\\s]+`,`gu`):S)??[]],unquote=e=>e.startsWith(`"`)&&e.endsWith(`"`)?n(e.substring(1,e.length-1)):e;if(s.length===0)return t.error(e.InvalidWhenClause,`Invalid 'when' clause '${r.content}'`,o),null;if(s.length===1)return value(`PropertyChanged`,[unquote(s[0])]);if(s[1]===`from`)return s.length===5&&s[3]===`to`?value(`ValueTransition`,[unquote(s[0])],unquote(s[2]),unquote(s[4])):(t.error(e.InvalidWhenTransitionClause,`Invalid 'when ... from ... to ...' clause '${r.content}'`,o),null);if(s[1]!==`or`&&s[1]!==`and`)return t.error(e.InvalidWhenClause,`Invalid 'when' clause '${r.content}'`,o),null;if(s.length%2==0)return t.error(e.WhenCombinatorWithoutProperty,`Expected a property after '${s[1]}'`,o),null;let c=[unquote(s[0])];for(let n=1;n<s.length-1;n+=2){if(s[n]!==s[1])return t.error(e.MixedWhenCombinators,`Cannot mix 'and' and 'or' in a single 'when' clause '${r.content}'`,o),null;c.push(unquote(s[n+1]))}return value(s[1]===`or`?`LogicalOr`:`LogicalAnd`,c)}export{parseCapture};
2
2
  //# sourceMappingURL=CaptureParser.js.map
@@ -1,2 +1,2 @@
1
- import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";function isPendingHandler(e){return e.implementation!=null&&e.file===null&&e.code===null}function validateHandlerOccurrences(t,n){let r=t.some(e=>e.handler!==null&&isPendingHandler(e.handler)),i=r?e.PendingIntentWithOtherHandler:e.DuplicateDeclaration,a=r?`A pending handler intent cannot coexist with another handler on the same command.`:`A command cannot declare more than one handler.`;for(let e of t.slice(1))n.error(i,a,e.location)}function validateApplicationHandlers(e,t){let validateFeature=e=>{for(let n of e.slices)validateCommandHandlers(n.commands,t);e.features.forEach(validateFeature)};for(let t of e.modules)t.features.forEach(validateFeature)}function validateCommandHandlers(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(t.name,[...n.get(t.name)??[],t]);for(let e of n.values())validateHandlerOccurrences(e.flatMap(e=>e.handler==null?[]:[{handler:e.handler,location:e.handler.location}]),t)}export{isPendingHandler,validateApplicationHandlers,validateCommandHandlers,validateHandlerOccurrences};
1
+ import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";function isPendingHandler(e){return e.implementation!=null&&e.file===null&&e.code===null}function validateHandlerOccurrences(t,n){let r=t.some(e=>e.handler!==null&&isPendingHandler(e.handler)),i=r?e.PendingIntentWithOtherHandler:e.DuplicateDeclaration,a=r?`A pending handler intent cannot coexist with another handler on the same command.`:`A command cannot declare more than one handler.`;for(let e of t.slice(1))n.error(i,a,e.location)}function validateApplicationHandlers(e,t){let validateFeature=e=>{for(let n of e.slices)validateCommandHandlers(n.commands,t);e.features.forEach(validateFeature)};for(let t of e.modules)t.features.forEach(validateFeature)}function validateHandlerContracts(e,t,n,r){validateHandlerOccurrences(e,r),validatePossibleEvents(t,n,r)}function validatePossibleEvents(t,n,r){n&&t?.possibleEvents!=null&&r.error(e.InvalidPossibleEventsDeclaration,`A command cannot combine 'produces' with a handler 'may produce' set.`,t.possibleEvents.location)}function validateCommandHandlers(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(t.name,[...n.get(t.name)??[],t]);for(let e of n.values()){validateHandlerOccurrences(e.flatMap(e=>e.handler==null?[]:[{handler:e.handler,location:e.handler.location}]),t);let n=e.some(e=>e.produces.length>0);e.forEach(e=>validatePossibleEvents(e.handler,n,t))}}export{isPendingHandler,validateApplicationHandlers,validateCommandHandlers,validateHandlerContracts,validateHandlerOccurrences,validatePossibleEvents};
2
2
  //# sourceMappingURL=CommandHandlerValidator.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"CommandHandlerValidator.js","names":["handler","hasPending","occurrences","entry","code","DiagnosticCodes","message","context","slice","feature","module","application","groups","command","commands","group"],"sources":["../../../../../../Compiler/Parsing/CommandHandlerValidator.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { DiagnosticCodes } from '../Diagnostics/DiagnosticCodes';\nimport { SourceLocation } from '../Diagnostics/SourceLocation';\nimport { CommandSyntax } from '../Syntax/Commands';\nimport { HandlerSyntax } from '../Syntax/Implementations';\nimport { ApplicationSyntax, FeatureSyntax } from '../Syntax/Structure';\nimport { ParserContext } from './ParserContext';\n\nexport function isPendingHandler(handler: HandlerSyntax): boolean {\n return handler.implementation != null && handler.file === null && handler.code === null;\n}\n\nexport function validateHandlerOccurrences(occurrences: readonly { handler: HandlerSyntax | null; location: SourceLocation }[], context: ParserContext): void {\n const hasPending = occurrences.some(entry => entry.handler !== null && isPendingHandler(entry.handler));\n const code = hasPending ? DiagnosticCodes.PendingIntentWithOtherHandler : DiagnosticCodes.DuplicateDeclaration;\n const message = hasPending\n ? 'A pending handler intent cannot coexist with another handler on the same command.'\n : 'A command cannot declare more than one handler.';\n for (const entry of occurrences.slice(1)) {\n context.error(code, message, entry.location);\n }\n}\n\nexport function validateApplicationHandlers(application: ApplicationSyntax, context: ParserContext): void {\n const validateFeature = (feature: FeatureSyntax): void => {\n for (const slice of feature.slices) validateCommandHandlers(slice.commands, context);\n feature.features.forEach(validateFeature);\n };\n for (const module of application.modules) module.features.forEach(validateFeature);\n}\n\nexport function validateCommandHandlers(commands: readonly CommandSyntax[], context: ParserContext): void {\n const groups = new Map<string, CommandSyntax[]>();\n for (const command of commands) groups.set(command.name, [...(groups.get(command.name) ?? []), command]);\n for (const group of groups.values()) {\n validateHandlerOccurrences(group.flatMap(command => command.handler == null ? [] : [{ handler: command.handler, location: command.handler.location }]), context);\n }\n}\n"],"mappings":"yHAUA,SAAgB,iBAAiB,EAAiC,CAC9D,OAAOA,EAAQ,gBAAkB,MAAQA,EAAQ,OAAS,MAAQA,EAAQ,OAAS,IACvF,CAEA,SAAgB,2BAA2B,EAAqF,EAA8B,CAC1J,IAAMC,EAAaC,EAAY,KAAK,GAASC,EAAM,UAAY,MAAQ,iBAAiBA,EAAM,OAAO,CAAC,EAChGC,EAAOH,EAAaI,EAAgB,8BAAgCA,EAAgB,qBACpFC,EAAUL,EACV,oFACA,kDACN,IAAK,IAAME,KAASD,EAAY,MAAM,CAAC,EACnCK,EAAQ,MAAMH,EAAME,EAASH,EAAM,QAAQ,CAEnD,CAEA,SAAgB,4BAA4B,EAAgC,EAA8B,CACtG,IAAM,gBAAmB,GAAiC,CACtD,IAAK,IAAMK,KAASC,EAAQ,OAAQ,wBAAwBD,EAAM,SAAUD,CAAO,EACnFE,EAAQ,SAAS,QAAQ,eAAe,CAC5C,EACA,IAAK,IAAMC,KAAUC,EAAY,QAASD,EAAO,SAAS,QAAQ,eAAe,CACrF,CAEA,SAAgB,wBAAwB,EAAoC,EAA8B,CACtG,IAAME,kBAAS,IAAI,IACnB,IAAK,IAAMC,KAAWC,EAAUF,EAAO,IAAIC,EAAQ,KAAM,CAAC,GAAID,EAAO,IAAIC,EAAQ,IAAI,GAAK,CAAC,EAAIA,CAAO,CAAC,EACvG,IAAK,IAAME,KAASH,EAAO,OAAO,EAC9B,2BAA2BG,EAAM,QAAQ,GAAWF,EAAQ,SAAW,KAAO,CAAC,EAAI,CAAC,CAAE,QAASA,EAAQ,QAAS,SAAUA,EAAQ,QAAQ,QAAS,CAAC,CAAC,EAAGN,CAAO,CAEvK"}
1
+ {"version":3,"file":"CommandHandlerValidator.js","names":["handler","hasPending","occurrences","entry","code","DiagnosticCodes","message","context","slice","feature","module","application","handlers","hasProduces","groups","command","commands","group"],"sources":["../../../../../../Compiler/Parsing/CommandHandlerValidator.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { DiagnosticCodes } from '../Diagnostics/DiagnosticCodes';\nimport { SourceLocation } from '../Diagnostics/SourceLocation';\nimport { CommandSyntax } from '../Syntax/Commands';\nimport { HandlerSyntax } from '../Syntax/Implementations';\nimport { ApplicationSyntax, FeatureSyntax } from '../Syntax/Structure';\nimport { ParserContext } from './ParserContext';\n\nexport function isPendingHandler(handler: HandlerSyntax): boolean {\n return handler.implementation != null && handler.file === null && handler.code === null;\n}\n\nexport function validateHandlerOccurrences(occurrences: readonly { handler: HandlerSyntax | null; location: SourceLocation }[], context: ParserContext): void {\n const hasPending = occurrences.some(entry => entry.handler !== null && isPendingHandler(entry.handler));\n const code = hasPending ? DiagnosticCodes.PendingIntentWithOtherHandler : DiagnosticCodes.DuplicateDeclaration;\n const message = hasPending\n ? 'A pending handler intent cannot coexist with another handler on the same command.'\n : 'A command cannot declare more than one handler.';\n for (const entry of occurrences.slice(1)) {\n context.error(code, message, entry.location);\n }\n}\n\nexport function validateApplicationHandlers(application: ApplicationSyntax, context: ParserContext): void {\n const validateFeature = (feature: FeatureSyntax): void => {\n for (const slice of feature.slices) validateCommandHandlers(slice.commands, context);\n feature.features.forEach(validateFeature);\n };\n for (const module of application.modules) module.features.forEach(validateFeature);\n}\n\nexport function validateHandlerContracts(handlers: readonly { handler: HandlerSyntax | null; location: SourceLocation }[], handler: HandlerSyntax | null, hasProduces: boolean, context: ParserContext): void {\n validateHandlerOccurrences(handlers, context);\n validatePossibleEvents(handler, hasProduces, context);\n}\n\nexport function validatePossibleEvents(handler: HandlerSyntax | null | undefined, hasProduces: boolean, context: ParserContext): void {\n if (hasProduces && handler?.possibleEvents != null) {\n context.error(DiagnosticCodes.InvalidPossibleEventsDeclaration, \"A command cannot combine 'produces' with a handler 'may produce' set.\", handler.possibleEvents.location);\n }\n}\n\nexport function validateCommandHandlers(commands: readonly CommandSyntax[], context: ParserContext): void {\n const groups = new Map<string, CommandSyntax[]>();\n for (const command of commands) groups.set(command.name, [...(groups.get(command.name) ?? []), command]);\n for (const group of groups.values()) {\n validateHandlerOccurrences(group.flatMap(command => command.handler == null ? [] : [{ handler: command.handler, location: command.handler.location }]), context);\n const hasProduces = group.some(command => command.produces.length > 0);\n group.forEach(command => validatePossibleEvents(command.handler, hasProduces, context));\n }\n}\n"],"mappings":"yHAUA,SAAgB,iBAAiB,EAAiC,CAC9D,OAAOA,EAAQ,gBAAkB,MAAQA,EAAQ,OAAS,MAAQA,EAAQ,OAAS,IACvF,CAEA,SAAgB,2BAA2B,EAAqF,EAA8B,CAC1J,IAAMC,EAAaC,EAAY,KAAK,GAASC,EAAM,UAAY,MAAQ,iBAAiBA,EAAM,OAAO,CAAC,EAChGC,EAAOH,EAAaI,EAAgB,8BAAgCA,EAAgB,qBACpFC,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as e}from"../Diagnostics/DiagnosticCodes.js";import{stringBodyPattern as t,unescapeString as n}from"../Text/StringLiteral.js";import{pattern as r}from"../Text/patterns.js";import{locationOf as i}from"./SourceLine.js";import{dependencySources as a}from"../Syntax/DependencySources.js";import{parseMappingSource as o}from"./ExpressionParser.js";import{validateHandlerOccurrences as s}from"./CommandHandlerValidator.js";import{firstWord as c}from"./LineText.js";import{reportInvalidModifierOrder as l,reportLegacyOptionalSuffix as u,tryParseProperty as d}from"./PropertyLineParser.js";import{combineAuthorize as f,parseAuthorize as p}from"./AuthorizeParser.js";import{parseDescription as m}from"./DescriptionParser.js";import{parseDocumentation as h}from"./DocumentationParser.js";import{parseCondition as g}from"./ConditionParser.js";import{ParserContext as _}from"./ParserContext.js";import{isReactionIdentityLine as v,misplacedReactionIdentity as y}from"./ReactionIdentityParser.js";import{sourceStreamPattern as b}from"../Text/SourceStreamNames.js";import{parseCommandStream as x}from"./EventSourceParser.js";import{isFileDirectiveAmongProperties as S}from"./FileReferences.js";import{isCode as C,isFile as w,parseCode as T,parseFile as E,parseHandler as D,parseImplementationWrapper as O}from"./ImplementationParser.js";import{parseCommandResponse as k,scalarResponsePattern as A}from"./CommandResponseParser.js";import{matchSubject as j,validateMatchOperand as M}from"./MatchOperandValidation.js";import{commandReadSources as N}from"./CommandReadSources.js";import{captureConcurrency as P}from"./DependencySourceParser.js";import{parseReads as F}from"./ReadsParser.js";import{parseProduces as I}from"./ProducesParser.js";const L=r(`^command\\s+([A-Za-z_]\\w*)$`),ee=b(`^stream\\s+[A-Za-z_]\\w*\\.[A-Za-z_]\\w*$`),R=r(`^calendar\\s+(?:"|from\\s+\\$context\\.)`),z=r(`^calendar\\s+(?:"(${t})"|from\\s+\\$context\\.([A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)*))$`),B=r(`\\bseverity\\s+(\\S+)$`),V=r(`\\bmessage\\s+(?:"(${t})"|(\\$strings\\.\\S*))$`),H=r(`^([\\w.]+)\\s+(.+)$`),U=r(`^(?:(not empty|matches|not contains|contains|starts with|ends with|max|min|rule)(?:\\s+|$)|(length ==|decimals <=|all >=|all >|>=|<=|==|!=|>|<)\\s*)(.*)$`),W=b(`^[A-Za-z_]\\w*$`),G=r(`^reads\\s+[A-Z]\\w*\\s+optional(?:\\s|$)`),K={max:`Max`,min:`Min`,">":`GreaterThan`,">=":`GreaterThanOrEqual`,"<":`LessThan`,"<=":`LessThanOrEqual`,"==":`Equal`,"!=":`NotEqual`,"length ==":`Length`,"decimals <=":`DecimalPlaces`,matches:`Matches`,contains:`Contains`,"not contains":`NotContains`,"starts with":`StartsWith`,"ends with":`EndsWith`,"all >":`AllGreaterThan`,"all >=":`AllGreaterThanOrEqual`},q={information:`Information`,warning:`Warning`,error:`Error`},J=/* @__PURE__ */ new Set([`reads`,`concurrency`]),Y=/* @__PURE__ */ new Set([`description`,`documentation`,`handler`,`concurrency`]);function parseCommand(e,t){let n=/* @__PURE__ */ new Set,r=new _(e.reader.fork(),e.path,e.languages);return r.sourceOptions=e.sourceOptions,r.streamCandidates=e.streamCandidates,parseCommandBody(r,t,void 0,n),parseCommandBody(e,t,n)}function parseCommandBody(t,r,o,u){let g=L.exec(r.content)?.[1]??``;g===``&&t.error(e.InvalidCommandDeclaration,`Invalid command declaration '${r.content}' - expected 'command <Name>'`,i(r));let _=[],b=[],S,C=[],w=[],T=[],E=[],O,j=null,M=null,B=null,V=null,H=[],U=null,W=[],K=null;for(let a=t.peekChild(r.indent);a!==void 0;a=t.peekChild(r.indent)){t.reader.takeSignificant();let r=c(a.content),s=d(a);if(r===`calendar`&&R.test(a.content)){let r=z.exec(a.content);K!==null||r===null?t.error(e.InvalidCommandCalendar,`A command declares at most one 'calendar "<id>"' or 'calendar from $context.<member>'.`,i(a)):K={kind:`CommandCalendarSyntax`,id:r[1]===void 0?null:n(r[1]),contextMember:r[2]??null,location:i(a)}}else if(s!==void 0&&(Y.has(r)||r===`validate`&&a.content!==`validate csharp`))S=addProperty(t,_,s,g,a,S);else if(r===`returns`){let e=A.exec(a.content);e!==null&&!e[1].startsWith(`@`)&&s!==void 0?o===void 0?(_.push(s),b.push({line:a,candidate:s,response:null})):o.has(s.type.name)?b.push({line:a,candidate:null,response:k(t,a)}):S=addProperty(t,_,s,g,a,S):s===void 0?l(t,a)?t.skipBlock(a.indent):b.push({line:a,candidate:null,response:k(t,a)}):S=addProperty(t,_,s,g,a,S)}else if(r===`stream`&&ee.test(a.content)&&s!==void 0&&t.streamCandidates?.hasSource(s.type.name.split(`.`)[0])===!0){let[n,r]=s.type.name.split(`.`),o=t.streamCandidates.hasPropertyType(s.type.name)&&t.streamCandidates.hasUniqueStream(n,r),c=x(t,a,s,o);(U!==null||W.length>0)&&t.error(e.InvalidCommandStream,`A command declares at most one stream route.`,i(a)),o||U!==null?W.push(c):U=c}else if(r===`runs`&&v(a))y(t,a);else if(r===`description`)j=m(t,a,j,`Command '${g}'`);else if(r===`documentation`)M=h(t,a,M,`Command '${g}'`);else if(r===`authorize`)B=f(B,p(t,a));else if(r===`validate`){let e=parseValidate(t,a,`command`,g);e!==void 0&&C.push(e)}else if(r===`produces`){let e=I(t,a,!0);e!==void 0&&w.push(e)}else if(r===`handler`)V=D(t,a),H.push({handler:V,location:i(a)});else if(J.has(r)){let n=r===`reads`?F(t,a):void 0;n!==void 0&&E.push(n),r===`concurrency`&&O===void 0&&(O=P(t,a));let o=/^reads\s+([A-Z]\w*)(?:\s+as\s+([a-z_]\w*))?(?:\s+by\s+([a-z_]\w*))?$/.exec(a.content);o!==null&&T.push({readModel:o[1],alias:o[2]??null}),G.test(a.content)&&t.error(e.OptionalReadsNotSupported,`Optional reads are not yet supported (see #308).`,i(a)),t.skipOpaqueBlock(a.indent)}else s===void 0?(l(t,a),t.error(e.UnknownCommandDirective,`Unexpected '${a.content}' in command body`,i(a)),t.skipBlock(a.indent)):S=addProperty(t,_,s,g,a,S)}let q=new Set(b.flatMap(e=>e.candidate===null?[]:[e.candidate])),X=new Set(_.filter(e=>!q.has(e)).map(e=>e.name));b.some(e=>e.candidate!==null&&!X.has(e.candidate.type.name)&&e.candidate.type.name!==`returns`)&&X.add(`returns`);for(let e of X)u?.add(e);let Z=null,Q=/* @__PURE__ */ new Set;for(let n of b){let r=n.response;if(n.candidate!==null){if(!X.has(n.candidate.type.name))continue;Q.add(n.candidate),r={kind:`ScalarCommandResponseSyntax`,source:{kind:`PropertyResponseSourceSyntax`,property:n.candidate.type.name,location:n.candidate.type.location},location:i(n.line)}}r!==null&&(Z===null?Z=r:t.error(e.InvalidCommandResponse,`A command declares at most one unconditional response.`,i(n.line)))}s(H,t);let $={kind:`CommandSyntax`,name:g,description:j,documentation:M,authorize:B,properties:_.filter(e=>!Q.has(e)),validations:C,produces:w,handler:V,response:Z,stream:U,streamCandidates:W,...K===null?{}:{calendar:K},location:i(r)};return N.set($,T),a.set($,{reads:E,concurrency:O}),$}function addProperty(t,n,r,i,a,o){return u(t,r.type,a),r.isIdentifier&&o!==void 0&&(t.error(e.DuplicateCommandIdentifier,`Command '${i}' already marks '${o.name}' as identifier - only one property can be the identifier`,r.location),r={...r,isIdentifier:!1}),n.push(r),o??(r.isIdentifier?r:void 0)}function parseValidationFile(e,t,n){let r=E(e,n);return r===void 0?void 0:{kind:`FileValidateSyntax`,file:r,location:i(t)}}function hasValidationOperand(e){let t=H.exec(e.content);if(t===null)return!1;let n=t[2];return c(n)===`not`&&c(n.substring(3).trimStart())===`empty`||c(n)===`checksum`||U.test(n)}function isValidationFileBody(e,t,n){if(!S(n)||hasValidationOperand(n))return!1;let r=e.reader.fork();r.takeSignificant();let i=r.peekSignificant();return i===void 0||i.indent<=t.indent}function parseValidate(t,r,a,o){if(r.content===`validate`){let s=t.peekChild(r.indent);if(s!==void 0&&isValidationFileBody(t,r,s))return t.reader.takeSignificant(),parseValidationFile(t,r,s);if(s!==void 0&&s.content.startsWith("```")){t.reader.takeSignificant();let e=T(t.valueContext,s);return e===null&&t.skipFencedBody(),{kind:`CodeValidateSyntax`,code:e,location:i(r)}}let l=[],u=[],d;for(let s=t.peekChild(r.indent);s!==void 0;s=t.peekChild(r.indent)){if(t.reader.takeSignificant(),a===`concept`){if(t.sourceOptions.numericMode===`legacy`&&s.content.startsWith("```")){t.skipFencedBody();continue}if(d!==void 0&&s.indent<=d&&(d=void 0),d!==void 0||c(s.content)===`implementation`){t.error(e.InvalidValidationRule,`Invalid validation rule '${s.content}'`,i(s)),d??=s.indent;continue}}if(c(s.content)===`require`){let e=g(a===`concept`?t.valueContext:t,s.content.substring(7).trim(),i(s)),r=null,o=`Error`,l=!1;for(let e=t.peekChild(s.indent);e!==void 0;e=t.peekChild(s.indent)){t.reader.takeSignificant();let i=V.exec(e.content);i!==null&&i.index===0?r=i[1]===void 0?i[2]:n(i[1]):c(e.content)===`severity`?(l||(o=q[e.content.substring(8).trim()]??`Error`),l=!0):t.skipOpaqueBlock(e.indent)}e!==null&&u.push({kind:`RequirementSyntax`,condition:e,message:r,severity:o,location:i(s)});continue}let r=parseValidationRule(t,a===`concept`?{...s,content:`value ${s.content}`}:s,a,o);r!==void 0&&l.push(r)}return{kind:`DeclarativeValidateSyntax`,rules:l,requirements:u,location:i(r)}}if(a===`concept`&&c(r.content.substring(8).trimStart())===`checksum`){let e=parseValidationRule(t,{...r,content:`value ${r.content.substring(8).trimStart()}`},a,o);return e===void 0?void 0:{kind:`DeclarativeValidateSyntax`,rules:[e],requirements:[],location:i(r)}}if(r.content===`validate csharp`){let e=T(t.valueContext,{...r,content:`csharp`});return e===null&&t.skipOpaqueBlock(r.indent),{kind:`CodeValidateSyntax`,code:e,location:i(r)}}t.error(e.InvalidValidateDeclaration,`Invalid validate declaration '${r.content}' - expected 'validate' or 'validate csharp'`,i(r)),t.skipBlock(r.indent)}function parseValidationRule(t,n,r,a){let o=c(H.exec(n.content)?.[2]??``)===`checksum`,s=r===`concept`&&!o?t.valueContext:t,{content:l,message:u}=splitMessage(n.content),d=splitSeverity(s,n,l);if(d===void 0)return;let f=H.exec(d.content);if(f===null){s.error(e.InvalidValidationRule,`Invalid validation rule '${n.content}'`,i(n));return}let p=parseRule(s,f[2],n);if(p===void 0)return;p.kind===`Matches`&&p.value!==null&&M(t,p.value,i(n),n.raw,j(t,r,a,f[1]));let m=p.kind===`Rule`?parseRuleImplementation(t,n,r===`command`):{file:null,code:null,implementation:null};return{kind:`ValidationRuleSyntax`,property:f[1],rule:p.kind,value:p.value,message:u,severity:d.severity,...m,location:i(n)}}function parseRuleImplementation(t,n,r){let a=t.peekChild(n.indent);if(a===void 0)return{file:null,code:null,implementation:null};t.reader.takeSignificant();let o=r&&c(a.content)===`implementation`,s=o?O(t,a):{file:w(a)?E(t,a):null,code:!w(a)&&C(t,a)?T(t,a):null,implementation:null};!o&&s.file===null&&s.code===null&&(t.error(e.UnknownRuleImplementationDirective,`Unexpected '${a.content}' in rule implementation - expected 'file <path>' or an inline code block`,i(a)),t.skipBlock(a.indent));for(let a=t.peekChild(n.indent);a!==void 0&&(o||r&&c(a.content)===`implementation`);a=t.peekChild(n.indent))t.reader.takeSignificant(),t.error(o&&c(a.content)===`implementation`?e.InvalidImplementationBlock:e.ConflictingImplementationSources,`A named rule has one implementation wrapper and cannot mix wrapped and direct sources.`,i(a)),C(t,a)?T(t,a):t.skipBlock(a.indent);return s}function splitMessage(e){let t=V.exec(e);if(t===null)return{content:e,message:null};let r=t[1]===void 0?t[2]:n(t[1]);return{content:e.substring(0,t.index).trimEnd(),message:r}}function splitSeverity(t,n,r){let a=B.exec(r);if(a===null)return{content:r,severity:`Error`};let o=q[a[1]];if(o===void 0)t.error(e.InvalidValidationSeverity,`Unknown validation severity '${a[1]}' - expected information, warning or error`,i(n));else return{content:r.substring(0,a.index).trimEnd(),severity:o}}function parseRule(t,n,r){if(n===`not empty`)return{kind:`NotEmpty`,value:null};if(c(n)===`checksum`){let a=n.substring(8).trim();if(a!==`luhn`&&a!==`mod11`&&a!==`mod97`){t.error(e.InvalidGenerationArgument,`Checksum validation requires luhn, mod11 or mod97.`,i(r));return}return{kind:`Checksum`,value:{kind:`LiteralExpressionSyntax`,value:a,location:i(r)}}}let a=U.exec(n);if(a===null){t.error(e.InvalidValidationRule,`Invalid validation rule '${r.content}'`,i(r));return}let s=a[1]??a[2];if(s===`rule`){let n=a[3].trim();if(!W.test(n)){t.error(e.InvalidRuleName,`Invalid rule name '${n}' in '${r.content}' - expected 'rule <Name>' with an identifier`,i(r));return}return{kind:`Rule`,value:{kind:`PathExpressionSyntax`,path:n,location:i(r)}}}return{kind:K[s],value:o(a[3],i(r),t)}}export{parseCommand,parseValidate};
1
+ import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";import{stringBodyPattern as t,unescapeString as n}from"../Text/StringLiteral.js";import{pattern as r}from"../Text/patterns.js";import{locationOf as i}from"./SourceLine.js";import{combineAuthorize as a,parseAuthorize as o}from"./AuthorizeParser.js";import{dependencySources as s}from"../Syntax/DependencySources.js";import{parseMappingSource as c}from"./ExpressionParser.js";import{validateHandlerContracts as l}from"./CommandHandlerValidator.js";import{firstWord as u}from"./LineText.js";import{reportInvalidModifierOrder as d,reportLegacyOptionalSuffix as f,tryParseProperty as p}from"./PropertyLineParser.js";import{parseDescription as m}from"./DescriptionParser.js";import{parseDocumentation as h}from"./DocumentationParser.js";import{parseCondition as g}from"./ConditionParser.js";import{ParserContext as _}from"./ParserContext.js";import{isReactionIdentityLine as v,misplacedReactionIdentity as y}from"./ReactionIdentityParser.js";import{sourceStreamPattern as b}from"../Text/SourceStreamNames.js";import{parseCommandStream as x}from"./EventSourceParser.js";import{isFileDirectiveAmongProperties as S}from"./FileReferences.js";import{isCode as C,isFile as w,parseCode as T,parseFile as E,parseHandler as D,parseImplementationWrapper as O}from"./ImplementationParser.js";import{parseCommandResponse as k,scalarResponsePattern as A}from"./CommandResponseParser.js";import{matchSubject as j,validateMatchOperand as M}from"./MatchOperandValidation.js";import{commandReadSources as N}from"./CommandReadSources.js";import{captureConcurrency as P}from"./DependencySourceParser.js";import{parseReads as F}from"./ReadsParser.js";import{parseProduces as I}from"./ProducesParser.js";const L=r(`^command\\s+([A-Za-z_]\\w*)$`),R=b(`^stream\\s+[A-Za-z_]\\w*\\.[A-Za-z_]\\w*$`),ee=r(`^calendar\\s+(?:"|from\\s+\\$context\\.)`),z=r(`^calendar\\s+(?:"(${t})"|from\\s+\\$context\\.([A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)*))$`),B=r(`\\bseverity\\s+(\\S+)$`),V=r(`\\bmessage\\s+(?:"(${t})"|(\\$strings\\.\\S*))$`),H=r(`^([\\w.]+)\\s+(.+)$`),U=r(`^(?:(not empty|matches|not contains|contains|starts with|ends with|max|min|rule)(?:\\s+|$)|(length ==|decimals <=|all >=|all >|>=|<=|==|!=|>|<)\\s*)(.*)$`),W=b(`^[A-Za-z_]\\w*$`),G=r(`^reads\\s+[A-Z]\\w*\\s+optional(?:\\s|$)`),K={max:`Max`,min:`Min`,">":`GreaterThan`,">=":`GreaterThanOrEqual`,"<":`LessThan`,"<=":`LessThanOrEqual`,"==":`Equal`,"!=":`NotEqual`,"length ==":`Length`,"decimals <=":`DecimalPlaces`,matches:`Matches`,contains:`Contains`,"not contains":`NotContains`,"starts with":`StartsWith`,"ends with":`EndsWith`,"all >":`AllGreaterThan`,"all >=":`AllGreaterThanOrEqual`},q={information:`Information`,warning:`Warning`,error:`Error`},J=/* @__PURE__ */ new Set([`reads`,`concurrency`]),Y=/* @__PURE__ */ new Set([`description`,`documentation`,`handler`,`concurrency`]);function parseCommand(e,t){let n=/* @__PURE__ */ new Set,r=new _(e.reader.fork(),e.path,e.languages);return r.sourceOptions=e.sourceOptions,r.streamCandidates=e.streamCandidates,parseCommandBody(r,t,void 0,n),parseCommandBody(e,t,n)}function parseCommandBody(t,r,c,f){let g=L.exec(r.content)?.[1]??``;g===``&&t.error(e.InvalidCommandDeclaration,`Invalid command declaration '${r.content}' - expected 'command <Name>'`,i(r));let _=[],b=[],S,C=[],w=[],T=[],E=[],O,j=null,M=null,B=null,V=null,H=[],U=null,W=[],K=null;for(let s=t.peekChild(r.indent);s!==void 0;s=t.peekChild(r.indent)){t.reader.takeSignificant();let r=u(s.content),l=p(s);if(r===`calendar`&&ee.test(s.content)){let r=z.exec(s.content);K!==null||r===null?t.error(e.InvalidCommandCalendar,`A command declares at most one 'calendar "<id>"' or 'calendar from $context.<member>'.`,i(s)):K={kind:`CommandCalendarSyntax`,id:r[1]===void 0?null:n(r[1]),contextMember:r[2]??null,location:i(s)}}else if(l!==void 0&&(Y.has(r)||r===`validate`&&s.content!==`validate csharp`))S=addProperty(t,_,l,g,s,S);else if(r===`returns`){let e=A.exec(s.content);e!==null&&!e[1].startsWith(`@`)&&l!==void 0?c===void 0?(_.push(l),b.push({line:s,candidate:l,response:null})):c.has(l.type.name)?b.push({line:s,candidate:null,response:k(t,s)}):S=addProperty(t,_,l,g,s,S):l===void 0?d(t,s)?t.skipBlock(s.indent):b.push({line:s,candidate:null,response:k(t,s)}):S=addProperty(t,_,l,g,s,S)}else if(r===`stream`&&R.test(s.content)&&l!==void 0&&t.streamCandidates?.hasSource(l.type.name.split(`.`)[0])===!0){let[n,r]=l.type.name.split(`.`),a=t.streamCandidates.hasPropertyType(l.type.name)&&t.streamCandidates.hasUniqueStream(n,r),o=x(t,s,l,a);(U!==null||W.length>0)&&t.error(e.InvalidCommandStream,`A command declares at most one stream route.`,i(s)),a||U!==null?W.push(o):U=o}else if(r===`runs`&&v(s))y(t,s);else if(r===`description`)j=m(t,s,j,`Command '${g}'`);else if(r===`documentation`)M=h(t,s,M,`Command '${g}'`);else if(r===`authorize`)B=a(B,o(t,s));else if(r===`validate`){let e=parseValidate(t,s,`command`,g);e!==void 0&&C.push(e)}else if(r===`produces`){let e=I(t,s,!0);e!==void 0&&w.push(e)}else if(r===`handler`)V=D(t,s),H.push({handler:V,location:i(s)});else if(J.has(r)){let n=r===`reads`?F(t,s):void 0;n!==void 0&&E.push(n),r===`concurrency`&&O===void 0&&(O=P(t,s));let a=/^reads\s+([A-Z]\w*)(?:\s+as\s+([a-z_]\w*))?(?:\s+by\s+([a-z_]\w*))?$/.exec(s.content);a!==null&&T.push({readModel:a[1],alias:a[2]??null}),G.test(s.content)&&t.error(e.OptionalReadsNotSupported,`Optional reads are not yet supported (see #308).`,i(s)),t.skipOpaqueBlock(s.indent)}else l===void 0?(d(t,s),t.error(e.UnknownCommandDirective,`Unexpected '${s.content}' in command body`,i(s)),t.skipBlock(s.indent)):S=addProperty(t,_,l,g,s,S)}let q=new Set(b.flatMap(e=>e.candidate===null?[]:[e.candidate])),X=new Set(_.filter(e=>!q.has(e)).map(e=>e.name));b.some(e=>e.candidate!==null&&!X.has(e.candidate.type.name)&&e.candidate.type.name!==`returns`)&&X.add(`returns`);for(let e of X)f?.add(e);let Z=null,Q=/* @__PURE__ */ new Set;for(let n of b){let r=n.response;if(n.candidate!==null){if(!X.has(n.candidate.type.name))continue;Q.add(n.candidate),r={kind:`ScalarCommandResponseSyntax`,source:{kind:`PropertyResponseSourceSyntax`,property:n.candidate.type.name,location:n.candidate.type.location},location:i(n.line)}}r!==null&&(Z===null?Z=r:t.error(e.InvalidCommandResponse,`A command declares at most one unconditional response.`,i(n.line)))}l(H,V,w.length>0,t);let $={kind:`CommandSyntax`,name:g,description:j,documentation:M,authorize:B,properties:_.filter(e=>!Q.has(e)),validations:C,produces:w,handler:V,response:Z,stream:U,streamCandidates:W,...K===null?{}:{calendar:K},location:i(r)};return N.set($,T),s.set($,{reads:E,concurrency:O}),$}function addProperty(t,n,r,i,a,o){return f(t,r.type,a),r.isIdentifier&&o!==void 0&&(t.error(e.DuplicateCommandIdentifier,`Command '${i}' already marks '${o.name}' as identifier - only one property can be the identifier`,r.location),r={...r,isIdentifier:!1}),n.push(r),o??(r.isIdentifier?r:void 0)}function parseValidationFile(e,t,n){let r=E(e,n);return r===void 0?void 0:{kind:`FileValidateSyntax`,file:r,location:i(t)}}function hasValidationOperand(e){let t=H.exec(e.content);if(t===null)return!1;let n=t[2];return u(n)===`not`&&u(n.substring(3).trimStart())===`empty`||u(n)===`checksum`||U.test(n)}function isValidationFileBody(e,t,n){if(!S(n)||hasValidationOperand(n))return!1;let r=e.reader.fork();r.takeSignificant();let i=r.peekSignificant();return i===void 0||i.indent<=t.indent}function parseValidate(t,r,a,o){if(r.content===`validate`){let s=t.peekChild(r.indent);if(s!==void 0&&isValidationFileBody(t,r,s))return t.reader.takeSignificant(),parseValidationFile(t,r,s);if(s!==void 0&&s.content.startsWith("```")){t.reader.takeSignificant();let e=T(t.valueContext,s);return e===null&&t.skipFencedBody(),{kind:`CodeValidateSyntax`,code:e,location:i(r)}}let c=[],l=[],d;for(let s=t.peekChild(r.indent);s!==void 0;s=t.peekChild(r.indent)){if(t.reader.takeSignificant(),a===`concept`){if(t.sourceOptions.numericMode===`legacy`&&s.content.startsWith("```")){t.skipFencedBody();continue}if(d!==void 0&&s.indent<=d&&(d=void 0),d!==void 0||u(s.content)===`implementation`){t.error(e.InvalidValidationRule,`Invalid validation rule '${s.content}'`,i(s)),d??=s.indent;continue}}if(u(s.content)===`require`){let e=g(a===`concept`?t.valueContext:t,s.content.substring(7).trim(),i(s)),r=null,o=`Error`,c=!1;for(let e=t.peekChild(s.indent);e!==void 0;e=t.peekChild(s.indent)){t.reader.takeSignificant();let i=V.exec(e.content);i!==null&&i.index===0?r=i[1]===void 0?i[2]:n(i[1]):u(e.content)===`severity`?(c||(o=q[e.content.substring(8).trim()]??`Error`),c=!0):t.skipOpaqueBlock(e.indent)}e!==null&&l.push({kind:`RequirementSyntax`,condition:e,message:r,severity:o,location:i(s)});continue}let r=parseValidationRule(t,a===`concept`?{...s,content:`value ${s.content}`}:s,a,o);r!==void 0&&c.push(r)}return{kind:`DeclarativeValidateSyntax`,rules:c,requirements:l,location:i(r)}}if(a===`concept`&&u(r.content.substring(8).trimStart())===`checksum`){let e=parseValidationRule(t,{...r,content:`value ${r.content.substring(8).trimStart()}`},a,o);return e===void 0?void 0:{kind:`DeclarativeValidateSyntax`,rules:[e],requirements:[],location:i(r)}}if(r.content===`validate csharp`){let e=T(t.valueContext,{...r,content:`csharp`});return e===null&&t.skipOpaqueBlock(r.indent),{kind:`CodeValidateSyntax`,code:e,location:i(r)}}t.error(e.InvalidValidateDeclaration,`Invalid validate declaration '${r.content}' - expected 'validate' or 'validate csharp'`,i(r)),t.skipBlock(r.indent)}function parseValidationRule(t,n,r,a){let o=u(H.exec(n.content)?.[2]??``)===`checksum`,s=r===`concept`&&!o?t.valueContext:t,{content:c,message:l}=splitMessage(n.content),d=splitSeverity(s,n,c);if(d===void 0)return;let f=H.exec(d.content);if(f===null){s.error(e.InvalidValidationRule,`Invalid validation rule '${n.content}'`,i(n));return}let p=parseRule(s,f[2],n);if(p===void 0)return;p.kind===`Matches`&&p.value!==null&&M(t,p.value,i(n),n.raw,j(t,r,a,f[1]));let m=p.kind===`Rule`?parseRuleImplementation(t,n,r===`command`):{file:null,code:null,implementation:null};return{kind:`ValidationRuleSyntax`,property:f[1],rule:p.kind,value:p.value,message:l,severity:d.severity,...m,location:i(n)}}function parseRuleImplementation(t,n,r){let a=t.peekChild(n.indent);if(a===void 0)return{file:null,code:null,implementation:null};t.reader.takeSignificant();let o=r&&u(a.content)===`implementation`,s=o?O(t,a):{file:w(a)?E(t,a):null,code:!w(a)&&C(t,a)?T(t,a):null,implementation:null};!o&&s.file===null&&s.code===null&&(t.error(e.UnknownRuleImplementationDirective,`Unexpected '${a.content}' in rule implementation - expected 'file <path>' or an inline code block`,i(a)),t.skipBlock(a.indent));for(let a=t.peekChild(n.indent);a!==void 0&&(o||r&&u(a.content)===`implementation`);a=t.peekChild(n.indent))t.reader.takeSignificant(),t.error(o&&u(a.content)===`implementation`?e.InvalidImplementationBlock:e.ConflictingImplementationSources,`A named rule has one implementation wrapper and cannot mix wrapped and direct sources.`,i(a)),C(t,a)?T(t,a):t.skipBlock(a.indent);return s}function splitMessage(e){let t=V.exec(e);if(t===null)return{content:e,message:null};let r=t[1]===void 0?t[2]:n(t[1]);return{content:e.substring(0,t.index).trimEnd(),message:r}}function splitSeverity(t,n,r){let a=B.exec(r);if(a===null)return{content:r,severity:`Error`};let o=q[a[1]];if(o===void 0)t.error(e.InvalidValidationSeverity,`Unknown validation severity '${a[1]}' - expected information, warning or error`,i(n));else return{content:r.substring(0,a.index).trimEnd(),severity:o}}function parseRule(t,n,r){if(n===`not empty`)return{kind:`NotEmpty`,value:null};if(u(n)===`checksum`){let a=n.substring(8).trim();if(a!==`luhn`&&a!==`mod11`&&a!==`mod97`){t.error(e.InvalidGenerationArgument,`Checksum validation requires luhn, mod11 or mod97.`,i(r));return}return{kind:`Checksum`,value:{kind:`LiteralExpressionSyntax`,value:a,location:i(r)}}}let a=U.exec(n);if(a===null){t.error(e.InvalidValidationRule,`Invalid validation rule '${r.content}'`,i(r));return}let o=a[1]??a[2];if(o===`rule`){let n=a[3].trim();if(!W.test(n)){t.error(e.InvalidRuleName,`Invalid rule name '${n}' in '${r.content}' - expected 'rule <Name>' with an identifier`,i(r));return}return{kind:`Rule`,value:{kind:`PathExpressionSyntax`,path:n,location:i(r)}}}return{kind:K[o],value:c(a[3],i(r),t)}}export{parseCommand,parseValidate};
2
2
  //# sourceMappingURL=CommandParser.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"CommandParser.js","names":["header","pattern","routeHeader","sourceStreamPattern","calendarPrefix","calendarPattern","stringBodyPattern","severityPattern","messagePattern","rulePattern","operandPattern","ruleNamePattern","optionalReads","operandKinds","severities","opaqueDirectives","propertyShapedDirectives","names","lookahead","ParserContext","context","line","name","DiagnosticCodes","locationOf","properties","responses","identifier","validations","produces","reads","referenceReads","concurrency","description","documentation","authorize","handler","handlers","stream","streamCandidates","calendar","child","keyword","firstWord","asProperty","tryParseProperty","match","unescapeString","scalar","scalarResponsePattern","responseNames","parseCommandResponse","reportInvalidModifierOrder","source","streamName","ambiguous","route","parseCommandStream","isReactionIdentityLine","misplacedReactionIdentity","parseDescription","parseDocumentation","combineAuthorize","parseAuthorize","validate","production","parseProduces","parseHandler","reference","parseReads","captureConcurrency","read","candidates","entry","property","discoveredNames","response","removed","parsed","validateHandlerOccurrences","syntax","commandReadSources","dependencySources","reportLegacyOptionalSuffix","commandName","file","parseFile","body","rule","isFileDirectiveAmongProperties","next","fence","code","parseCode","rules","requirements","wrapperIndent","owner","condition","parseCondition","message","severity","hasSeverity","directive","matched","ownerName","checksum","valueContext","withSeverity","validateMatchOperand","matchSubject","wrapped","commandOwner","parseImplementationWrapper","isFile","isCode","extra","content","text","algorithm","operand","operator","parseMappingSource"],"sources":["../../../../../../Compiler/Parsing/CommandParser.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { DiagnosticCodes } from '../Diagnostics/DiagnosticCodes';\nimport { validateHandlerOccurrences } from './CommandHandlerValidator';\nimport { SourceLocation } from '../Diagnostics/SourceLocation';\nimport { RequirementSyntax } from '../Syntax/Conditions';\nimport { parseCondition } from './ConditionParser';\nimport { AuthorizeSyntax } from '../Syntax/Authorization';\nimport { CommandSyntax, ValidateSyntax, ValidationRuleKind, ValidationRuleSyntax, ValidationSeverity } from '../Syntax/Commands';\nimport { PropertySyntax } from '../Syntax/Declarations';\nimport { CommandCalendarSyntax } from '../Syntax/Calendar';\nimport { CommandStreamSyntax } from '../Syntax/EventSources';\nimport { parseCommandStream } from './EventSourceParser';\nimport { ExpressionSyntax } from '../Syntax/Expressions';\nimport { ProducesSyntax } from '../Syntax/Reactions';\nimport { CommandResponseSyntax } from '../Syntax/Responses';\nimport { pattern } from '../Text/patterns';\nimport { sourceStreamPattern } from '../Text/SourceStreamNames';\nimport { stringBodyPattern, unescapeString } from '../Text/StringLiteral';\nimport { combineAuthorize, parseAuthorize } from './AuthorizeParser';\nimport { parseCommandResponse, scalarResponsePattern } from './CommandResponseParser';\nimport { parseDescription } from './DescriptionParser';\nimport { parseDocumentation } from './DocumentationParser';\nimport { isCode, isFile, parseCode, parseFile, parseHandler, parseImplementationWrapper } from './ImplementationParser';\nimport { CodeBlockSyntax, FileReferenceSyntax, HandlerSyntax, ImplementationSyntax } from '../Syntax/Implementations';\nimport { parseMappingSource } from './ExpressionParser';\nimport { firstWord } from './LineText';\nimport { ParserContext } from './ParserContext';\nimport { matchSubject, validateMatchOperand } from './MatchOperandValidation';\nimport { isReactionIdentityLine, misplacedReactionIdentity } from './ReactionIdentityParser';\nimport { commandReadSources } from './CommandReadSources';\nimport { dependencySources, ReadsSyntax, ConcurrencySyntax } from '../Syntax/DependencySources';\nimport { captureConcurrency } from './DependencySourceParser';\nimport { parseReads } from './ReadsParser';\nimport { parseProduces } from './ProducesParser';\nimport { reportInvalidModifierOrder, reportLegacyOptionalSuffix, tryParseProperty } from './PropertyLineParser';\nimport { locationOf, SourceLine } from './SourceLine';\nimport { isFileDirectiveAmongProperties } from './FileReferences';\n\nconst header = pattern('^command\\\\s+([A-Za-z_]\\\\w*)$');\nconst routeHeader = sourceStreamPattern('^stream\\\\s+[A-Za-z_]\\\\w*\\\\.[A-Za-z_]\\\\w*$');\nconst calendarPrefix = pattern('^calendar\\\\s+(?:\"|from\\\\s+\\\\$context\\\\.)');\nconst calendarPattern = pattern(`^calendar\\\\s+(?:\"(${stringBodyPattern})\"|from\\\\s+\\\\$context\\\\.([A-Za-z_][A-Za-z0-9_]*(?:\\\\.[A-Za-z_][A-Za-z0-9_]*)*))$`);\nconst severityPattern = pattern('\\\\bseverity\\\\s+(\\\\S+)$');\nconst messagePattern = pattern(`\\\\bmessage\\\\s+(?:\"(${stringBodyPattern})\"|(\\\\$strings\\\\.\\\\S*))$`);\nconst rulePattern = pattern('^([\\\\w.]+)\\\\s+(.+)$');\nconst operandPattern = pattern('^(?:(not empty|matches|not contains|contains|starts with|ends with|max|min|rule)(?:\\\\s+|$)|(length ==|decimals <=|all >=|all >|>=|<=|==|!=|>|<)\\\\s*)(.*)$');\nconst ruleNamePattern = sourceStreamPattern('^[A-Za-z_]\\\\w*$');\nconst optionalReads = pattern('^reads\\\\s+[A-Z]\\\\w*\\\\s+optional(?:\\\\s|$)');\n\n// Every operand the pattern matches has a kind, so an operand never goes unrecognized here.\nconst operandKinds: Record<string, ValidationRuleKind> = {\n max: 'Max',\n min: 'Min',\n '>': 'GreaterThan',\n '>=': 'GreaterThanOrEqual',\n '<': 'LessThan',\n '<=': 'LessThanOrEqual',\n '==': 'Equal',\n '!=': 'NotEqual',\n 'length ==': 'Length',\n 'decimals <=': 'DecimalPlaces',\n matches: 'Matches',\n contains: 'Contains',\n 'not contains': 'NotContains',\n 'starts with': 'StartsWith',\n 'ends with': 'EndsWith',\n 'all >': 'AllGreaterThan',\n 'all >=': 'AllGreaterThanOrEqual',\n};\n\nconst severities: Record<string, ValidationSeverity> = { information: 'Information', warning: 'Warning', error: 'Error' };\n\n// Command directives this compiler does not model. They are skipped whole.\nconst opaqueDirectives = new Set(['reads', 'concurrency']);\n\n// The bare directives cannot take a type reference, so a line with property shape is a property whatever\n// keyword it starts with - 'description String' declares a property called description.\nconst propertyShapedDirectives = new Set(['description', 'documentation', 'handler', 'concurrency']);\n\nexport function parseCommand(context: ParserContext, line: SourceLine): CommandSyntax {\n // Properties are leaves, not indentation owners. Resolve ambiguous returns spelling\n // before the committed pass decides whether its deeper lines belong to a response.\n const names = new Set<string>();\n const lookahead = new ParserContext(context.reader.fork(), context.path, context.languages);\n lookahead.sourceOptions = context.sourceOptions;\n lookahead.streamCandidates = context.streamCandidates;\n parseCommandBody(lookahead, line, undefined, names);\n return parseCommandBody(context, line, names);\n}\n\nfunction parseCommandBody(context: ParserContext, line: SourceLine, responseNames?: ReadonlySet<string>, discoveredNames?: Set<string>): CommandSyntax {\n const name = header.exec(line.content)?.[1] ?? '';\n if (name === '') {\n context.error(DiagnosticCodes.InvalidCommandDeclaration, `Invalid command declaration '${line.content}' - expected 'command <Name>'`, locationOf(line));\n }\n const properties: PropertySyntax[] = [];\n const responses: { line: SourceLine; candidate: PropertySyntax | null; response: CommandResponseSyntax | null }[] = [];\n let identifier: PropertySyntax | undefined;\n const validations: ValidateSyntax[] = [];\n const produces: ProducesSyntax[] = [];\n const reads: { readModel: string; alias: string | null }[] = [];\n const referenceReads: ReadsSyntax[] = [];\n let concurrency: ConcurrencySyntax | undefined;\n let description: string | null = null;\n let documentation: string | null = null;\n let authorize: AuthorizeSyntax | null = null;\n let handler: HandlerSyntax | null = null;\n const handlers: { handler: HandlerSyntax | null; location: SourceLocation }[] = [];\n let stream: CommandStreamSyntax | null = null;\n const streamCandidates: CommandStreamSyntax[] = [];\n let calendar: CommandCalendarSyntax | null = null;\n for (let child = context.peekChild(line.indent); child !== undefined; child = context.peekChild(line.indent)) {\n context.reader.takeSignificant();\n const keyword = firstWord(child.content);\n const asProperty = tryParseProperty(child);\n if (keyword === 'calendar' && calendarPrefix.test(child.content)) {\n const match = calendarPattern.exec(child.content);\n if (calendar !== null || match === null) {\n context.error(DiagnosticCodes.InvalidCommandCalendar, 'A command declares at most one \\'calendar \"<id>\"\\' or \\'calendar from $context.<member>\\'.', locationOf(child));\n } else {\n calendar = { kind: 'CommandCalendarSyntax', id: match[1] === undefined ? null : unescapeString(match[1]), contextMember: match[2] ?? null, location: locationOf(child) };\n }\n } else if (asProperty !== undefined && (propertyShapedDirectives.has(keyword) || (keyword === 'validate' && child.content !== 'validate csharp'))) {\n identifier = addProperty(context, properties, asProperty, name, child, identifier);\n } else if (keyword === 'returns') {\n const scalar = scalarResponsePattern.exec(child.content);\n if (scalar !== null && !scalar[1].startsWith('@') && asProperty !== undefined) {\n if (responseNames === undefined) {\n properties.push(asProperty);\n responses.push({ line: child, candidate: asProperty, response: null });\n } else if (responseNames.has(asProperty.type.name)) {\n responses.push({ line: child, candidate: null, response: parseCommandResponse(context, child) });\n } else {\n identifier = addProperty(context, properties, asProperty, name, child, identifier);\n }\n } else if (asProperty !== undefined) {\n identifier = addProperty(context, properties, asProperty, name, child, identifier);\n } else if (reportInvalidModifierOrder(context, child)) {\n context.skipBlock(child.indent);\n } else {\n responses.push({ line: child, candidate: null, response: parseCommandResponse(context, child) });\n }\n } else if (keyword === 'stream' && routeHeader.test(child.content) && asProperty !== undefined && context.streamCandidates?.hasSource(asProperty.type.name.split('.')[0]) === true) {\n const [source, streamName] = asProperty.type.name.split('.');\n const ambiguous = context.streamCandidates.hasPropertyType(asProperty.type.name) && context.streamCandidates.hasUniqueStream(source, streamName);\n const route = parseCommandStream(context, child, asProperty, ambiguous);\n if (stream !== null || streamCandidates.length > 0) context.error(DiagnosticCodes.InvalidCommandStream, 'A command declares at most one stream route.', locationOf(child));\n if (ambiguous || stream !== null) streamCandidates.push(route);\n else stream = route;\n } else if (keyword === 'runs' && isReactionIdentityLine(child)) {\n misplacedReactionIdentity(context, child);\n } else if (keyword === 'description') {\n description = parseDescription(context, child, description, `Command '${name}'`);\n } else if (keyword === 'documentation') {\n documentation = parseDocumentation(context, child, documentation, `Command '${name}'`);\n } else if (keyword === 'authorize') {\n authorize = combineAuthorize(authorize, parseAuthorize(context, child));\n } else if (keyword === 'validate') {\n const validate = parseValidate(context, child, 'command', name);\n if (validate !== undefined) {\n validations.push(validate);\n }\n } else if (keyword === 'produces') {\n const production = parseProduces(context, child, true);\n if (production !== undefined) produces.push(production);\n } else if (keyword === 'handler') {\n handler = parseHandler(context, child);\n handlers.push({ handler, location: locationOf(child) });\n } else if (opaqueDirectives.has(keyword)) {\n const reference = keyword === 'reads' ? parseReads(context, child) : undefined;\n if (reference !== undefined) referenceReads.push(reference);\n if (keyword === 'concurrency' && concurrency === undefined) concurrency = captureConcurrency(context, child);\n const read = /^reads\\s+([A-Z]\\w*)(?:\\s+as\\s+([a-z_]\\w*))?(?:\\s+by\\s+([a-z_]\\w*))?$/.exec(child.content);\n if (read !== null) reads.push({ readModel: read[1], alias: read[2] ?? null });\n if (optionalReads.test(child.content)) {\n context.error(DiagnosticCodes.OptionalReadsNotSupported, 'Optional reads are not yet supported (see #308).', locationOf(child));\n }\n context.skipOpaqueBlock(child.indent);\n } else if (asProperty !== undefined) {\n identifier = addProperty(context, properties, asProperty, name, child, identifier);\n } else {\n reportInvalidModifierOrder(context, child);\n context.error(DiagnosticCodes.UnknownCommandDirective, `Unexpected '${child.content}' in command body`, locationOf(child));\n context.skipBlock(child.indent);\n }\n }\n const candidates = new Set(responses.flatMap(entry => entry.candidate === null ? [] : [entry.candidate]));\n const names = new Set(properties.filter(property => !candidates.has(property)).map(property => property.name));\n if (responses.some(entry => entry.candidate !== null && !names.has(entry.candidate.type.name) && entry.candidate.type.name !== 'returns')) names.add('returns');\n for (const name of names) discoveredNames?.add(name);\n let response: CommandResponseSyntax | null = null;\n const removed = new Set<PropertySyntax>();\n for (const entry of responses) {\n let parsed = entry.response;\n if (entry.candidate !== null) {\n if (!names.has(entry.candidate.type.name)) continue;\n removed.add(entry.candidate);\n parsed = { kind: 'ScalarCommandResponseSyntax', source: { kind: 'PropertyResponseSourceSyntax', property: entry.candidate.type.name, location: entry.candidate.type.location }, location: locationOf(entry.line) };\n }\n if (parsed === null) continue;\n if (response !== null) {\n context.error(DiagnosticCodes.InvalidCommandResponse, 'A command declares at most one unconditional response.', locationOf(entry.line));\n } else {\n response = parsed;\n }\n }\n validateHandlerOccurrences(handlers, context);\n const syntax: CommandSyntax = { kind: 'CommandSyntax', name, description, documentation, authorize, properties: properties.filter(property => !removed.has(property)), validations, produces, handler, response, stream, streamCandidates, ...(calendar === null ? {} : { calendar }), location: locationOf(line) };\n commandReadSources.set(syntax, reads);\n dependencySources.set(syntax, { reads: referenceReads, concurrency });\n return syntax;\n}\n\nfunction addProperty(context: ParserContext, properties: PropertySyntax[], property: PropertySyntax, commandName: string, line: SourceLine, identifier: PropertySyntax | undefined): PropertySyntax | undefined {\n reportLegacyOptionalSuffix(context, property.type, line);\n if (property.isIdentifier && identifier !== undefined) {\n context.error(DiagnosticCodes.DuplicateCommandIdentifier, `Command '${commandName}' already marks '${identifier.name}' as identifier - only one property can be the identifier`, property.location);\n property = { ...property, isIdentifier: false };\n }\n properties.push(property);\n return identifier ?? (property.isIdentifier ? property : undefined);\n}\n\nfunction parseValidationFile(context: ParserContext, header: SourceLine, body: SourceLine): ValidateSyntax | undefined {\n const file = parseFile(context, body);\n return file === undefined ? undefined : { kind: 'FileValidateSyntax', file, location: locationOf(header) };\n}\n\nfunction hasValidationOperand(line: SourceLine): boolean {\n const match = rulePattern.exec(line.content);\n if (match === null) return false;\n const rule = match[2];\n return (firstWord(rule) === 'not' && firstWord(rule.substring('not'.length).trimStart()) === 'empty') ||\n firstWord(rule) === 'checksum' || operandPattern.test(rule);\n}\n\nfunction isValidationFileBody(context: ParserContext, header: SourceLine, body: SourceLine): boolean {\n if (!isFileDirectiveAmongProperties(body) || hasValidationOperand(body)) return false;\n const lookahead = context.reader.fork();\n lookahead.takeSignificant();\n const next = lookahead.peekSignificant();\n return next === undefined || next.indent <= header.indent;\n}\n\n// Reads a 'validate' block: declarative rules, or code - which is recognized but not modeled.\nexport function parseValidate(context: ParserContext, line: SourceLine, owner: 'command' | 'concept', ownerName: string): ValidateSyntax | undefined {\n if (line.content === 'validate') {\n const fence = context.peekChild(line.indent);\n if (fence !== undefined && isValidationFileBody(context, line, fence)) {\n context.reader.takeSignificant();\n return parseValidationFile(context, line, fence);\n }\n if (fence !== undefined && fence.content.startsWith('```')) {\n context.reader.takeSignificant();\n const code = parseCode(context.valueContext, fence);\n if (code === null) context.skipFencedBody();\n return { kind: 'CodeValidateSyntax', code, location: locationOf(line) };\n }\n const rules: ValidationRuleSyntax[] = [];\n const requirements: RequirementSyntax[] = [];\n let wrapperIndent: number | undefined;\n for (let child = context.peekChild(line.indent); child !== undefined; child = context.peekChild(line.indent)) {\n context.reader.takeSignificant();\n if (owner === 'concept') {\n if (context.sourceOptions.numericMode === 'legacy' && child.content.startsWith('```')) { context.skipFencedBody(); continue; }\n if (wrapperIndent !== undefined && child.indent <= wrapperIndent) wrapperIndent = undefined;\n if (wrapperIndent !== undefined || firstWord(child.content) === 'implementation') {\n context.error(DiagnosticCodes.InvalidValidationRule, `Invalid validation rule '${child.content}'`, locationOf(child));\n wrapperIndent ??= child.indent;\n continue;\n }\n }\n if (firstWord(child.content) === 'require') {\n const condition = parseCondition(owner === 'concept' ? context.valueContext : context, child.content.substring('require'.length).trim(), locationOf(child));\n let message: string | null = null;\n let severity: ValidationSeverity = 'Error';\n let hasSeverity = false;\n for (let directive = context.peekChild(child.indent); directive !== undefined; directive = context.peekChild(child.indent)) {\n context.reader.takeSignificant();\n const matched = messagePattern.exec(directive.content);\n if (matched !== null && matched.index === 0) message = matched[1] !== undefined ? unescapeString(matched[1]) : matched[2];\n else if (firstWord(directive.content) === 'severity') {\n if (!hasSeverity) severity = severities[directive.content.substring('severity'.length).trim()] ?? 'Error';\n hasSeverity = true;\n } else context.skipOpaqueBlock(directive.indent);\n }\n if (condition !== null) requirements.push({ kind: 'RequirementSyntax', condition, message, severity, location: locationOf(child) });\n continue;\n }\n const rule = parseValidationRule(context, owner === 'concept' ? { ...child, content: `value ${child.content}` } : child, owner, ownerName);\n if (rule !== undefined) {\n rules.push(rule);\n }\n }\n return { kind: 'DeclarativeValidateSyntax', rules, requirements, location: locationOf(line) };\n }\n if (owner === 'concept' && firstWord(line.content.substring('validate'.length).trimStart()) === 'checksum') {\n const ruleLine = { ...line, content: `value ${line.content.substring('validate'.length).trimStart()}` };\n const rule = parseValidationRule(context, ruleLine, owner, ownerName);\n return rule === undefined ? undefined : { kind: 'DeclarativeValidateSyntax', rules: [rule], requirements: [], location: locationOf(line) };\n }\n if (line.content === 'validate csharp') {\n const code = parseCode(context.valueContext, { ...line, content: 'csharp' });\n if (code === null) context.skipOpaqueBlock(line.indent);\n return { kind: 'CodeValidateSyntax', code, location: locationOf(line) };\n }\n context.error(DiagnosticCodes.InvalidValidateDeclaration, `Invalid validate declaration '${line.content}' - expected 'validate' or 'validate csharp'`, locationOf(line));\n context.skipBlock(line.indent);\n return undefined;\n}\n\nfunction parseValidationRule(context: ParserContext, line: SourceLine, owner: 'command' | 'concept', ownerName: string): ValidationRuleSyntax | undefined {\n // Checksum is a new declaration, not enrichment of a formerly opaque Legacy rule.\n const checksum = firstWord(rulePattern.exec(line.content)?.[2] ?? '') === 'checksum';\n const valueContext = owner === 'concept' && !checksum ? context.valueContext : context;\n const { content: withSeverity, message } = splitMessage(line.content);\n const severity = splitSeverity(valueContext, line, withSeverity);\n if (severity === undefined) {\n return undefined;\n }\n const match = rulePattern.exec(severity.content);\n if (match === null) {\n valueContext.error(DiagnosticCodes.InvalidValidationRule, `Invalid validation rule '${line.content}'`, locationOf(line));\n return undefined;\n }\n const parsed = parseRule(valueContext, match[2], line);\n if (parsed === undefined) {\n return undefined;\n }\n if (parsed.kind === 'Matches' && parsed.value !== null) validateMatchOperand(context, parsed.value, locationOf(line), line.raw, matchSubject(context, owner, ownerName, match[1]));\n const source = parsed.kind === 'Rule' ? parseRuleImplementation(context, line, owner === 'command') : { file: null, code: null, implementation: null };\n return {\n kind: 'ValidationRuleSyntax',\n property: match[1],\n rule: parsed.kind,\n value: parsed.value,\n message,\n severity: severity.severity,\n ...source,\n location: locationOf(line),\n };\n}\n\nfunction parseRuleImplementation(context: ParserContext, rule: SourceLine, commandOwner: boolean): { file: FileReferenceSyntax | null; code: CodeBlockSyntax | null; implementation: ImplementationSyntax | null } {\n const body = context.peekChild(rule.indent);\n if (body === undefined) return { file: null, code: null, implementation: null };\n context.reader.takeSignificant();\n const wrapped = commandOwner && firstWord(body.content) === 'implementation';\n const source = wrapped ? parseImplementationWrapper(context, body) : {\n file: isFile(body) ? parseFile(context, body) : null,\n code: !isFile(body) && isCode(context, body) ? parseCode(context, body) : null,\n implementation: null,\n };\n if (!wrapped && source.file === null && source.code === null) {\n context.error(DiagnosticCodes.UnknownRuleImplementationDirective, `Unexpected '${body.content}' in rule implementation - expected 'file <path>' or an inline code block`, locationOf(body));\n context.skipBlock(body.indent);\n }\n for (let extra = context.peekChild(rule.indent); extra !== undefined && (wrapped || (commandOwner && firstWord(extra.content) === 'implementation')); extra = context.peekChild(rule.indent)) {\n context.reader.takeSignificant();\n context.error(wrapped && firstWord(extra.content) === 'implementation' ? DiagnosticCodes.InvalidImplementationBlock : DiagnosticCodes.ConflictingImplementationSources,\n 'A named rule has one implementation wrapper and cannot mix wrapped and direct sources.', locationOf(extra));\n if (isCode(context, extra)) parseCode(context, extra);\n else context.skipBlock(extra.indent);\n }\n return source;\n}\n\nfunction splitMessage(content: string): { content: string; message: string | null } {\n const match = messagePattern.exec(content);\n if (match === null) {\n return { content, message: null };\n }\n const message = match[1] !== undefined ? unescapeString(match[1]) : match[2];\n return { content: content.substring(0, match.index).trimEnd(), message };\n}\n\nfunction splitSeverity(context: ParserContext, line: SourceLine, text: string): { content: string; severity: ValidationSeverity } | undefined {\n const match = severityPattern.exec(text);\n if (match === null) {\n return { content: text, severity: 'Error' };\n }\n const severity = severities[match[1]];\n if (severity === undefined) {\n context.error(DiagnosticCodes.InvalidValidationSeverity, `Unknown validation severity '${match[1]}' - expected information, warning or error`, locationOf(line));\n return undefined;\n }\n return { content: text.substring(0, match.index).trimEnd(), severity };\n}\n\nfunction parseRule(context: ParserContext, rule: string, line: SourceLine): { kind: ValidationRuleKind; value: ExpressionSyntax | null } | undefined {\n if (rule === 'not empty') {\n return { kind: 'NotEmpty', value: null };\n }\n if (firstWord(rule) === 'checksum') {\n const algorithm = rule.substring('checksum'.length).trim();\n if (algorithm !== 'luhn' && algorithm !== 'mod11' && algorithm !== 'mod97') {\n context.error(DiagnosticCodes.InvalidGenerationArgument, 'Checksum validation requires luhn, mod11 or mod97.', locationOf(line));\n return undefined;\n }\n return { kind: 'Checksum', value: { kind: 'LiteralExpressionSyntax', value: algorithm, location: locationOf(line) } };\n }\n const operand = operandPattern.exec(rule);\n if (operand === null) {\n context.error(DiagnosticCodes.InvalidValidationRule, `Invalid validation rule '${line.content}'`, locationOf(line));\n return undefined;\n }\n const operator = operand[1] ?? operand[2];\n if (operator === 'rule') {\n const name = operand[3].trim();\n if (!ruleNamePattern.test(name)) {\n context.error(DiagnosticCodes.InvalidRuleName, `Invalid rule name '${name}' in '${line.content}' - expected 'rule <Name>' with an identifier`, locationOf(line));\n return undefined;\n }\n return { kind: 'Rule', value: { kind: 'PathExpressionSyntax', path: name, location: locationOf(line) } };\n }\n return { kind: operandKinds[operator], value: parseMappingSource(operand[3], locationOf(line), context) };\n}\n"],"mappings":"wwDAwCA,MAAMA,EAASC,EAAQ,8BAA8B,EAC/CC,GAAcC,EAAoB,2CAA2C,EAC7EC,EAAiBH,EAAQ,0CAA0C,EACnEI,EAAkBJ,EAAQ,qBAAqBK,EAAkB,iFAAiF,EAClJC,EAAkBN,EAAQ,wBAAwB,EAClDO,EAAiBP,EAAQ,sBAAsBK,EAAkB,yBAAyB,EAC1FG,EAAcR,EAAQ,qBAAqB,EAC3CS,EAAiBT,EAAQ,2JAA2J,EACpLU,EAAkBR,EAAoB,iBAAiB,EACvDS,EAAgBX,EAAQ,0CAA0C,EAGlEY,EAAmD,CACrD,IAAK,MACL,IAAK,MACL,IAAK,cACL,KAAM,qBACN,IAAK,WACL,KAAM,kBACN,KAAM,QACN,KAAM,WACN,YAAa,SACb,cAAe,gBACf,QAAS,UACT,SAAU,WACV,eAAgB,cAChB,cAAe,aACf,YAAa,WACb,QAAS,iBACT,SAAU,uBACd,EAEMC,EAAiD,CAAE,YAAa,cAAe,QAAS,UAAW,MAAO,OAAQ,EAGlHC,kBAAmB,IAAI,IAAI,CAAC,QAAS,aAAa,CAAC,EAInDC,kBAA2B,IAAI,IAAI,CAAC,cAAe,gBAAiB,UAAW,aAAa,CAAC,EAEnG,SAAgB,aAAa,EAAwB,EAAiC,CAGlF,IAAMC,kBAAQ,IAAI,IACZC,EAAY,IAAIC,EAAcC,EAAQ,OAAO,KAAK,EAAGA,EAAQ,KAAMA,EAAQ,SAAS,EAI1F,MAHA,GAAU,cAAgBA,EAAQ,cAClC,EAAU,iBAAmBA,EAAQ,iBACrC,iBAAiBF,EAAWG,EAAM,IAAA,GAAWJ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C5G"}
1
+ {"version":3,"file":"CommandParser.js","names":["header","pattern","routeHeader","sourceStreamPattern","calendarPrefix","calendarPattern","stringBodyPattern","severityPattern","messagePattern","rulePattern","operandPattern","ruleNamePattern","optionalReads","operandKinds","severities","opaqueDirectives","propertyShapedDirectives","names","lookahead","ParserContext","context","line","name","DiagnosticCodes","locationOf","properties","responses","identifier","validations","produces","reads","referenceReads","concurrency","description","documentation","authorize","handler","handlers","stream","streamCandidates","calendar","child","keyword","firstWord","asProperty","tryParseProperty","match","unescapeString","scalar","scalarResponsePattern","responseNames","parseCommandResponse","reportInvalidModifierOrder","source","streamName","ambiguous","route","parseCommandStream","isReactionIdentityLine","misplacedReactionIdentity","parseDescription","parseDocumentation","combineAuthorize","parseAuthorize","validate","production","parseProduces","parseHandler","reference","parseReads","captureConcurrency","read","candidates","entry","property","discoveredNames","response","removed","parsed","validateHandlerContracts","syntax","commandReadSources","dependencySources","reportLegacyOptionalSuffix","commandName","file","parseFile","body","rule","isFileDirectiveAmongProperties","next","fence","code","parseCode","rules","requirements","wrapperIndent","owner","condition","parseCondition","message","severity","hasSeverity","directive","matched","ownerName","checksum","valueContext","withSeverity","validateMatchOperand","matchSubject","wrapped","commandOwner","parseImplementationWrapper","isFile","isCode","extra","content","text","algorithm","operand","operator","parseMappingSource"],"sources":["../../../../../../Compiler/Parsing/CommandParser.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { DiagnosticCodes } from '../Diagnostics/DiagnosticCodes';\nimport { validateHandlerContracts } from './CommandHandlerValidator';\nimport { SourceLocation } from '../Diagnostics/SourceLocation';\nimport { RequirementSyntax } from '../Syntax/Conditions';\nimport { parseCondition } from './ConditionParser';\nimport { AuthorizeSyntax } from '../Syntax/Authorization';\nimport { CommandSyntax, ValidateSyntax, ValidationRuleKind, ValidationRuleSyntax, ValidationSeverity } from '../Syntax/Commands';\nimport { PropertySyntax } from '../Syntax/Declarations';\nimport { CommandCalendarSyntax } from '../Syntax/Calendar';\nimport { CommandStreamSyntax } from '../Syntax/EventSources';\nimport { parseCommandStream } from './EventSourceParser';\nimport { ExpressionSyntax } from '../Syntax/Expressions';\nimport { ProducesSyntax } from '../Syntax/Reactions';\nimport { CommandResponseSyntax } from '../Syntax/Responses';\nimport { pattern } from '../Text/patterns';\nimport { sourceStreamPattern } from '../Text/SourceStreamNames';\nimport { stringBodyPattern, unescapeString } from '../Text/StringLiteral';\nimport { combineAuthorize, parseAuthorize } from './AuthorizeParser';\nimport { parseCommandResponse, scalarResponsePattern } from './CommandResponseParser';\nimport { parseDescription } from './DescriptionParser';\nimport { parseDocumentation } from './DocumentationParser';\nimport { isCode, isFile, parseCode, parseFile, parseHandler, parseImplementationWrapper } from './ImplementationParser';\nimport { CodeBlockSyntax, FileReferenceSyntax, HandlerSyntax, ImplementationSyntax } from '../Syntax/Implementations';\nimport { parseMappingSource } from './ExpressionParser';\nimport { firstWord } from './LineText';\nimport { ParserContext } from './ParserContext';\nimport { matchSubject, validateMatchOperand } from './MatchOperandValidation';\nimport { isReactionIdentityLine, misplacedReactionIdentity } from './ReactionIdentityParser';\nimport { commandReadSources } from './CommandReadSources';\nimport { dependencySources, ReadsSyntax, ConcurrencySyntax } from '../Syntax/DependencySources';\nimport { captureConcurrency } from './DependencySourceParser';\nimport { parseReads } from './ReadsParser';\nimport { parseProduces } from './ProducesParser';\nimport { reportInvalidModifierOrder, reportLegacyOptionalSuffix, tryParseProperty } from './PropertyLineParser';\nimport { locationOf, SourceLine } from './SourceLine';\nimport { isFileDirectiveAmongProperties } from './FileReferences';\n\nconst header = pattern('^command\\\\s+([A-Za-z_]\\\\w*)$');\nconst routeHeader = sourceStreamPattern('^stream\\\\s+[A-Za-z_]\\\\w*\\\\.[A-Za-z_]\\\\w*$');\nconst calendarPrefix = pattern('^calendar\\\\s+(?:\"|from\\\\s+\\\\$context\\\\.)');\nconst calendarPattern = pattern(`^calendar\\\\s+(?:\"(${stringBodyPattern})\"|from\\\\s+\\\\$context\\\\.([A-Za-z_][A-Za-z0-9_]*(?:\\\\.[A-Za-z_][A-Za-z0-9_]*)*))$`);\nconst severityPattern = pattern('\\\\bseverity\\\\s+(\\\\S+)$');\nconst messagePattern = pattern(`\\\\bmessage\\\\s+(?:\"(${stringBodyPattern})\"|(\\\\$strings\\\\.\\\\S*))$`);\nconst rulePattern = pattern('^([\\\\w.]+)\\\\s+(.+)$');\nconst operandPattern = pattern('^(?:(not empty|matches|not contains|contains|starts with|ends with|max|min|rule)(?:\\\\s+|$)|(length ==|decimals <=|all >=|all >|>=|<=|==|!=|>|<)\\\\s*)(.*)$');\nconst ruleNamePattern = sourceStreamPattern('^[A-Za-z_]\\\\w*$');\nconst optionalReads = pattern('^reads\\\\s+[A-Z]\\\\w*\\\\s+optional(?:\\\\s|$)');\n\n// Every operand the pattern matches has a kind, so an operand never goes unrecognized here.\nconst operandKinds: Record<string, ValidationRuleKind> = {\n max: 'Max',\n min: 'Min',\n '>': 'GreaterThan',\n '>=': 'GreaterThanOrEqual',\n '<': 'LessThan',\n '<=': 'LessThanOrEqual',\n '==': 'Equal',\n '!=': 'NotEqual',\n 'length ==': 'Length',\n 'decimals <=': 'DecimalPlaces',\n matches: 'Matches',\n contains: 'Contains',\n 'not contains': 'NotContains',\n 'starts with': 'StartsWith',\n 'ends with': 'EndsWith',\n 'all >': 'AllGreaterThan',\n 'all >=': 'AllGreaterThanOrEqual',\n};\n\nconst severities: Record<string, ValidationSeverity> = { information: 'Information', warning: 'Warning', error: 'Error' };\n\n// Command directives this compiler does not model. They are skipped whole.\nconst opaqueDirectives = new Set(['reads', 'concurrency']);\n\n// The bare directives cannot take a type reference, so a line with property shape is a property whatever\n// keyword it starts with - 'description String' declares a property called description.\nconst propertyShapedDirectives = new Set(['description', 'documentation', 'handler', 'concurrency']);\n\nexport function parseCommand(context: ParserContext, line: SourceLine): CommandSyntax {\n // Properties are leaves, not indentation owners. Resolve ambiguous returns spelling\n // before the committed pass decides whether its deeper lines belong to a response.\n const names = new Set<string>();\n const lookahead = new ParserContext(context.reader.fork(), context.path, context.languages);\n lookahead.sourceOptions = context.sourceOptions;\n lookahead.streamCandidates = context.streamCandidates;\n parseCommandBody(lookahead, line, undefined, names);\n return parseCommandBody(context, line, names);\n}\n\nfunction parseCommandBody(context: ParserContext, line: SourceLine, responseNames?: ReadonlySet<string>, discoveredNames?: Set<string>): CommandSyntax {\n const name = header.exec(line.content)?.[1] ?? '';\n if (name === '') {\n context.error(DiagnosticCodes.InvalidCommandDeclaration, `Invalid command declaration '${line.content}' - expected 'command <Name>'`, locationOf(line));\n }\n const properties: PropertySyntax[] = [];\n const responses: { line: SourceLine; candidate: PropertySyntax | null; response: CommandResponseSyntax | null }[] = [];\n let identifier: PropertySyntax | undefined;\n const validations: ValidateSyntax[] = [];\n const produces: ProducesSyntax[] = [];\n const reads: { readModel: string; alias: string | null }[] = [];\n const referenceReads: ReadsSyntax[] = [];\n let concurrency: ConcurrencySyntax | undefined;\n let description: string | null = null;\n let documentation: string | null = null;\n let authorize: AuthorizeSyntax | null = null;\n let handler: HandlerSyntax | null = null;\n const handlers: { handler: HandlerSyntax | null; location: SourceLocation }[] = [];\n let stream: CommandStreamSyntax | null = null;\n const streamCandidates: CommandStreamSyntax[] = [];\n let calendar: CommandCalendarSyntax | null = null;\n for (let child = context.peekChild(line.indent); child !== undefined; child = context.peekChild(line.indent)) {\n context.reader.takeSignificant();\n const keyword = firstWord(child.content);\n const asProperty = tryParseProperty(child);\n if (keyword === 'calendar' && calendarPrefix.test(child.content)) {\n const match = calendarPattern.exec(child.content);\n if (calendar !== null || match === null) {\n context.error(DiagnosticCodes.InvalidCommandCalendar, 'A command declares at most one \\'calendar \"<id>\"\\' or \\'calendar from $context.<member>\\'.', locationOf(child));\n } else {\n calendar = { kind: 'CommandCalendarSyntax', id: match[1] === undefined ? null : unescapeString(match[1]), contextMember: match[2] ?? null, location: locationOf(child) };\n }\n } else if (asProperty !== undefined && (propertyShapedDirectives.has(keyword) || (keyword === 'validate' && child.content !== 'validate csharp'))) {\n identifier = addProperty(context, properties, asProperty, name, child, identifier);\n } else if (keyword === 'returns') {\n const scalar = scalarResponsePattern.exec(child.content);\n if (scalar !== null && !scalar[1].startsWith('@') && asProperty !== undefined) {\n if (responseNames === undefined) {\n properties.push(asProperty);\n responses.push({ line: child, candidate: asProperty, response: null });\n } else if (responseNames.has(asProperty.type.name)) {\n responses.push({ line: child, candidate: null, response: parseCommandResponse(context, child) });\n } else {\n identifier = addProperty(context, properties, asProperty, name, child, identifier);\n }\n } else if (asProperty !== undefined) {\n identifier = addProperty(context, properties, asProperty, name, child, identifier);\n } else if (reportInvalidModifierOrder(context, child)) {\n context.skipBlock(child.indent);\n } else {\n responses.push({ line: child, candidate: null, response: parseCommandResponse(context, child) });\n }\n } else if (keyword === 'stream' && routeHeader.test(child.content) && asProperty !== undefined && context.streamCandidates?.hasSource(asProperty.type.name.split('.')[0]) === true) {\n const [source, streamName] = asProperty.type.name.split('.');\n const ambiguous = context.streamCandidates.hasPropertyType(asProperty.type.name) && context.streamCandidates.hasUniqueStream(source, streamName);\n const route = parseCommandStream(context, child, asProperty, ambiguous);\n if (stream !== null || streamCandidates.length > 0) context.error(DiagnosticCodes.InvalidCommandStream, 'A command declares at most one stream route.', locationOf(child));\n if (ambiguous || stream !== null) streamCandidates.push(route);\n else stream = route;\n } else if (keyword === 'runs' && isReactionIdentityLine(child)) {\n misplacedReactionIdentity(context, child);\n } else if (keyword === 'description') {\n description = parseDescription(context, child, description, `Command '${name}'`);\n } else if (keyword === 'documentation') {\n documentation = parseDocumentation(context, child, documentation, `Command '${name}'`);\n } else if (keyword === 'authorize') {\n authorize = combineAuthorize(authorize, parseAuthorize(context, child));\n } else if (keyword === 'validate') {\n const validate = parseValidate(context, child, 'command', name);\n if (validate !== undefined) {\n validations.push(validate);\n }\n } else if (keyword === 'produces') {\n const production = parseProduces(context, child, true);\n if (production !== undefined) produces.push(production);\n } else if (keyword === 'handler') {\n handler = parseHandler(context, child);\n handlers.push({ handler, location: locationOf(child) });\n } else if (opaqueDirectives.has(keyword)) {\n const reference = keyword === 'reads' ? parseReads(context, child) : undefined;\n if (reference !== undefined) referenceReads.push(reference);\n if (keyword === 'concurrency' && concurrency === undefined) concurrency = captureConcurrency(context, child);\n const read = /^reads\\s+([A-Z]\\w*)(?:\\s+as\\s+([a-z_]\\w*))?(?:\\s+by\\s+([a-z_]\\w*))?$/.exec(child.content);\n if (read !== null) reads.push({ readModel: read[1], alias: read[2] ?? null });\n if (optionalReads.test(child.content)) {\n context.error(DiagnosticCodes.OptionalReadsNotSupported, 'Optional reads are not yet supported (see #308).', locationOf(child));\n }\n context.skipOpaqueBlock(child.indent);\n } else if (asProperty !== undefined) {\n identifier = addProperty(context, properties, asProperty, name, child, identifier);\n } else {\n reportInvalidModifierOrder(context, child);\n context.error(DiagnosticCodes.UnknownCommandDirective, `Unexpected '${child.content}' in command body`, locationOf(child));\n context.skipBlock(child.indent);\n }\n }\n const candidates = new Set(responses.flatMap(entry => entry.candidate === null ? [] : [entry.candidate]));\n const names = new Set(properties.filter(property => !candidates.has(property)).map(property => property.name));\n if (responses.some(entry => entry.candidate !== null && !names.has(entry.candidate.type.name) && entry.candidate.type.name !== 'returns')) names.add('returns');\n for (const name of names) discoveredNames?.add(name);\n let response: CommandResponseSyntax | null = null;\n const removed = new Set<PropertySyntax>();\n for (const entry of responses) {\n let parsed = entry.response;\n if (entry.candidate !== null) {\n if (!names.has(entry.candidate.type.name)) continue;\n removed.add(entry.candidate);\n parsed = { kind: 'ScalarCommandResponseSyntax', source: { kind: 'PropertyResponseSourceSyntax', property: entry.candidate.type.name, location: entry.candidate.type.location }, location: locationOf(entry.line) };\n }\n if (parsed === null) continue;\n if (response !== null) {\n context.error(DiagnosticCodes.InvalidCommandResponse, 'A command declares at most one unconditional response.', locationOf(entry.line));\n } else {\n response = parsed;\n }\n }\n validateHandlerContracts(handlers, handler, produces.length > 0, context);\n const syntax: CommandSyntax = { kind: 'CommandSyntax', name, description, documentation, authorize, properties: properties.filter(property => !removed.has(property)), validations, produces, handler, response, stream, streamCandidates, ...(calendar === null ? {} : { calendar }), location: locationOf(line) };\n commandReadSources.set(syntax, reads);\n dependencySources.set(syntax, { reads: referenceReads, concurrency });\n return syntax;\n}\n\nfunction addProperty(context: ParserContext, properties: PropertySyntax[], property: PropertySyntax, commandName: string, line: SourceLine, identifier: PropertySyntax | undefined): PropertySyntax | undefined {\n reportLegacyOptionalSuffix(context, property.type, line);\n if (property.isIdentifier && identifier !== undefined) {\n context.error(DiagnosticCodes.DuplicateCommandIdentifier, `Command '${commandName}' already marks '${identifier.name}' as identifier - only one property can be the identifier`, property.location);\n property = { ...property, isIdentifier: false };\n }\n properties.push(property);\n return identifier ?? (property.isIdentifier ? property : undefined);\n}\n\nfunction parseValidationFile(context: ParserContext, header: SourceLine, body: SourceLine): ValidateSyntax | undefined {\n const file = parseFile(context, body);\n return file === undefined ? undefined : { kind: 'FileValidateSyntax', file, location: locationOf(header) };\n}\n\nfunction hasValidationOperand(line: SourceLine): boolean {\n const match = rulePattern.exec(line.content);\n if (match === null) return false;\n const rule = match[2];\n return (firstWord(rule) === 'not' && firstWord(rule.substring('not'.length).trimStart()) === 'empty') ||\n firstWord(rule) === 'checksum' || operandPattern.test(rule);\n}\n\nfunction isValidationFileBody(context: ParserContext, header: SourceLine, body: SourceLine): boolean {\n if (!isFileDirectiveAmongProperties(body) || hasValidationOperand(body)) return false;\n const lookahead = context.reader.fork();\n lookahead.takeSignificant();\n const next = lookahead.peekSignificant();\n return next === undefined || next.indent <= header.indent;\n}\n\n// Reads a 'validate' block: declarative rules, or code - which is recognized but not modeled.\nexport function parseValidate(context: ParserContext, line: SourceLine, owner: 'command' | 'concept', ownerName: string): ValidateSyntax | undefined {\n if (line.content === 'validate') {\n const fence = context.peekChild(line.indent);\n if (fence !== undefined && isValidationFileBody(context, line, fence)) {\n context.reader.takeSignificant();\n return parseValidationFile(context, line, fence);\n }\n if (fence !== undefined && fence.content.startsWith('```')) {\n context.reader.takeSignificant();\n const code = parseCode(context.valueContext, fence);\n if (code === null) context.skipFencedBody();\n return { kind: 'CodeValidateSyntax', code, location: locationOf(line) };\n }\n const rules: ValidationRuleSyntax[] = [];\n const requirements: RequirementSyntax[] = [];\n let wrapperIndent: number | undefined;\n for (let child = context.peekChild(line.indent); child !== undefined; child = context.peekChild(line.indent)) {\n context.reader.takeSignificant();\n if (owner === 'concept') {\n if (context.sourceOptions.numericMode === 'legacy' && child.content.startsWith('```')) { context.skipFencedBody(); continue; }\n if (wrapperIndent !== undefined && child.indent <= wrapperIndent) wrapperIndent = undefined;\n if (wrapperIndent !== undefined || firstWord(child.content) === 'implementation') {\n context.error(DiagnosticCodes.InvalidValidationRule, `Invalid validation rule '${child.content}'`, locationOf(child));\n wrapperIndent ??= child.indent;\n continue;\n }\n }\n if (firstWord(child.content) === 'require') {\n const condition = parseCondition(owner === 'concept' ? context.valueContext : context, child.content.substring('require'.length).trim(), locationOf(child));\n let message: string | null = null;\n let severity: ValidationSeverity = 'Error';\n let hasSeverity = false;\n for (let directive = context.peekChild(child.indent); directive !== undefined; directive = context.peekChild(child.indent)) {\n context.reader.takeSignificant();\n const matched = messagePattern.exec(directive.content);\n if (matched !== null && matched.index === 0) message = matched[1] !== undefined ? unescapeString(matched[1]) : matched[2];\n else if (firstWord(directive.content) === 'severity') {\n if (!hasSeverity) severity = severities[directive.content.substring('severity'.length).trim()] ?? 'Error';\n hasSeverity = true;\n } else context.skipOpaqueBlock(directive.indent);\n }\n if (condition !== null) requirements.push({ kind: 'RequirementSyntax', condition, message, severity, location: locationOf(child) });\n continue;\n }\n const rule = parseValidationRule(context, owner === 'concept' ? { ...child, content: `value ${child.content}` } : child, owner, ownerName);\n if (rule !== undefined) {\n rules.push(rule);\n }\n }\n return { kind: 'DeclarativeValidateSyntax', rules, requirements, location: locationOf(line) };\n }\n if (owner === 'concept' && firstWord(line.content.substring('validate'.length).trimStart()) === 'checksum') {\n const ruleLine = { ...line, content: `value ${line.content.substring('validate'.length).trimStart()}` };\n const rule = parseValidationRule(context, ruleLine, owner, ownerName);\n return rule === undefined ? undefined : { kind: 'DeclarativeValidateSyntax', rules: [rule], requirements: [], location: locationOf(line) };\n }\n if (line.content === 'validate csharp') {\n const code = parseCode(context.valueContext, { ...line, content: 'csharp' });\n if (code === null) context.skipOpaqueBlock(line.indent);\n return { kind: 'CodeValidateSyntax', code, location: locationOf(line) };\n }\n context.error(DiagnosticCodes.InvalidValidateDeclaration, `Invalid validate declaration '${line.content}' - expected 'validate' or 'validate csharp'`, locationOf(line));\n context.skipBlock(line.indent);\n return undefined;\n}\n\nfunction parseValidationRule(context: ParserContext, line: SourceLine, owner: 'command' | 'concept', ownerName: string): ValidationRuleSyntax | undefined {\n // Checksum is a new declaration, not enrichment of a formerly opaque Legacy rule.\n const checksum = firstWord(rulePattern.exec(line.content)?.[2] ?? '') === 'checksum';\n const valueContext = owner === 'concept' && !checksum ? context.valueContext : context;\n const { content: withSeverity, message } = splitMessage(line.content);\n const severity = splitSeverity(valueContext, line, withSeverity);\n if (severity === undefined) {\n return undefined;\n }\n const match = rulePattern.exec(severity.content);\n if (match === null) {\n valueContext.error(DiagnosticCodes.InvalidValidationRule, `Invalid validation rule '${line.content}'`, locationOf(line));\n return undefined;\n }\n const parsed = parseRule(valueContext, match[2], line);\n if (parsed === undefined) {\n return undefined;\n }\n if (parsed.kind === 'Matches' && parsed.value !== null) validateMatchOperand(context, parsed.value, locationOf(line), line.raw, matchSubject(context, owner, ownerName, match[1]));\n const source = parsed.kind === 'Rule' ? parseRuleImplementation(context, line, owner === 'command') : { file: null, code: null, implementation: null };\n return {\n kind: 'ValidationRuleSyntax',\n property: match[1],\n rule: parsed.kind,\n value: parsed.value,\n message,\n severity: severity.severity,\n ...source,\n location: locationOf(line),\n };\n}\n\nfunction parseRuleImplementation(context: ParserContext, rule: SourceLine, commandOwner: boolean): { file: FileReferenceSyntax | null; code: CodeBlockSyntax | null; implementation: ImplementationSyntax | null } {\n const body = context.peekChild(rule.indent);\n if (body === undefined) return { file: null, code: null, implementation: null };\n context.reader.takeSignificant();\n const wrapped = commandOwner && firstWord(body.content) === 'implementation';\n const source = wrapped ? parseImplementationWrapper(context, body) : {\n file: isFile(body) ? parseFile(context, body) : null,\n code: !isFile(body) && isCode(context, body) ? parseCode(context, body) : null,\n implementation: null,\n };\n if (!wrapped && source.file === null && source.code === null) {\n context.error(DiagnosticCodes.UnknownRuleImplementationDirective, `Unexpected '${body.content}' in rule implementation - expected 'file <path>' or an inline code block`, locationOf(body));\n context.skipBlock(body.indent);\n }\n for (let extra = context.peekChild(rule.indent); extra !== undefined && (wrapped || (commandOwner && firstWord(extra.content) === 'implementation')); extra = context.peekChild(rule.indent)) {\n context.reader.takeSignificant();\n context.error(wrapped && firstWord(extra.content) === 'implementation' ? DiagnosticCodes.InvalidImplementationBlock : DiagnosticCodes.ConflictingImplementationSources,\n 'A named rule has one implementation wrapper and cannot mix wrapped and direct sources.', locationOf(extra));\n if (isCode(context, extra)) parseCode(context, extra);\n else context.skipBlock(extra.indent);\n }\n return source;\n}\n\nfunction splitMessage(content: string): { content: string; message: string | null } {\n const match = messagePattern.exec(content);\n if (match === null) {\n return { content, message: null };\n }\n const message = match[1] !== undefined ? unescapeString(match[1]) : match[2];\n return { content: content.substring(0, match.index).trimEnd(), message };\n}\n\nfunction splitSeverity(context: ParserContext, line: SourceLine, text: string): { content: string; severity: ValidationSeverity } | undefined {\n const match = severityPattern.exec(text);\n if (match === null) {\n return { content: text, severity: 'Error' };\n }\n const severity = severities[match[1]];\n if (severity === undefined) {\n context.error(DiagnosticCodes.InvalidValidationSeverity, `Unknown validation severity '${match[1]}' - expected information, warning or error`, locationOf(line));\n return undefined;\n }\n return { content: text.substring(0, match.index).trimEnd(), severity };\n}\n\nfunction parseRule(context: ParserContext, rule: string, line: SourceLine): { kind: ValidationRuleKind; value: ExpressionSyntax | null } | undefined {\n if (rule === 'not empty') {\n return { kind: 'NotEmpty', value: null };\n }\n if (firstWord(rule) === 'checksum') {\n const algorithm = rule.substring('checksum'.length).trim();\n if (algorithm !== 'luhn' && algorithm !== 'mod11' && algorithm !== 'mod97') {\n context.error(DiagnosticCodes.InvalidGenerationArgument, 'Checksum validation requires luhn, mod11 or mod97.', locationOf(line));\n return undefined;\n }\n return { kind: 'Checksum', value: { kind: 'LiteralExpressionSyntax', value: algorithm, location: locationOf(line) } };\n }\n const operand = operandPattern.exec(rule);\n if (operand === null) {\n context.error(DiagnosticCodes.InvalidValidationRule, `Invalid validation rule '${line.content}'`, locationOf(line));\n return undefined;\n }\n const operator = operand[1] ?? operand[2];\n if (operator === 'rule') {\n const name = operand[3].trim();\n if (!ruleNamePattern.test(name)) {\n context.error(DiagnosticCodes.InvalidRuleName, `Invalid rule name '${name}' in '${line.content}' - expected 'rule <Name>' with an identifier`, locationOf(line));\n return undefined;\n }\n return { kind: 'Rule', value: { kind: 'PathExpressionSyntax', path: name, location: locationOf(line) } };\n }\n return { kind: operandKinds[operator], value: parseMappingSource(operand[3], locationOf(line), context) };\n}\n"],"mappings":"swDAwCA,MAAMA,EAASC,EAAQ,8BAA8B,EAC/CC,EAAcC,EAAoB,2CAA2C,EAC7EC,GAAiBH,EAAQ,0CAA0C,EACnEI,EAAkBJ,EAAQ,qBAAqBK,EAAkB,iFAAiF,EAClJC,EAAkBN,EAAQ,wBAAwB,EAClDO,EAAiBP,EAAQ,sBAAsBK,EAAkB,yBAAyB,EAC1FG,EAAcR,EAAQ,qBAAqB,EAC3CS,EAAiBT,EAAQ,2JAA2J,EACpLU,EAAkBR,EAAoB,iBAAiB,EACvDS,EAAgBX,EAAQ,0CAA0C,EAGlEY,EAAmD,CACrD,IAAK,MACL,IAAK,MACL,IAAK,cACL,KAAM,qBACN,IAAK,WACL,KAAM,kBACN,KAAM,QACN,KAAM,WACN,YAAa,SACb,cAAe,gBACf,QAAS,UACT,SAAU,WACV,eAAgB,cAChB,cAAe,aACf,YAAa,WACb,QAAS,iB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AMA,EAAQ,GACvC,GAAIC,IAAa,OAAQ,CACrB,IAAMnG,EAAOkG,EAAQ,EAAE,CAAC,KAAK,EAC7B,GAAI,CAAC7G,EAAgB,KAAKW,CAAI,EAAG,CAC7BF,EAAQ,MAAMG,EAAgB,gBAAiB,sBAAsBD,EAAK,QAAQD,EAAK,QAAQ,+CAAgDG,EAAWH,CAAI,CAAC,EAC/J,MACJ,CACA,MAAO,CAAE,KAAM,OAAQ,MAAO,CAAE,KAAM,uBAAwB,KAAMC,EAAM,SAAUE,EAAWH,CAAI,CAAE,CAAE,CAC3G,CACA,MAAO,CAAE,KAAMR,EAAa4G,GAAW,MAAOC,EAAmBF,EAAQ,GAAIhG,EAAWH,CAAI,EAAGD,CAAO,CAAE,CAC5G"}
@@ -1,2 +1,2 @@
1
- import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";import{pattern as t}from"../Text/patterns.js";import{locationOf as n}from"./SourceLine.js";import{firstWord as r}from"./LineText.js";import{combineAuthorize as i,parseAuthorize as a}from"./AuthorizeParser.js";import{parseDescription as o}from"./DescriptionParser.js";import{parsePurposeReference as s}from"./PurposeParser.js";import{parseDocumentation as c}from"./DocumentationParser.js";import{parseDependsOn as l}from"./DependsOnParser.js";import{parseFileImport as u}from"./FileImportParser.js";import{collectInputUses as d}from"./InputUses.js";import{misplacedReactionIdentity as f}from"./ReactionIdentityParser.js";import{parseExample as p}from"./SpecificationExampleParser.js";import{parseToolbar as m}from"./ScreenParser.js";import{parseSlice as h}from"./SliceParser.js";const g=t(`^feature\\s+([A-Za-z_]\\w*)$`),_=/* @__PURE__ */ new Set([`on`,`uses`,`contribute`,`template`]),v=`description, documentation, depends on <Name>, authorize, import, feature, slice, contribute, toolbar, example, 'on <trigger>' or 'uses <Behavior>'`;var FeatureBody=class{name;#e=[];#t=[];#n=[];#r=[];#i=[];#a=[];#o=[];#s=null;#c=null;#l=null;constructor(e){this.name=e}tryParse(t,n){let g=r(n.content);switch(g){case`runs`:return f(t,n),!0;case`description`:return this.#s=o(t,n,this.#s,`Feature '${this.name}'`),!0;case`documentation`:return this.#c=c(t,n,this.#c,`Feature '${this.name}'`),!0;case`depends`:return l(t,n,this.#i,e.UnknownFeatureDirective),!0;case`purpose`:return s(t,n,this.#a),!0;case`authorize`:return this.#l=i(this.#l,a(t,n)),!0;case`import`:return u(t,n,this.#r),!0;case`toolbar`:return this.#o.push(m(t,n)),!0;case`feature`:return this.#e.push(parseFeature(t,n)),!0;case`example`:return this.#n.push(p(t,n)),!0;case`slice`:return this.#t.push(h(t,n)),!0;default:return _.has(g)?(d(t,n),!0):!1}}build(e,t=!1){return{kind:`FeatureSyntax`,name:this.name,description:this.#s,documentation:this.#c,authorize:this.#l,dependsOn:this.#i,purposes:this.#a,...this.#o.length>0?{toolbars:this.#o}:{},features:this.#e,slices:this.#t,examples:this.#n,fileImports:this.#r,isPlacement:t,location:e}}};function parseFeature(t,i){let a=g.exec(i.content)?.[1]??``;a===``&&t.error(e.InvalidFeatureDeclaration,`Invalid feature declaration '${i.content}' - expected 'feature <Name>'`,n(i));let o=new FeatureBody(a),s=t.scope;t.scope=[...s,a];for(let a=t.peekChild(i.indent);a!==void 0;a=t.peekChild(i.indent))t.reader.takeSignificant(),o.tryParse(t,a)||(t.error(e.UnknownFeatureDirective,`Unexpected '${r(a.content)}' in feature body - expected ${v}`,n(a)),t.skipBlock(a.indent));return t.scope=s,o.build(n(i))}export{FeatureBody,v as featureBodyExpected,parseFeature};
1
+ import"../../_virtual/_virtual/_rolldown/runtime.js";import{DiagnosticCodes as e}from"../Diagnostics/DiagnosticCodes.js";import{pattern as t}from"../Text/patterns.js";import{locationOf as n}from"./SourceLine.js";import{combineAuthorize as r,parseAuthorize as i}from"./AuthorizeParser.js";import{firstWord as a}from"./LineText.js";import{parseDescription as o}from"./DescriptionParser.js";import{parsePurposeReference as s}from"./PurposeParser.js";import{parseDocumentation as c}from"./DocumentationParser.js";import{parseDependsOn as l}from"./DependsOnParser.js";import{parseFileImport as u}from"./FileImportParser.js";import{collectInputUses as d}from"./InputUses.js";import{misplacedReactionIdentity as f}from"./ReactionIdentityParser.js";import{parseExample as p}from"./SpecificationExampleParser.js";import{parseToolbar as m}from"./ScreenParser.js";import{parseSlice as h}from"./SliceParser.js";const g=t(`^feature\\s+([A-Za-z_]\\w*)$`),_=/* @__PURE__ */ new Set([`on`,`uses`,`contribute`,`template`]),v=`description, documentation, depends on <Name>, authorize, import, feature, slice, contribute, toolbar, example, 'on <trigger>' or 'uses <Behavior>'`;var FeatureBody=class{name;#e=[];#t=[];#n=[];#r=[];#i=[];#a=[];#o=[];#s=null;#c=null;#l=null;constructor(e){this.name=e}tryParse(t,n){let g=a(n.content);switch(g){case`runs`:return f(t,n),!0;case`description`:return this.#s=o(t,n,this.#s,`Feature '${this.name}'`),!0;case`documentation`:return this.#c=c(t,n,this.#c,`Feature '${this.name}'`),!0;case`depends`:return l(t,n,this.#i,e.UnknownFeatureDirective),!0;case`purpose`:return s(t,n,this.#a),!0;case`authorize`:return this.#l=r(this.#l,i(t,n)),!0;case`import`:return u(t,n,this.#r),!0;case`toolbar`:return this.#o.push(m(t,n)),!0;case`feature`:return this.#e.push(parseFeature(t,n)),!0;case`example`:return this.#n.push(p(t,n)),!0;case`slice`:return this.#t.push(h(t,n)),!0;default:return _.has(g)?(d(t,n),!0):!1}}build(e,t=!1){return{kind:`FeatureSyntax`,name:this.name,description:this.#s,documentation:this.#c,authorize:this.#l,dependsOn:this.#i,purposes:this.#a,...this.#o.length>0?{toolbars:this.#o}:{},features:this.#e,slices:this.#t,examples:this.#n,fileImports:this.#r,isPlacement:t,location:e}}};function parseFeature(t,r){let i=g.exec(r.content)?.[1]??``;i===``&&t.error(e.InvalidFeatureDeclaration,`Invalid feature declaration '${r.content}' - expected 'feature <Name>'`,n(r));let o=new FeatureBody(i),s=t.scope;t.scope=[...s,i];for(let i=t.peekChild(r.indent);i!==void 0;i=t.peekChild(r.indent))t.reader.takeSignificant(),o.tryParse(t,i)||(t.error(e.UnknownFeatureDirective,`Unexpected '${a(i.content)}' in feature body - expected ${v}`,n(i)),t.skipBlock(i.indent));return t.scope=s,o.build(n(r))}export{FeatureBody,v as featureBodyExpected,parseFeature};
2
2
  //# sourceMappingURL=FeatureBody.js.map