@skmtc/core 0.58.0 → 0.58.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,60 +42,82 @@ skmtc generate petstore https://petstore3.swagger.io/api/v3/openapi.json
42
42
 
43
43
  ### Example generator code
44
44
 
45
- ```typescript
45
+ A whole generator, in one file. It writes one `fetch` function for each
46
+ operation of the document. It is short on purpose: the function sends the
47
+ path as the document writes it, with no path parameters and no body.
48
+
49
+ ```ts
46
50
  import {
47
- toOasOperationEntry,
48
- toOasOperationProjectionBase,
49
- Identifier
51
+ decapitalize,
52
+ type EmptyEnrichments,
53
+ emptyEnrichmentSchema,
54
+ type OasOperationProjectionConstructorArgs,
55
+ toEndpointName,
56
+ toOasOperationEntry
50
57
  } from '@skmtc/core'
51
- import { ZodProjection } from '@skmtc/gen-zod'
52
- import denoJson from '../deno.json' with { type: 'json' }
53
-
54
- // Build a per-generator projection base via the factory.
55
- const ZodFetchBase = toOasOperationProjectionBase({
56
- id: denoJson.name,
57
- toIdentifier: ({ operation }) =>
58
- Identifier.createVariable(`fetch${operation.operationId}`),
59
- toExportPath: ({ operation }) =>
60
- `@/services/${operation.operationId}.generated.ts`
58
+ import { toStringLiteral, toTsOasOperationProjectionBase } from '@skmtc/lang-typescript'
59
+
60
+ const ID = '@acme/gen-fetch'
61
+
62
+ // This generator takes no settings from its consumer.
63
+ const toEnrichmentSchema = () => emptyEnrichmentSchema
64
+
65
+ // The name and the export path of each definition are decided here, once.
66
+ const FetchBase = toTsOasOperationProjectionBase<EmptyEnrichments>({
67
+ id: ID,
68
+
69
+ // Method and path, never operationId: `POST /search` is `createApiSearch`.
70
+ toIdentifierName: ({ operation }) => decapitalize(toEndpointName(operation)),
71
+
72
+ toIdentifierType: () => ({ type: 'variable' }),
73
+
74
+ toExportPath({ operation, enrichments, variant }) {
75
+ return `@/api/${this.toIdentifierName({ operation, enrichments, variant })}.generated.ts`
76
+ },
77
+
78
+ toEnrichmentSchema
61
79
  })
62
80
 
63
- class ZodFetch extends ZodFetchBase {
64
- zodName: string
81
+ // A producer: the constructor stores the parts, and toString() arranges them.
82
+ class FetchEndpoint extends FetchBase {
83
+ method: string
84
+ path: string
65
85
 
66
- constructor(args: ConstructorParameters<typeof ZodFetchBase>[0]) {
86
+ constructor(args: OasOperationProjectionConstructorArgs<EmptyEnrichments>) {
67
87
  super(args)
68
88
 
69
- // Insert a Zod schema for the success response into the same file.
70
- const response = this.operation.toSuccessResponse()?.resolve().toSchema()
71
- const zodResponse = this.insertNormalizedModel(ZodProjection, {
72
- schema: response,
73
- fallbackName: `${this.operation.operationId}Response`
74
- })
75
-
76
- // Grab the Zod identifier so toString() can reference it.
77
- this.zodName = zodResponse.identifier.name
89
+ this.method = toStringLiteral(this.operation.method.toUpperCase())
90
+ this.path = toStringLiteral(this.operation.path)
78
91
  }
79
92
 
80
93
  override toString(): string {
81
- return `async () => {
82
- const res = await fetch('${this.operation.path}')
83
- const data = await res.json()
84
- return ${this.zodName}.parse(data)
85
- }`
94
+ return `() => fetch(${this.path}, { method: ${this.method} })`
86
95
  }
87
96
  }
88
97
 
89
- // Wire it up so the engine dispatches against OAS operations.
90
- export const zodFetchEntry = toOasOperationEntry({
91
- id: denoJson.name,
92
- isSupported: () => true,
93
- transform: ({ context, operation }) => {
94
- context.insertOperation(ZodFetch, operation)
98
+ // The engine runs the entry once for each operation of the document.
99
+ export default toOasOperationEntry<EmptyEnrichments>({
100
+ id: ID,
101
+ toEnrichmentSchema,
102
+ transform({ context, operation, variant }) {
103
+ context.insertOperation({ projection: FetchEndpoint, operation, variant })
95
104
  }
96
105
  })
97
106
  ```
98
107
 
108
+ For a document with `GET /pets` and `POST /search`, it writes two files:
109
+
110
+ ```ts
111
+ // api/getApiPets.generated.ts
112
+ export const getApiPets = () => fetch('/pets', { method: 'GET' });
113
+
114
+ // api/createApiSearch.generated.ts
115
+ export const createApiSearch = () => fetch('/search', { method: 'POST' });
116
+ ```
117
+
118
+ `deno task verify-docs` type-checks this example against the packages in
119
+ this repository, so it compiles with the version you read it beside.
120
+
99
121
  ## 📦 Available Generators
100
122
 
101
123
  Stock generators on JSR (under `@skmtc/`):
@@ -39,6 +39,7 @@ export declare class FilePlan {
39
39
  /**
40
40
  * How many times a projection could not say where a subject's file is: a
41
41
  * static threw, or the subject's enrichments have variants and no `main`.
42
+ * Each declared projection counts, also one that another is asked for.
42
43
  * The run reports such a fault where it happens. The plan leaves the file out.
43
44
  */
44
45
  unanswered: number;
@@ -9,10 +9,29 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _FilePlan_instances, _FilePlan_context, _FilePlan_projections, _FilePlan_toFilePath, _FilePlan_paths, _FilePlan_indexes, _FilePlan_left, _FilePlan_held, _FilePlan_namedLeft, _FilePlan_filesBehind, _FilePlan_modelFiles, _FilePlan_toFilesBehind, _FilePlan_toModelFiles, _FilePlan_toFiles, _FilePlan_toVariants, _FilePlan_toIndex;
12
+ var _FilePlan_instances, _FilePlan_context, _FilePlan_projections, _FilePlan_toFilePath, _FilePlan_paths, _FilePlan_indexes, _FilePlan_left, _FilePlan_held, _FilePlan_namedLeft, _FilePlan_filesBehind, _FilePlan_modelFiles, _FilePlan_toFilesBehind, _FilePlan_toModelFiles, _FilePlan_toFiles, _FilePlan_toGroupFiles, _FilePlan_toVariants, _FilePlan_toIndex;
13
13
  import { ModelSubject } from './Subject.js';
14
14
  import { fromModelKey } from '../helpers/refFns.js';
15
15
  import { toVariantList } from '../helpers/toVariantList.js';
16
+ /**
17
+ * Whether two declared projections of one kind give every subject the same
18
+ * answer. A projection always does with itself, also when it gives a new
19
+ * function each time a static is read.
20
+ */
21
+ const haveSameAnswers = (first, second) => first === second ||
22
+ (first.id === second.id &&
23
+ first.toEnrichments === second.toEnrichments &&
24
+ first.toExportPath === second.toExportPath);
25
+ /** Groups the declared projections of one kind. The groups keep the order of their first projections. */
26
+ const toDeclaredOfType = (projections) => {
27
+ const asked = projections.filter((projection, index) => projections.findIndex(other => haveSameAnswers(other, projection)) === index);
28
+ const groupOf = projections.map(projection => asked.findIndex(other => haveSameAnswers(other, projection)));
29
+ const groups = asked.map((projection, index) => ({
30
+ projection,
31
+ size: groupOf.filter(group => group === index).length
32
+ }));
33
+ return { groups, groupOf };
34
+ };
16
35
  /**
17
36
  * Which subjects of a run hold each file, known before the run from what the
18
37
  * entries declared. A subject holds a file when it can write to it or read
@@ -63,12 +82,14 @@ export class FilePlan {
63
82
  /**
64
83
  * How many times a projection could not say where a subject's file is: a
65
84
  * static threw, or the subject's enrichments have variants and no `main`.
85
+ * Each declared projection counts, also one that another is asked for.
66
86
  * The run reports such a fault where it happens. The plan leaves the file out.
67
87
  */
68
88
  );
69
89
  /**
70
90
  * How many times a projection could not say where a subject's file is: a
71
91
  * static threw, or the subject's enrichments have variants and no `main`.
92
+ * Each declared projection counts, also one that another is asked for.
72
93
  * The run reports such a fault where it happens. The plan leaves the file out.
73
94
  */
74
95
  Object.defineProperty(this, "unanswered", {
@@ -78,7 +99,10 @@ export class FilePlan {
78
99
  value: 0
79
100
  });
80
101
  __classPrivateFieldSet(this, _FilePlan_context, context, "f");
81
- __classPrivateFieldSet(this, _FilePlan_projections, Map.groupBy(projections, projection => projection.type), "f");
102
+ __classPrivateFieldSet(this, _FilePlan_projections, new Map([...Map.groupBy(projections, projection => projection.type)].map(([type, ofType]) => [
103
+ type,
104
+ toDeclaredOfType(ofType)
105
+ ])), "f");
82
106
  __classPrivateFieldSet(this, _FilePlan_toFilePath, toFilePath, "f");
83
107
  subjects.forEach(subject => {
84
108
  // A model names itself, so its own files are among the files behind
@@ -152,18 +176,25 @@ _FilePlan_context = new WeakMap(), _FilePlan_projections = new WeakMap(), _FileP
152
176
  __classPrivateFieldGet(this, _FilePlan_modelFiles, "f").set(key, files);
153
177
  return files;
154
178
  }, _FilePlan_toFiles = function _FilePlan_toFiles(subject) {
155
- const projections = __classPrivateFieldGet(this, _FilePlan_projections, "f").get(subject.type) ?? [];
156
- return projections.flatMap(projection => __classPrivateFieldGet(this, _FilePlan_instances, "m", _FilePlan_toVariants).call(this, subject, projection).flatMap(variant => {
179
+ const declared = __classPrivateFieldGet(this, _FilePlan_projections, "f").get(subject.type);
180
+ if (declared === undefined) {
181
+ return [];
182
+ }
183
+ const filesOfGroup = declared.groups.map(group => __classPrivateFieldGet(this, _FilePlan_instances, "m", _FilePlan_toGroupFiles).call(this, subject, group));
184
+ return declared.groupOf.flatMap(group => filesOfGroup[group]);
185
+ }, _FilePlan_toGroupFiles = function _FilePlan_toGroupFiles(subject, group) {
186
+ const { projection, size } = group;
187
+ return __classPrivateFieldGet(this, _FilePlan_instances, "m", _FilePlan_toVariants).call(this, subject, group).flatMap(variant => {
157
188
  try {
158
189
  const exportPath = subject.toExportPath({ projection, context: __classPrivateFieldGet(this, _FilePlan_context, "f"), variant });
159
190
  return exportPath === undefined ? [] : [__classPrivateFieldGet(this, _FilePlan_instances, "m", _FilePlan_toIndex).call(this, __classPrivateFieldGet(this, _FilePlan_toFilePath, "f").call(this, exportPath, projection.id))];
160
191
  }
161
192
  catch {
162
- this.unanswered += 1;
193
+ this.unanswered += size;
163
194
  return [];
164
195
  }
165
- }));
166
- }, _FilePlan_toVariants = function _FilePlan_toVariants(subject, projection) {
196
+ });
197
+ }, _FilePlan_toVariants = function _FilePlan_toVariants(subject, { projection, size }) {
167
198
  try {
168
199
  return toVariantList({
169
200
  opEnrichments: __classPrivateFieldGet(this, _FilePlan_context, "f").readEnrichment([projection.id, ...subject.enrichmentPath]),
@@ -172,7 +203,7 @@ _FilePlan_context = new WeakMap(), _FilePlan_projections = new WeakMap(), _FileP
172
203
  });
173
204
  }
174
205
  catch {
175
- this.unanswered += 1;
206
+ this.unanswered += size;
176
207
  return [];
177
208
  }
178
209
  }, _FilePlan_toIndex = function _FilePlan_toIndex(path) {
@@ -1097,7 +1097,8 @@ _GenerateContext_files = new WeakMap(), _GenerateContext_failedItems = new WeakM
1097
1097
  if (__classPrivateFieldGet(this, _GenerateContext_released, "f").has(path)) {
1098
1098
  throw new Error(`File '${path}' was complete and given to the host before this subject used it. ` +
1099
1099
  `A generator inserts a projection that its entry does not list in 'projections', ` +
1100
- `or inserts a model that this subject does not reach through '$ref's.`);
1100
+ `or inserts a model that this subject does not reach through '$ref's, ` +
1101
+ `or a static of a listed projection answers differently through 'this' from one that shares it.`);
1101
1102
  }
1102
1103
  }, _GenerateContext_logGeneratorLine = function _GenerateContext_logGeneratorLine(generatorTrail, message) {
1103
1104
  if (!__classPrivateFieldGet(this, _GenerateContext_logsGeneratorLines, "f")) {
@@ -44,5 +44,10 @@ export type DeclaredGqlOperationProjection = {
44
44
  * and each one of another generator that it inserts, such as the model
45
45
  * projection an operation generator takes its schemas from. From the list,
46
46
  * core can know before a run which files the generator can write.
47
+ *
48
+ * Projections with the same `type` and `id`, and the same `toEnrichments`
49
+ * and `toExportPath` functions (compared by reference), are taken to give the
50
+ * same answers: the file plan asks one of them for all. So the answer of such
51
+ * a static must not depend on the class it is called on, through `this`.
47
52
  */
48
53
  export type DeclaredProjection = DeclaredModelProjection | DeclaredOasOperationProjection | DeclaredWebhookProjection | DeclaredGqlOperationProjection;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skmtc/core",
3
- "version": "0.58.0",
3
+ "version": "0.58.2",
4
4
  "description": "Skmtc is a declarative code generation framework",
5
5
  "keywords": [
6
6
  "openapi",
@@ -39,6 +39,7 @@ export declare class FilePlan {
39
39
  /**
40
40
  * How many times a projection could not say where a subject's file is: a
41
41
  * static threw, or the subject's enrichments have variants and no `main`.
42
+ * Each declared projection counts, also one that another is asked for.
42
43
  * The run reports such a fault where it happens. The plan leaves the file out.
43
44
  */
44
45
  unanswered: number;
@@ -10,12 +10,31 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _FilePlan_instances, _FilePlan_context, _FilePlan_projections, _FilePlan_toFilePath, _FilePlan_paths, _FilePlan_indexes, _FilePlan_left, _FilePlan_held, _FilePlan_namedLeft, _FilePlan_filesBehind, _FilePlan_modelFiles, _FilePlan_toFilesBehind, _FilePlan_toModelFiles, _FilePlan_toFiles, _FilePlan_toVariants, _FilePlan_toIndex;
13
+ var _FilePlan_instances, _FilePlan_context, _FilePlan_projections, _FilePlan_toFilePath, _FilePlan_paths, _FilePlan_indexes, _FilePlan_left, _FilePlan_held, _FilePlan_namedLeft, _FilePlan_filesBehind, _FilePlan_modelFiles, _FilePlan_toFilesBehind, _FilePlan_toModelFiles, _FilePlan_toFiles, _FilePlan_toGroupFiles, _FilePlan_toVariants, _FilePlan_toIndex;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.FilePlan = void 0;
16
16
  const Subject_js_1 = require("./Subject.js");
17
17
  const refFns_js_1 = require("../helpers/refFns.js");
18
18
  const toVariantList_js_1 = require("../helpers/toVariantList.js");
19
+ /**
20
+ * Whether two declared projections of one kind give every subject the same
21
+ * answer. A projection always does with itself, also when it gives a new
22
+ * function each time a static is read.
23
+ */
24
+ const haveSameAnswers = (first, second) => first === second ||
25
+ (first.id === second.id &&
26
+ first.toEnrichments === second.toEnrichments &&
27
+ first.toExportPath === second.toExportPath);
28
+ /** Groups the declared projections of one kind. The groups keep the order of their first projections. */
29
+ const toDeclaredOfType = (projections) => {
30
+ const asked = projections.filter((projection, index) => projections.findIndex(other => haveSameAnswers(other, projection)) === index);
31
+ const groupOf = projections.map(projection => asked.findIndex(other => haveSameAnswers(other, projection)));
32
+ const groups = asked.map((projection, index) => ({
33
+ projection,
34
+ size: groupOf.filter(group => group === index).length
35
+ }));
36
+ return { groups, groupOf };
37
+ };
19
38
  /**
20
39
  * Which subjects of a run hold each file, known before the run from what the
21
40
  * entries declared. A subject holds a file when it can write to it or read
@@ -66,12 +85,14 @@ class FilePlan {
66
85
  /**
67
86
  * How many times a projection could not say where a subject's file is: a
68
87
  * static threw, or the subject's enrichments have variants and no `main`.
88
+ * Each declared projection counts, also one that another is asked for.
69
89
  * The run reports such a fault where it happens. The plan leaves the file out.
70
90
  */
71
91
  );
72
92
  /**
73
93
  * How many times a projection could not say where a subject's file is: a
74
94
  * static threw, or the subject's enrichments have variants and no `main`.
95
+ * Each declared projection counts, also one that another is asked for.
75
96
  * The run reports such a fault where it happens. The plan leaves the file out.
76
97
  */
77
98
  Object.defineProperty(this, "unanswered", {
@@ -81,7 +102,10 @@ class FilePlan {
81
102
  value: 0
82
103
  });
83
104
  __classPrivateFieldSet(this, _FilePlan_context, context, "f");
84
- __classPrivateFieldSet(this, _FilePlan_projections, Map.groupBy(projections, projection => projection.type), "f");
105
+ __classPrivateFieldSet(this, _FilePlan_projections, new Map([...Map.groupBy(projections, projection => projection.type)].map(([type, ofType]) => [
106
+ type,
107
+ toDeclaredOfType(ofType)
108
+ ])), "f");
85
109
  __classPrivateFieldSet(this, _FilePlan_toFilePath, toFilePath, "f");
86
110
  subjects.forEach(subject => {
87
111
  // A model names itself, so its own files are among the files behind
@@ -156,18 +180,25 @@ _FilePlan_context = new WeakMap(), _FilePlan_projections = new WeakMap(), _FileP
156
180
  __classPrivateFieldGet(this, _FilePlan_modelFiles, "f").set(key, files);
157
181
  return files;
158
182
  }, _FilePlan_toFiles = function _FilePlan_toFiles(subject) {
159
- const projections = __classPrivateFieldGet(this, _FilePlan_projections, "f").get(subject.type) ?? [];
160
- return projections.flatMap(projection => __classPrivateFieldGet(this, _FilePlan_instances, "m", _FilePlan_toVariants).call(this, subject, projection).flatMap(variant => {
183
+ const declared = __classPrivateFieldGet(this, _FilePlan_projections, "f").get(subject.type);
184
+ if (declared === undefined) {
185
+ return [];
186
+ }
187
+ const filesOfGroup = declared.groups.map(group => __classPrivateFieldGet(this, _FilePlan_instances, "m", _FilePlan_toGroupFiles).call(this, subject, group));
188
+ return declared.groupOf.flatMap(group => filesOfGroup[group]);
189
+ }, _FilePlan_toGroupFiles = function _FilePlan_toGroupFiles(subject, group) {
190
+ const { projection, size } = group;
191
+ return __classPrivateFieldGet(this, _FilePlan_instances, "m", _FilePlan_toVariants).call(this, subject, group).flatMap(variant => {
161
192
  try {
162
193
  const exportPath = subject.toExportPath({ projection, context: __classPrivateFieldGet(this, _FilePlan_context, "f"), variant });
163
194
  return exportPath === undefined ? [] : [__classPrivateFieldGet(this, _FilePlan_instances, "m", _FilePlan_toIndex).call(this, __classPrivateFieldGet(this, _FilePlan_toFilePath, "f").call(this, exportPath, projection.id))];
164
195
  }
165
196
  catch {
166
- this.unanswered += 1;
197
+ this.unanswered += size;
167
198
  return [];
168
199
  }
169
- }));
170
- }, _FilePlan_toVariants = function _FilePlan_toVariants(subject, projection) {
200
+ });
201
+ }, _FilePlan_toVariants = function _FilePlan_toVariants(subject, { projection, size }) {
171
202
  try {
172
203
  return (0, toVariantList_js_1.toVariantList)({
173
204
  opEnrichments: __classPrivateFieldGet(this, _FilePlan_context, "f").readEnrichment([projection.id, ...subject.enrichmentPath]),
@@ -176,7 +207,7 @@ _FilePlan_context = new WeakMap(), _FilePlan_projections = new WeakMap(), _FileP
176
207
  });
177
208
  }
178
209
  catch {
179
- this.unanswered += 1;
210
+ this.unanswered += size;
180
211
  return [];
181
212
  }
182
213
  }, _FilePlan_toIndex = function _FilePlan_toIndex(path) {
@@ -1108,7 +1108,8 @@ _GenerateContext_files = new WeakMap(), _GenerateContext_failedItems = new WeakM
1108
1108
  if (__classPrivateFieldGet(this, _GenerateContext_released, "f").has(path)) {
1109
1109
  throw new Error(`File '${path}' was complete and given to the host before this subject used it. ` +
1110
1110
  `A generator inserts a projection that its entry does not list in 'projections', ` +
1111
- `or inserts a model that this subject does not reach through '$ref's.`);
1111
+ `or inserts a model that this subject does not reach through '$ref's, ` +
1112
+ `or a static of a listed projection answers differently through 'this' from one that shares it.`);
1112
1113
  }
1113
1114
  }, _GenerateContext_logGeneratorLine = function _GenerateContext_logGeneratorLine(generatorTrail, message) {
1114
1115
  if (!__classPrivateFieldGet(this, _GenerateContext_logsGeneratorLines, "f")) {
@@ -44,5 +44,10 @@ export type DeclaredGqlOperationProjection = {
44
44
  * and each one of another generator that it inserts, such as the model
45
45
  * projection an operation generator takes its schemas from. From the list,
46
46
  * core can know before a run which files the generator can write.
47
+ *
48
+ * Projections with the same `type` and `id`, and the same `toEnrichments`
49
+ * and `toExportPath` functions (compared by reference), are taken to give the
50
+ * same answers: the file plan asks one of them for all. So the answer of such
51
+ * a static must not depend on the class it is called on, through `this`.
47
52
  */
48
53
  export type DeclaredProjection = DeclaredModelProjection | DeclaredOasOperationProjection | DeclaredWebhookProjection | DeclaredGqlOperationProjection;