@bidirekt/typescript-sdk-cli 0.2.0 → 0.4.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 +77 -37
  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 +412 -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, and `__typename` the broker 0.5.0. `bidirekt validate` and `bidirekt publish` without file arguments need the CLI 0.5.0.
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,
@@ -147,22 +147,25 @@ export class PetsController {
147
147
  if (typeof body.name !== 'string') {
148
148
  throw new BadRequestException()
149
149
  }
150
- const pet = Object.assign(new Pet(), { petId: this.pets.size + 1, ...body })
150
+ const pet = Object.assign(new Pet(), {
151
+ petId: this.pets.size + 1,
152
+ ...body,
153
+ })
151
154
  this.pets.set(pet.petId, pet)
152
155
  return pet
153
156
  }
154
157
  }
155
158
  ```
156
159
 
157
- `@BidirektConsumer` declares a resource it consumes, and names the provider:
160
+ `@BidirektRestConsumer` declares a resource it consumes, and names the provider:
158
161
 
159
162
  ```ts
160
163
  // ratings.client.ts
161
- import { BidirektConsumer } from '@bidirekt/typescript-sdk'
164
+ import { BidirektRestConsumer } from '@bidirekt/typescript-sdk'
162
165
  import { Rating } from './pet.js'
163
166
 
164
167
  export class RatingsClient {
165
- @BidirektConsumer({
168
+ @BidirektRestConsumer({
166
169
  provider: 'petstore_reviews',
167
170
  method: 'GET',
168
171
  path: '/ratings/*',
@@ -170,14 +173,15 @@ export class RatingsClient {
170
173
  })
171
174
  async find(petId: number): Promise<Rating | null> {
172
175
  const response = await fetch(`http://petstore-reviews/ratings/${petId}`)
173
- return response.status === 404 ? null : ((await response.json()) as Rating)
176
+ if (response.status === 404) return null
177
+ return (await response.json()) as Rating
174
178
  }
175
179
  }
176
180
  ```
177
181
 
178
182
  ### With tags
179
183
 
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:
184
+ `@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
185
 
182
186
  ```ts
183
187
  // pet.ts
@@ -259,7 +263,7 @@ const pets = new Map<string, Pet>()
259
263
  export const router = express.Router()
260
264
 
261
265
  /**
262
- * @bidirekt provides GET /pets/*
266
+ * @bidirekt rest provides GET /pets/*
263
267
  * @bidirekt response 200 Pet
264
268
  * @bidirekt response 404
265
269
  */
@@ -273,7 +277,7 @@ router.get('/pets/:petId', (req, res) => {
273
277
  })
274
278
 
275
279
  /**
276
- * @bidirekt provides POST /pets
280
+ * @bidirekt rest provides POST /pets
277
281
  * @bidirekt request NewPet
278
282
  * @bidirekt response 201 Pet
279
283
  * @bidirekt response 400
@@ -293,13 +297,14 @@ router.post('/pets', (req, res) => {
293
297
  import type { Rating } from './pet.ts'
294
298
 
295
299
  /**
296
- * @bidirekt consumes petstore_reviews GET /ratings/*
300
+ * @bidirekt rest consumes petstore_reviews GET /ratings/*
297
301
  * @bidirekt response 200 Rating
298
302
  * @bidirekt response 404
299
303
  */
300
304
  export async function findRating(petId: number): Promise<Rating | null> {
301
305
  const response = await fetch(`http://petstore-reviews/ratings/${petId}`)
302
- return response.status === 404 ? null : ((await response.json()) as Rating)
306
+ if (response.status === 404) return null
307
+ return (await response.json()) as Rating
303
308
  }
304
309
  ```
305
310
 
@@ -412,7 +417,7 @@ import express from 'express'
412
417
  export const router = express.Router()
413
418
 
414
419
  /**
415
- * @bidirekt provides GET /health
420
+ * @bidirekt rest provides GET /health
416
421
  * @bidirekt response 200 Health
417
422
  *
418
423
  * @bidirekt schema Health
@@ -513,18 +518,21 @@ npx @bidirekt/typescript-sdk-cli generate --check
513
518
 
514
519
  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
520
 
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:
521
+ 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
522
 
518
523
  ```sh
519
524
  npx @bidirekt/typescript-sdk-cli generate
520
- bidirekt validate contracts/generated.yaml --participant petstore_ts --environment production
521
- bidirekt publish contracts/generated.yaml --participant petstore_ts --version 1.4.0
525
+ bidirekt validate
526
+ bidirekt validate --participant petstore_ts --environment production
527
+ bidirekt publish --participant petstore_ts --version 1.4.0
522
528
  bidirekt can-i-deploy petstore_ts --version 1.4.0 --environment production
523
529
  # deploy
524
530
  bidirekt record-deployment petstore_ts --version 1.4.0 --environment production
525
531
  ```
526
532
 
527
- When `can-i-deploy` reports a break, fix the annotation or the type in the code and generate again.
533
+ Without file arguments, `validate` and `publish` read the `contracts/` folder of the current directory. `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.
534
+
535
+ 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/ src/schema.graphql`, and the same in `publish`. `contracts/` alone fails with `graph "petstore_graph" without a GraphQL schema`.
528
536
 
529
537
  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
538
 
@@ -532,12 +540,15 @@ A package of your workspace, which npm links into `node_modules`, is read as you
532
540
 
533
541
  ### Decorators
534
542
 
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` |
543
+ | Decorator | Goes on | Options |
544
+ | ----------------------------------- | ---------- | ------------------------------------------------------------------------------ |
545
+ | `@BidirektSchema(options?)` | a class | `name`, `union` |
546
+ | `@BidirektField(options?)` | a property | `type`, `name`, `optional`, `nullable`, `description`, `union`, see Fields |
547
+ | `@BidirektRestProvider(options)` | a method | `method`, `path`, `request`, `responses` |
548
+ | `@BidirektRestConsumer(options)` | a method | `provider`, `method`, `path`, `request`, `responses` |
549
+ | `@BidirektGraphqlConsumer(options)` | a method | `provider`, `query` or `mutation`, `arguments`, `returns`, see GraphQL returns |
550
+ | `@BidirektGraphqlField(options?)` | a property | the options of `@BidirektField`, `scalar`, `arguments`, see Fields |
551
+ | `@BidirektGraph(name)` | a class | none: `name` is the graph the service is a subgraph of |
541
552
 
542
553
  `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
554
 
@@ -545,14 +556,18 @@ With `emitDecoratorMetadata` on (NestJS, TypeORM), TypeScript keeps the imports
545
556
 
546
557
  ### Tags
547
558
 
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 |
559
+ | Tag | Goes above |
560
+ | -------------------------------------------------------------- | ------------------------------------------------------------------------------ |
561
+ | `@bidirekt schema [name=<Name>] [union={...}]` | a class, an `interface`, an object `type` or a string `enum` |
562
+ | `@bidirekt field [key=value ...]` | a property of a schema |
563
+ | `@bidirekt rest provides <METHOD> <path>` | a function, an exported arrow function, a method or a statement (`router.get`) |
564
+ | `@bidirekt rest consumes <provider> <METHOD> <path>` | the same |
565
+ | `@bidirekt request [body]` | follows `rest provides` or `rest consumes` |
566
+ | `@bidirekt response <status> [body]` | follows `rest provides` or `rest consumes`, once per status |
567
+ | `@bidirekt graphql consumes <provider> query\|mutation <name>` | the same as `rest provides` |
568
+ | `@bidirekt arguments <schema>`, `@bidirekt returns <type>` | follow `graphql consumes`, see GraphQL returns |
569
+ | `@bidirekt graphql field [key=value ...]` | a property of a schema, in place of `field`, see Fields |
570
+ | `@bidirekt graph <name>` | a class or any other element: `name` is the graph the service is a subgraph of |
556
571
 
557
572
  - A handler's comment can also declare schemas, see [Schemas in a handler's comment](#schemas-in-a-handlers-comment).
558
573
  - 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 +589,27 @@ A handler declares one resource: its method, in uppercase (`GET`, `POST`, `PUT`,
574
589
 
575
590
  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
591
 
592
+ ### GraphQL returns
593
+
594
+ `@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:
595
+
596
+ | Returns | Decorator | Tag | Contract |
597
+ | ----------------------- | ------------------------------------------------------------- | ------------------------------------------------ | --------------- |
598
+ | a schema | `Pet` | `Pet` | `Pet` |
599
+ | a schema or null | `{ nullable: Pet }` | `Pet?` | `PetOrNull` |
600
+ | a list | `[Pet]` or `{ list: Pet }` | `Pet[]` | `PetList` |
601
+ | a list or null | `{ list: Pet, nullable: true }` | `Pet[]?` | `PetListOrNull` |
602
+ | a list of items or null | `{ list: Pet, nullableItems: true }` | `Pet?[]` | `PetOrNullList` |
603
+ | a primitive | `'boolean'` | `boolean` | `Boolean` |
604
+ | a named primitive | `{ type: 'boolean', name: 'Flag' }` | `boolean as Flag` | `Flag` |
605
+ | a custom scalar | `{ scalar: 'DateTime' }` | `scalar:DateTime` | `DateTime` |
606
+ | an enum | `{ enum: ['AVAILABLE', 'SOLD'], name: 'Status' }` | `enum:AVAILABLE\|SOLD as Status` | `Status` |
607
+ | a union | `{ union: { Pet: Pet, Owner: Owner }, name: 'SearchResult' }` | `union={Pet: Pet, Owner: Owner} as SearchResult` | `SearchResult` |
608
+
609
+ 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 a bare string, `'boolean'`, is always written as `Boolean`; to name it, write `{ type: 'boolean', name: 'Flag' }` in the decorator or `boolean as Flag` in the tag, and both write `Flag: {type: 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.
610
+
611
+ 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.
612
+
577
613
  ### Fields
578
614
 
579
615
  | Decorator | Tag | What it declares |
@@ -587,6 +623,10 @@ Without a request (no `request` option, no `@bidirekt request` tag), the resourc
587
623
 
588
624
  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
625
 
626
+ 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.
627
+
628
+ A call that reads the type name declares a field `__typename` with the names it reads as a string literal type, `__typename: 'Pet'` or `__typename: 'Pet' | 'Toy'`, with `@BidirektField` or `@bidirekt field`. It is written as `type: enum` with `members: ["Pet", "Toy"]`, and breaks when the provider renames a type the call reads.
629
+
590
630
  ### Types
591
631
 
592
632
  A field's type comes from TypeScript, or from the JSDoc `@type` in JavaScript:
@@ -614,7 +654,7 @@ A declared `type` is the whole type of the field, whatever TypeScript says: a pr
614
654
 
615
655
  - 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
656
  - 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.
657
+ - 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
658
  - 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
659
  - 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
660
 
@@ -642,7 +682,7 @@ The contract describes what the code does, not the type the code declares. The T
642
682
  - `schema name "Pet" is declared more than once: give each schema a distinct name`
643
683
  - `method "get" must be uppercase: write "GET"`
644
684
  - `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.
685
+ - `@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
686
 
647
687
  ## Docs
648
688
 
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 {};