@bidirekt/typescript-sdk-cli 0.2.0 → 0.3.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 (36) hide show
  1. package/README.md +64 -32
  2. package/dist/command.js +14 -13
  3. package/dist/model/contract.js +7 -1
  4. package/dist/model/declarations-to-contract.js +97 -37
  5. package/dist/model/protocols/graphql/block-to-references.js +8 -0
  6. package/dist/model/protocols/graphql/blocks-to-merged.js +77 -0
  7. package/dist/model/protocols/graphql/contract.js +1 -0
  8. package/dist/model/protocols/graphql/field-extra.js +46 -0
  9. package/dist/model/protocols/graphql/returns-to-schema.js +77 -0
  10. package/dist/model/protocols/rest/contract.js +1 -0
  11. package/dist/model/{resources-to-merged.js → protocols/rest/resources-to-merged.js} +15 -10
  12. package/dist/model/protocols/rest/resources-to-references.js +10 -0
  13. package/dist/protocols.js +49 -0
  14. package/dist/reader/comment-tags.js +77 -37
  15. package/dist/reader/literal-options.js +8 -2
  16. package/dist/reader/program.js +1 -1
  17. package/dist/reader/project-to-contract.js +51 -23
  18. package/dist/reader/protocols/graphql/decorators-to-blocks.js +401 -0
  19. package/dist/reader/protocols/graphql/protocol-input-to-blocks.js +11 -0
  20. package/dist/reader/protocols/graphql/tags-to-blocks.js +239 -0
  21. package/dist/reader/{handler-methods.js → protocols/rest/handler-methods.js} +36 -26
  22. package/dist/reader/protocols/rest/protocol-input-to-resources.js +11 -0
  23. package/dist/reader/protocols/rest/tag-handlers.js +152 -0
  24. package/dist/reader/schema-classes.js +191 -29
  25. package/dist/reader/schema-context.js +10 -5
  26. package/dist/reader/sdk-references.js +149 -39
  27. package/dist/reader/tag-handlers.js +36 -146
  28. package/dist/reader/tag-schemas.js +82 -40
  29. package/dist/reader/type-text-to-schema-node.js +4 -1
  30. package/dist/reader/type-to-schema-node.js +60 -10
  31. package/dist/writer/contract-to-yaml.js +38 -59
  32. package/dist/writer/protocols/graphql/block-to-yaml.js +31 -0
  33. package/dist/writer/protocols/graphql/field-extra-to-yaml.js +13 -0
  34. package/dist/writer/protocols/rest/resources-to-yaml.js +36 -0
  35. package/package.json +2 -2
  36. /package/dist/model/{schema-names.js → protocols/rest/schema-names.js} +0 -0
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  In Bidirekt, each side of an integration declares in a contract file what it provides and what it consumes. This SDK writes that file from TypeScript and JavaScript code: you annotate the schemas and the handlers that provide or consume each resource, run `generate`, and get `contracts/generated.yaml`, ready for `bidirekt validate` and `bidirekt publish`. It comes in two packages: `@bidirekt/typescript-sdk`, the decorators your code imports, and `@bidirekt/typescript-sdk-cli`, the `generate` command.
6
6
 
7
- `contracts/generated.yaml` is the service's only contract file: once a service adopts the SDK, every resource and schema it provides or consumes is annotated in its code.
7
+ Once a service adopts the SDK, every resource and schema it provides or consumes is annotated in its code, and `contracts/generated.yaml` is its contract file. A subgraph also publishes its own GraphQL schema beside it, which the SDK never writes: see The `generate` command.
8
8
 
9
9
  ## Installation
10
10
 
@@ -20,7 +20,7 @@ With decorators, your app imports them at runtime, so install them as a regular
20
20
  npm install @bidirekt/typescript-sdk
21
21
  ```
22
22
 
23
- Their types need TypeScript 5.0 or later.
23
+ Their types need TypeScript 5.0 or later. GraphQL contracts need the Bidirekt CLI and broker 0.4.0 or later.
24
24
 
25
25
  ## Quickstart
26
26
 
@@ -102,7 +102,7 @@ export class Rating {
102
102
  }
103
103
  ```
104
104
 
105
- `@BidirektProvider` on a method declares a resource it provides (NestJS here). A body is a schema class, or `null` for no body:
105
+ `@BidirektRestProvider` on a method declares a resource it provides (NestJS here). A body is a schema class, or `null` for no body:
106
106
 
107
107
  ```ts
108
108
  // pets.controller.ts
@@ -115,7 +115,7 @@ import {
115
115
  Param,
116
116
  Post,
117
117
  } from '@nestjs/common'
118
- import { BidirektProvider } from '@bidirekt/typescript-sdk'
118
+ import { BidirektRestProvider } from '@bidirekt/typescript-sdk'
119
119
  import { NewPet, Pet } from './pet.js'
120
120
 
121
121
  @Controller('pets')
@@ -123,7 +123,7 @@ export class PetsController {
123
123
  private readonly pets = new Map<number, Pet>()
124
124
 
125
125
  @Get(':petId')
126
- @BidirektProvider({
126
+ @BidirektRestProvider({
127
127
  method: 'GET',
128
128
  path: '/pets/*',
129
129
  responses: { 200: Pet, 404: null },
@@ -137,7 +137,7 @@ export class PetsController {
137
137
  }
138
138
 
139
139
  @Post()
140
- @BidirektProvider({
140
+ @BidirektRestProvider({
141
141
  method: 'POST',
142
142
  path: '/pets',
143
143
  request: NewPet,
@@ -154,15 +154,15 @@ export class PetsController {
154
154
  }
155
155
  ```
156
156
 
157
- `@BidirektConsumer` declares a resource it consumes, and names the provider:
157
+ `@BidirektRestConsumer` declares a resource it consumes, and names the provider:
158
158
 
159
159
  ```ts
160
160
  // ratings.client.ts
161
- import { BidirektConsumer } from '@bidirekt/typescript-sdk'
161
+ import { BidirektRestConsumer } from '@bidirekt/typescript-sdk'
162
162
  import { Rating } from './pet.js'
163
163
 
164
164
  export class RatingsClient {
165
- @BidirektConsumer({
165
+ @BidirektRestConsumer({
166
166
  provider: 'petstore_reviews',
167
167
  method: 'GET',
168
168
  path: '/ratings/*',
@@ -177,7 +177,7 @@ export class RatingsClient {
177
177
 
178
178
  ### With tags
179
179
 
180
- `@bidirekt schema` above an `interface`, an object `type` or a class marks a schema, and `@bidirekt field` each field; `field` takes the same options as the decorator, as `key=value`. `@bidirekt provides <METHOD> <path>` or `@bidirekt consumes <provider> <METHOD> <path>` above a handler declares its resource, then `@bidirekt request [schema]` and one `@bidirekt response <status> [schema]` per status, where nothing after the status means no body:
180
+ `@bidirekt schema` above an `interface`, an object `type` or a class marks a schema, and `@bidirekt field` each field; `field` takes the same options as the decorator, as `key=value`. `@bidirekt rest provides <METHOD> <path>` or `@bidirekt rest consumes <provider> <METHOD> <path>` above a handler declares its resource, then `@bidirekt request [schema]` and one `@bidirekt response <status> [schema]` per status, where nothing after the status means no body:
181
181
 
182
182
  ```ts
183
183
  // pet.ts
@@ -259,7 +259,7 @@ const pets = new Map<string, Pet>()
259
259
  export const router = express.Router()
260
260
 
261
261
  /**
262
- * @bidirekt provides GET /pets/*
262
+ * @bidirekt rest provides GET /pets/*
263
263
  * @bidirekt response 200 Pet
264
264
  * @bidirekt response 404
265
265
  */
@@ -273,7 +273,7 @@ router.get('/pets/:petId', (req, res) => {
273
273
  })
274
274
 
275
275
  /**
276
- * @bidirekt provides POST /pets
276
+ * @bidirekt rest provides POST /pets
277
277
  * @bidirekt request NewPet
278
278
  * @bidirekt response 201 Pet
279
279
  * @bidirekt response 400
@@ -293,7 +293,7 @@ router.post('/pets', (req, res) => {
293
293
  import type { Rating } from './pet.ts'
294
294
 
295
295
  /**
296
- * @bidirekt consumes petstore_reviews GET /ratings/*
296
+ * @bidirekt rest consumes petstore_reviews GET /ratings/*
297
297
  * @bidirekt response 200 Rating
298
298
  * @bidirekt response 404
299
299
  */
@@ -412,7 +412,7 @@ import express from 'express'
412
412
  export const router = express.Router()
413
413
 
414
414
  /**
415
- * @bidirekt provides GET /health
415
+ * @bidirekt rest provides GET /health
416
416
  * @bidirekt response 200 Health
417
417
  *
418
418
  * @bidirekt schema Health
@@ -513,10 +513,11 @@ npx @bidirekt/typescript-sdk-cli generate --check
513
513
 
514
514
  Each error is printed as `file:line message`; on an error nothing is written and the exit code is 1. A warning is printed as `file:line warning: message` and doesn't change the exit code.
515
515
 
516
- `contracts/generated.yaml` is the service's only contract, and you never edit it by hand: the next `generate` writes over it. Regenerate it whenever an annotation or an annotated type changes, commit it with the code, and ship it like any contract file:
516
+ You never edit `contracts/generated.yaml` by hand: the next `generate` writes over it. Regenerate it whenever an annotation or an annotated type changes, commit it with the code, and ship it like any contract file:
517
517
 
518
518
  ```sh
519
519
  npx @bidirekt/typescript-sdk-cli generate
520
+ bidirekt validate contracts/generated.yaml
520
521
  bidirekt validate contracts/generated.yaml --participant petstore_ts --environment production
521
522
  bidirekt publish contracts/generated.yaml --participant petstore_ts --version 1.4.0
522
523
  bidirekt can-i-deploy petstore_ts --version 1.4.0 --environment production
@@ -524,7 +525,9 @@ bidirekt can-i-deploy petstore_ts --version 1.4.0 --environment production
524
525
  bidirekt record-deployment petstore_ts --version 1.4.0 --environment production
525
526
  ```
526
527
 
527
- When `can-i-deploy` reports a break, fix the annotation or the type in the code and generate again.
528
+ `validate` without `--participant` and `--environment` checks only the file; with them, it also compares the file with what is deployed in that environment. When `can-i-deploy` reports a break, fix the annotation or the type in the code and generate again.
529
+
530
+ A subgraph, a service that declares its graph with `@BidirektGraph` or `@bidirekt graph`, validates and publishes its own GraphQL schema together with the contract: `bidirekt validate contracts/generated.yaml src/schema.graphql`, and the same two files in `publish`. `contracts/generated.yaml` alone fails with `graph "petstore_graph" without a GraphQL schema`.
528
531
 
529
532
  A package of your workspace, which npm links into `node_modules`, is read as your code when its `types` or `exports` point at its source. A class, interface or type reached through its built `.d.ts` stops `generate`.
530
533
 
@@ -532,12 +535,15 @@ A package of your workspace, which npm links into `node_modules`, is read as you
532
535
 
533
536
  ### Decorators
534
537
 
535
- | Decorator | Goes on | Options |
536
- | ---------------------------- | ---------- | -------------------------------------------------------------------------- |
537
- | `@BidirektSchema(options?)` | a class | `name` |
538
- | `@BidirektField(options?)` | a property | `type`, `name`, `optional`, `nullable`, `description`, `union`, see Fields |
539
- | `@BidirektProvider(options)` | a method | `method`, `path`, `request`, `responses` |
540
- | `@BidirektConsumer(options)` | a method | `provider`, `method`, `path`, `request`, `responses` |
538
+ | Decorator | Goes on | Options |
539
+ | ----------------------------------- | ---------- | ------------------------------------------------------------------------------ |
540
+ | `@BidirektSchema(options?)` | a class | `name`, `union` |
541
+ | `@BidirektField(options?)` | a property | `type`, `name`, `optional`, `nullable`, `description`, `union`, see Fields |
542
+ | `@BidirektRestProvider(options)` | a method | `method`, `path`, `request`, `responses` |
543
+ | `@BidirektRestConsumer(options)` | a method | `provider`, `method`, `path`, `request`, `responses` |
544
+ | `@BidirektGraphqlConsumer(options)` | a method | `provider`, `query` or `mutation`, `arguments`, `returns`, see GraphQL returns |
545
+ | `@BidirektGraphqlField(options?)` | a property | the options of `@BidirektField`, `scalar`, `arguments`, see Fields |
546
+ | `@BidirektGraph(name)` | a class | none: `name` is the graph the service is a subgraph of |
541
547
 
542
548
  `generate` recognizes a decorator by where it is imported from, `@bidirekt/typescript-sdk`, also through an alias, `import * as` or a re-export in your own code, never by its name. Options are written in place, as literals and classes, never through a variable. A decorator built at runtime (returned by a wrapper function, applied in a loop) is not read, and `generate` warns. A decorator on a `static` property is not read either, and `generate` warns.
543
549
 
@@ -545,14 +551,18 @@ With `emitDecoratorMetadata` on (NestJS, TypeORM), TypeScript keeps the imports
545
551
 
546
552
  ### Tags
547
553
 
548
- | Tag | Goes above |
549
- | ----------------------------------------------- | ------------------------------------------------------------------------------ |
550
- | `@bidirekt schema [name=<Name>]` | a class, an `interface`, an object `type` or a string `enum` |
551
- | `@bidirekt field [key=value ...]` | a property of a schema |
552
- | `@bidirekt provides <METHOD> <path>` | a function, an exported arrow function, a method or a statement (`router.get`) |
553
- | `@bidirekt consumes <provider> <METHOD> <path>` | the same |
554
- | `@bidirekt request [body]` | follows `provides` or `consumes` |
555
- | `@bidirekt response <status> [body]` | follows `provides` or `consumes`, once per status |
554
+ | Tag | Goes above |
555
+ | -------------------------------------------------------------- | ------------------------------------------------------------------------------ |
556
+ | `@bidirekt schema [name=<Name>] [union={...}]` | a class, an `interface`, an object `type` or a string `enum` |
557
+ | `@bidirekt field [key=value ...]` | a property of a schema |
558
+ | `@bidirekt rest provides <METHOD> <path>` | a function, an exported arrow function, a method or a statement (`router.get`) |
559
+ | `@bidirekt rest consumes <provider> <METHOD> <path>` | the same |
560
+ | `@bidirekt request [body]` | follows `rest provides` or `rest consumes` |
561
+ | `@bidirekt response <status> [body]` | follows `rest provides` or `rest consumes`, once per status |
562
+ | `@bidirekt graphql consumes <provider> query\|mutation <name>` | the same as `rest provides` |
563
+ | `@bidirekt arguments <schema>`, `@bidirekt returns <type>` | follow `graphql consumes`, see GraphQL returns |
564
+ | `@bidirekt graphql field [key=value ...]` | a property of a schema, in place of `field`, see Fields |
565
+ | `@bidirekt graph <name>` | a class or any other element: `name` is the graph the service is a subgraph of |
556
566
 
557
567
  - A handler's comment can also declare schemas, see [Schemas in a handler's comment](#schemas-in-a-handlers-comment).
558
568
  - A tag starts a line of a `/** */` comment, and its arguments are separated by spaces. Only a `description` value is quoted (`description="Shown on the card"`), and inside the quotes it holds only ASCII letters and digits, with single spaces between words. Only a `union=` value is grouped in `{...}`, with optional spaces inside; quotes or braces anywhere else stop `generate`.
@@ -574,6 +584,26 @@ A handler declares one resource: its method, in uppercase (`GET`, `POST`, `PUT`,
574
584
 
575
585
  Without a request (no `request` option, no `@bidirekt request` tag), the resource has no `request` key. A list is written once however many handlers use it. The same method and path provided by two handlers stops `generate`. The same resource consumed by several handlers, with decorators, tags or both, is written once with the statuses of all of them; they declare the same request, and the same schema for a status they share.
576
586
 
587
+ ### GraphQL returns
588
+
589
+ `@BidirektGraphqlConsumer({ provider, query, arguments, returns })` on a method declares a GraphQL query the service calls, and `mutation` in place of `query` a mutation; with tags, `@bidirekt graphql consumes <provider> query|mutation <name>` above a handler, with `@bidirekt arguments <schema>` and `@bidirekt returns <type>`. `provider` names the service that answers the call, or a federated graph, and then the call is checked against the graph its subgraphs compose. `arguments` is a schema, and `returns` the shape the call reads:
590
+
591
+ | Returns | Decorator | Tag | Contract |
592
+ | ----------------------- | ------------------------------------------------------------- | ------------------------------------------------ | --------------- |
593
+ | a schema | `Pet` | `Pet` | `Pet` |
594
+ | a schema or null | `{ nullable: Pet }` | `Pet?` | `PetOrNull` |
595
+ | a list | `[Pet]` or `{ list: Pet }` | `Pet[]` | `PetList` |
596
+ | a list or null | `{ list: Pet, nullable: true }` | `Pet[]?` | `PetListOrNull` |
597
+ | a list of items or null | `{ list: Pet, nullableItems: true }` | `Pet?[]` | `PetOrNullList` |
598
+ | a primitive | `'boolean'` | `boolean` | `Boolean` |
599
+ | a custom scalar | `{ scalar: 'DateTime' }` | `scalar:DateTime` | `DateTime` |
600
+ | an enum | `{ enum: ['AVAILABLE', 'SOLD'], name: 'Status' }` | `enum:AVAILABLE\|SOLD as Status` | `Status` |
601
+ | a union | `{ union: { Pet: Pet, Owner: Owner }, name: 'SearchResult' }` | `union={Pet: Pet, Owner: Owner} as SearchResult` | `SearchResult` |
602
+
603
+ A primitive, a scalar, an enum or a union also takes the place of the schema in a nullable or a list (`{ nullable: 'integer' }`, `'string[]'`, `scalar:DateTime?[]`). Each key of a union is the name of one of its types in the provider's GraphQL schema, and its value the schema the call reads from that type. Each form but a schema returned as it is becomes a schema of the contract, with the name above, and `name` in the decorator or `as <name>` in the tag gives it another one (`{ nullable: Pet, name: 'MaybePet' }`, `Pet? as MaybePet`). They name only a schema `generate` creates: a schema returned as it is is not copied, the call references it by its own name, so `@bidirekt returns Pet as MyPet` stops `generate`. To call it `MyPet`, name the schema itself, with `@BidirektSchema({ name })` or `@bidirekt schema name=<Name>`. A primitive returned as it is takes another name only in the tag (`boolean as Flag`): in the decorator it is a bare string, `'boolean'`, always written as `Boolean`. An enum or a union in a nullable or a list is a schema of its own, under the name it declares, and the nullable or the list references it under the name above: `{ nullable: { enum: ['AVAILABLE', 'SOLD'], name: 'Status' } }` and `enum:AVAILABLE|SOLD? as Status` both write `Status` and `StatusOrNull: {ref: Status, nullable: true}`. In the tag, that `as` names the enum or the union, never the nullable or the list around it. A scalar in a nullable or a list takes no name of its own: the name goes on the nullable or the list, and in the tag `as` names them.
604
+
605
+ A call that reads a GraphQL interface both on the interface and on the types that implement it, as `node(id: $id) { id ... on User { name } ... on Pet { species } }`, returns a schema with a `union`: its fields are the ones read on the interface, and `union` maps each type read with `... on` to the schema the call reads from it. `@BidirektSchema({ union: { User: UserName, Pet: PetSpecies } })` on a class `Node` with `@BidirektField() id`, or `@bidirekt schema union={User: UserName, Pet: PetSpecies}` above `interface Node` with a `@bidirekt field` on `id`, writes `Node` as `type: union`, with `id` in its `properties` and `User` and `Pet` in its `members`. A member's schema holds only the fields read on its own type: a member class that extends `Node` would repeat `id`. A schema with a `union` and no field writes only the `members`, a named union like `{ union: {...}, name }`. `union=` goes above a class, an interface or an object type, never above an enum.
606
+
577
607
  ### Fields
578
608
 
579
609
  | Decorator | Tag | What it declares |
@@ -587,6 +617,8 @@ Without a request (no `request` option, no `@bidirekt request` tag), the resourc
587
617
 
588
618
  A `union` names each schema of the field's union once, by one key, and nothing else; a tag names each member by its name in the contract, never a list or a map. It applies to the union of the field, of its items or of its values (`Array<Card | Pix>`), and `null` and `undefined` in the type still make them `nullable` or `optional`.
589
619
 
620
+ In a GraphQL contract, `@BidirektGraphqlField` takes the place of `@BidirektField` on a field that needs GraphQL's own options, and `@bidirekt graphql field` that of `@bidirekt field`. They take the options above, plus `scalar: 'DateTime'`, a custom scalar that replaces the field's type and is written as `type: scalar, name: DateTime`, and `arguments: ReviewsArgs`, the schema of the arguments the call passes to the field, as `first` in `reviews(first: 10)`. In a tag, `scalar=DateTime` and `arguments=ReviewsArgs`. A field takes one of the two, never both.
621
+
590
622
  ### Types
591
623
 
592
624
  A field's type comes from TypeScript, or from the JSDoc `@type` in JavaScript:
@@ -614,7 +646,7 @@ A declared `type` is the whole type of the field, whatever TypeScript says: a pr
614
646
 
615
647
  - A schema is named after its class, interface or object type; `name` gives it another name in the contract. An anonymous class (`export default class`) needs a `name`.
616
648
  - Every schema is written, even one no handler references. Two schemas with the same name in the contract stop `generate`; give one of them a `name`.
617
- - A schema without a field stops `generate`, and so does `@bidirekt schema` above an object type that is only an index signature: that is a map, used as a field's type.
649
+ - A schema without a field or a `union` stops `generate`, and so does `@bidirekt schema` above an object type that is only an index signature: that is a map, used as a field's type.
618
650
  - A string enum used by a field is written as a schema named after it. `@bidirekt schema` above the enum gives it another name with `name=`, and writes it even when no field uses it, so tags can reference it (`@bidirekt response 200 PetStatus`). An enum without string members can't be a schema, and `generate` warns.
619
651
  - A schema class takes the annotated fields of its parent classes, whether or not they are schemas; a schema interface takes those of the interfaces it extends, and of all its blocks. A parent `generate` can't read, like a mixin or a utility type (`Omit<Pet, 'secret'>`), stops it: declare the fields in the schema.
620
652
 
@@ -642,7 +674,7 @@ The contract describes what the code does, not the type the code declares. The T
642
674
  - `schema name "Pet" is declared more than once: give each schema a distinct name`
643
675
  - `method "get" must be uppercase: write "GET"`
644
676
  - `response status "0201" must be written as 201`, also for a decorator status written as `'0201'`.
645
- - `@BidirektProvider and "@bidirekt provides GET /pets/*" are both on this handler: keep one`; a decorator and a tag on the same schema or field stop it too.
677
+ - `@BidirektRestProvider and "@bidirekt rest provides GET /pets/*" are both on this handler: keep one`; a decorator and a tag on the same schema or field stop it too.
646
678
 
647
679
  ## Docs
648
680
 
package/dist/command.js CHANGED
@@ -1,17 +1,21 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join, resolve } from 'node:path';
3
3
  import { parseArgs } from 'node:util';
4
+ import { compareLocations } from "./model/contract.js";
5
+ import { contractToProtocolBlocks } from "./model/declarations-to-contract.js";
6
+ import { defaultProtocols } from "./protocols.js";
4
7
  import { pathToShown } from "./reader/location.js";
5
8
  import { projectToContract } from "./reader/project-to-contract.js";
6
9
  import { contractToYaml } from "./writer/contract-to-yaml.js";
7
10
  const usage = 'Usage: typescript-sdk generate [--check] [--project <tsconfig>] [--out <file>]\n';
8
11
  const defaultOutput = join('contracts', 'generated.yaml');
9
- export function runCommand(args, cwd) {
12
+ const noLocation = { file: '', line: 0 };
13
+ export function runCommand(args, cwd, protocols = defaultProtocols) {
10
14
  const options = argsToGenerateOptions(args);
11
15
  if (options === undefined) {
12
16
  return { exitCode: 1, stderr: usage };
13
17
  }
14
- return generate(options, cwd);
18
+ return generate(options, cwd, protocols);
15
19
  }
16
20
  function argsToGenerateOptions(args) {
17
21
  try {
@@ -33,14 +37,14 @@ function argsToGenerateOptions(args) {
33
37
  return undefined;
34
38
  }
35
39
  }
36
- function generate(options, cwd) {
40
+ function generate(options, cwd, protocols) {
37
41
  const located = locateProject(options, cwd);
38
42
  if ('message' in located) {
39
43
  return { exitCode: 1, stderr: `${located.message}\n` };
40
44
  }
41
45
  const { project, source, directory } = located;
42
46
  const output = resolve(cwd, options.out ?? join(directory, defaultOutput));
43
- const read = projectToContract(project, cwd);
47
+ const read = projectToContract(project, cwd, protocols);
44
48
  const diagnostics = [
45
49
  ...read.errors.map((error) => ({ ...error, prefix: '' })),
46
50
  ...read.warnings.map((warning) => ({ ...warning, prefix: 'warning: ' })),
@@ -51,10 +55,10 @@ function generate(options, cwd) {
51
55
  if (read.errors.length > 0) {
52
56
  return failure(diagnostics);
53
57
  }
54
- if (isEmpty(read.contract)) {
58
+ if (isEmpty(read.contract, protocols)) {
55
59
  return failure(`${diagnostics}no @bidirekt/typescript-sdk annotation found in "${source}": nothing to generate\n`);
56
60
  }
57
- const yaml = contractToYaml(read.contract);
61
+ const yaml = contractToYaml(read.contract, protocols);
58
62
  const shownOutput = pathToShown(output, cwd);
59
63
  if (options.check) {
60
64
  if (!existsSync(output)) {
@@ -104,8 +108,9 @@ function configFileToLocatedProject(configFile, cwd) {
104
108
  directory: dirname(configFile),
105
109
  };
106
110
  }
107
- function isEmpty({ provides, consumes, schemas }) {
108
- return provides.length + consumes.length + schemas.length === 0;
111
+ function isEmpty(contract, protocols) {
112
+ return (contract.schemas.length === 0 &&
113
+ contractToProtocolBlocks(contract, protocols).every(({ protocol, block }) => protocol.isEmpty(block)));
109
114
  }
110
115
  function failure(stderr) {
111
116
  return { exitCode: 1, stderr };
@@ -117,11 +122,7 @@ function errorToReason(error) {
117
122
  return String(error);
118
123
  }
119
124
  function compareDiagnostics(a, b) {
120
- const fileOrder = Buffer.compare(Buffer.from(a.location?.file ?? ''), Buffer.from(b.location?.file ?? ''));
121
- if (fileOrder !== 0) {
122
- return fileOrder;
123
- }
124
- return (a.location?.line ?? 0) - (b.location?.line ?? 0);
125
+ return compareLocations(a.location ?? noLocation, b.location ?? noLocation);
125
126
  }
126
127
  function diagnosticToLine({ location, prefix, message }, cwd) {
127
128
  if (location === undefined) {
@@ -1 +1,7 @@
1
- export {};
1
+ export function compareLocations(a, b) {
2
+ const fileOrder = Buffer.compare(Buffer.from(a.file), Buffer.from(b.file));
3
+ if (fileOrder !== 0) {
4
+ return fileOrder;
5
+ }
6
+ return a.line - b.line;
7
+ }
@@ -1,32 +1,50 @@
1
1
  import { isDeepStrictEqual } from 'node:util';
2
- import { consumedToMerged, providedToMerged } from "./resources-to-merged.js";
3
- export function declarationsToContract(declarations) {
2
+ export function declarationsToContract(declarations, protocols) {
4
3
  const { schemas, errors } = declarationsToSchemas(declarations.schemas);
5
- const provides = providedToMerged(declarations.provides);
6
- const consumes = consumedToMerged(declarations.consumes);
7
4
  const contract = {
8
- provides: provides.resources,
9
- consumes: consumes.resources,
5
+ provides: new Map(),
6
+ consumes: new Map(),
10
7
  schemas,
11
8
  };
9
+ const mergeErrors = [];
10
+ for (const protocol of protocols) {
11
+ const sides = Map.groupBy(declarations.blocks.get(protocol.name) ?? [], ({ provider }) => provider);
12
+ for (const [provider, sideBlocks] of sides) {
13
+ const merged = protocol.merge(sideBlocks);
14
+ mergeErrors.push(...merged.errors);
15
+ sideToBlocks(contract, provider).set(protocol.name, merged.block);
16
+ }
17
+ }
12
18
  const declared = new Set(declarations.schemas.map((schema) => schema.name));
13
19
  return {
14
20
  contract,
15
21
  errors: [
16
22
  ...errors,
17
23
  ...declarations.schemas.flatMap(schemaToDuplicateFields),
18
- ...provides.errors,
19
- ...consumes.errors,
20
- ...contractToMissingReferences(contract, declared),
24
+ ...mergeErrors,
25
+ ...contractToMissingReferences(contract, protocols, declared),
21
26
  ],
22
27
  };
23
28
  }
29
+ export function contractToProtocolBlocks(contract, protocols) {
30
+ return [contract.provides, ...contract.consumes.values()].flatMap((blocks) => protocols
31
+ .filter((protocol) => blocks.has(protocol.name))
32
+ .map((protocol) => ({ protocol, block: blocks.get(protocol.name) })));
33
+ }
34
+ function sideToBlocks(contract, provider) {
35
+ if (provider === undefined) {
36
+ return contract.provides;
37
+ }
38
+ const blocks = contract.consumes.get(provider) ?? new Map();
39
+ contract.consumes.set(provider, blocks);
40
+ return blocks;
41
+ }
24
42
  function declarationsToSchemas(declarations) {
25
43
  const schemas = [];
26
44
  const errors = [];
27
45
  for (const [name, group] of Map.groupBy(declarations, (declaration) => declaration.name)) {
28
46
  const [first] = group;
29
- if (group.every((declaration) => isSameList(declaration.node, first.node))) {
47
+ if (group.every((declaration) => isSameSchema(declaration, first))) {
30
48
  schemas.push(first);
31
49
  continue;
32
50
  }
@@ -38,22 +56,44 @@ function declarationsToSchemas(declarations) {
38
56
  return { schemas, errors };
39
57
  }
40
58
  function schemaToDuplicateFields(schema) {
41
- if (schema.node.type !== 'object') {
42
- return [];
43
- }
44
- const names = schema.node.properties.map(({ name }) => name);
45
- return schema.node.properties
59
+ const properties = nodeToProperties(schema.node);
60
+ const names = properties.map(({ name }) => name);
61
+ return properties
46
62
  .filter(({ name }) => names.indexOf(name) !== names.lastIndexOf(name))
47
63
  .map(({ name, location }) => ({
48
64
  message: `field "${name}" is declared more than once in schema "${schema.name}": give each field a distinct name`,
49
65
  location,
50
66
  }));
51
67
  }
52
- function isSameList(node, first) {
53
- if (node === first) {
68
+ function nodeToProperties(node) {
69
+ switch (node.type) {
70
+ case 'object':
71
+ return node.properties;
72
+ case 'union':
73
+ return node.properties ?? [];
74
+ }
75
+ return [];
76
+ }
77
+ function isSameSchema(schema, first) {
78
+ if (schema.node === first.node) {
54
79
  return true;
55
80
  }
56
- return node.type === 'array' && isDeepStrictEqual(node, first);
81
+ if (schema.derived === true && first.derived === true) {
82
+ return isDeepStrictEqual(withSortedMembers(schema.node), withSortedMembers(first.node));
83
+ }
84
+ return (schema.node.type === 'array' && isDeepStrictEqual(schema.node, first.node));
85
+ }
86
+ function withSortedMembers(node) {
87
+ switch (node.type) {
88
+ case 'enum':
89
+ return { ...node, members: node.members.toSorted() };
90
+ case 'union':
91
+ return {
92
+ ...node,
93
+ members: node.members.toSorted((a, b) => Buffer.compare(Buffer.from(a.key), Buffer.from(b.key))),
94
+ };
95
+ }
96
+ return node;
57
97
  }
58
98
  function collisionToMessage(name, group) {
59
99
  const lists = group.filter(({ node }) => node.type === 'array');
@@ -65,38 +105,58 @@ function collisionToMessage(name, group) {
65
105
  }
66
106
  return `list name "${name}" is also the name of another schema: give the list a distinct name`;
67
107
  }
68
- function contractToMissingReferences(contract, declared) {
69
- const bodies = [...contract.provides, ...contract.consumes]
70
- .flatMap((resource) => [resource.request, ...resource.responses])
71
- .filter((body) => body !== undefined);
108
+ function contractToMissingReferences(contract, protocols, declared) {
72
109
  const references = [
73
- ...bodies.flatMap(({ schema, location }) => {
74
- if (schema === null) {
75
- return [];
76
- }
77
- return [{ schema, location }];
78
- }),
79
- ...contract.schemas.flatMap((schema) => nodeToReferences(schema.node, schema.location)),
110
+ ...contractToProtocolBlocks(contract, protocols).flatMap(({ protocol, block }) => protocol.references(block).map((reference) => ({
111
+ ...reference,
112
+ vocabulary: protocol.vocabulary,
113
+ }))),
114
+ ...contract.schemas.flatMap((schema) => nodeToReferences(schema.node, schema.location, schema.vocabulary)),
80
115
  ];
81
116
  return references
82
117
  .filter(({ schema }) => !declared.has(schema))
83
- .map(({ schema, location }) => ({
84
- message: `schema "${schema}" is not declared: reference a schema by its name in the contract`,
118
+ .map(({ schema, location, vocabulary }) => ({
119
+ message: missingSchemaToMessage(schema, vocabulary),
85
120
  location,
86
121
  }));
87
122
  }
88
- function nodeToReferences(node, location) {
123
+ function missingSchemaToMessage(schema, vocabulary) {
124
+ const primitive = vocabulary?.primitiveNames?.get(schema);
125
+ if (vocabulary === undefined || primitive === undefined) {
126
+ return `schema "${schema}" is not declared: reference a schema by its name in the contract`;
127
+ }
128
+ return `${schema} is ${vocabulary.label}'s name: write ${primitive}`;
129
+ }
130
+ function nodeToReferences(node, location, vocabulary) {
131
+ return [
132
+ ...extraToReferences(node, location, vocabulary),
133
+ ...typeToReferences(node, location, vocabulary),
134
+ ];
135
+ }
136
+ function extraToReferences(node, location, vocabulary) {
137
+ if (node.extra === undefined || vocabulary === undefined) {
138
+ return [];
139
+ }
140
+ return vocabulary.references(node).map((schema) => ({ schema, location }));
141
+ }
142
+ function typeToReferences(node, location, vocabulary) {
89
143
  switch (node.type) {
90
144
  case 'ref':
91
- return [{ schema: node.schema, location }];
145
+ return [{ schema: node.schema, location, vocabulary }];
92
146
  case 'object':
93
- return node.properties.flatMap((property) => nodeToReferences(property.node, property.location));
147
+ return propertiesToReferences(node.properties);
94
148
  case 'array':
95
- return nodeToReferences(node.items, location);
149
+ return nodeToReferences(node.items, location, vocabulary);
96
150
  case 'map':
97
- return nodeToReferences(node.values, location);
151
+ return nodeToReferences(node.values, location, vocabulary);
98
152
  case 'union':
99
- return node.members.flatMap((member) => nodeToReferences(member.node, location));
153
+ return [
154
+ ...propertiesToReferences(node.properties ?? []),
155
+ ...node.members.flatMap((member) => nodeToReferences(member.node, location, vocabulary)),
156
+ ];
100
157
  }
101
158
  return [];
102
159
  }
160
+ function propertiesToReferences(properties) {
161
+ return properties.flatMap((property) => nodeToReferences(property.node, property.location, property.vocabulary));
162
+ }
@@ -0,0 +1,8 @@
1
+ export function blockToReferences(block) {
2
+ return block.operations.flatMap((operation) => [operation.arguments, operation.returns].flatMap((use) => {
3
+ if (use === undefined) {
4
+ return [];
5
+ }
6
+ return [{ schema: use.schema, location: use.location }];
7
+ }));
8
+ }
@@ -0,0 +1,77 @@
1
+ import { compareLocations } from "../../contract.js";
2
+ export function sideBlocksToMerged(sideBlocks) {
3
+ const [{ provider }] = sideBlocks;
4
+ const errors = new Map();
5
+ const addConflict = ({ message, first, other }) => {
6
+ for (const location of [first, other]) {
7
+ errors.set(`${location.file}:${location.line} ${message}`, {
8
+ message,
9
+ location,
10
+ });
11
+ }
12
+ };
13
+ const blocks = sideBlocks.map(({ block }) => block);
14
+ const block = { operations: [] };
15
+ if (provider === undefined) {
16
+ block.graph = graphsToMerged(blocks.flatMap(({ graph }) => graph ?? []), addConflict);
17
+ }
18
+ else {
19
+ block.operations = operationsToMerged(blocks.flatMap(({ operations }) => operations), provider, addConflict);
20
+ }
21
+ return { block, errors: [...errors.values()] };
22
+ }
23
+ function graphsToMerged(graphs, addConflict) {
24
+ const [first, ...others] = [...graphs].sort((a, b) => compareLocations(a.location, b.location));
25
+ for (const other of others) {
26
+ if (other.name !== first.name) {
27
+ addConflict({
28
+ message: `the graph is declared as "${first.name}" and "${other.name}": declare one graph name in every @BidirektGraph`,
29
+ first: first.location,
30
+ other: other.location,
31
+ });
32
+ }
33
+ }
34
+ return first;
35
+ }
36
+ function operationsToMerged(operations, provider, addConflict) {
37
+ const merged = [];
38
+ for (const group of Map.groupBy(operations, operationToKey).values()) {
39
+ const [first, ...others] = group;
40
+ const operation = `${first.kind} ${first.name} consumed from "${provider}"`;
41
+ for (const other of others) {
42
+ const conflicts = [
43
+ usesToConflict('arguments', first, other, operation),
44
+ usesToConflict('returns', first, other, operation),
45
+ ];
46
+ for (const conflict of conflicts) {
47
+ if (conflict !== undefined) {
48
+ addConflict(conflict);
49
+ }
50
+ }
51
+ }
52
+ merged.push(first);
53
+ }
54
+ return merged;
55
+ }
56
+ function usesToConflict(use, first, other, operation) {
57
+ const firstUse = first[use];
58
+ const otherUse = other[use];
59
+ if (firstUse?.schema === otherUse?.schema) {
60
+ return undefined;
61
+ }
62
+ if (firstUse === undefined || otherUse === undefined) {
63
+ return {
64
+ message: `${use} of ${operation} is declared in one handler and not in another: declare the same ${use} in every handler`,
65
+ first: firstUse?.location ?? first.location,
66
+ other: otherUse?.location ?? other.location,
67
+ };
68
+ }
69
+ return {
70
+ message: `${use} of ${operation} is declared as ${firstUse.schema} and ${otherUse.schema}: declare the same ${use} in every handler`,
71
+ first: firstUse.location,
72
+ other: otherUse.location,
73
+ };
74
+ }
75
+ function operationToKey(operation) {
76
+ return JSON.stringify([operation.kind, operation.name]);
77
+ }
@@ -0,0 +1 @@
1
+ export {};