@osdk/generator 1.13.0 → 1.14.0-beta.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 (164) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/build/browser/index.js +1833 -981
  3. package/build/browser/index.js.map +1 -1
  4. package/build/cjs/GenerateContext/EnhanceCommon.d.cts +9 -0
  5. package/build/cjs/GenerateContext/EnhanceCommon.d.ts.map +1 -0
  6. package/build/cjs/GenerateContext/EnhancedAction.d.cts +14 -0
  7. package/build/cjs/GenerateContext/EnhancedAction.d.ts.map +1 -0
  8. package/build/cjs/GenerateContext/EnhancedBase.d.cts +23 -0
  9. package/build/cjs/GenerateContext/EnhancedBase.d.ts.map +1 -0
  10. package/build/cjs/GenerateContext/EnhancedInterfaceType.d.cts +13 -0
  11. package/build/cjs/GenerateContext/EnhancedInterfaceType.d.ts.map +1 -0
  12. package/build/cjs/GenerateContext/EnhancedObjectType.d.cts +12 -0
  13. package/build/cjs/GenerateContext/EnhancedObjectType.d.ts.map +1 -0
  14. package/build/cjs/GenerateContext/EnhancedOntologyDefinition.d.cts +27 -0
  15. package/build/cjs/GenerateContext/EnhancedOntologyDefinition.d.ts.map +1 -0
  16. package/build/cjs/GenerateContext/EnhancedQuery.d.cts +14 -0
  17. package/build/cjs/GenerateContext/EnhancedQuery.d.ts.map +1 -0
  18. package/build/cjs/GenerateContext/EnhancedSharedPropertyType.d.cts +8 -0
  19. package/build/cjs/GenerateContext/EnhancedSharedPropertyType.d.ts.map +1 -0
  20. package/build/cjs/GenerateContext/ForeignType.d.cts +10 -0
  21. package/build/cjs/GenerateContext/ForeignType.d.ts.map +1 -0
  22. package/build/cjs/GenerateContext/GenerateContext.d.cts +13 -0
  23. package/build/cjs/GenerateContext/GenerateContext.d.ts.map +1 -0
  24. package/build/cjs/GenerateContext/enhanceOntology.d.cts +4 -0
  25. package/build/cjs/GenerateContext/enhanceOntology.d.ts.map +1 -0
  26. package/build/cjs/generateClientSdkPackage.d.cts +1 -1
  27. package/build/cjs/generateClientSdkPackage.d.ts.map +1 -1
  28. package/build/cjs/index.cjs +1833 -981
  29. package/build/cjs/index.cjs.map +1 -1
  30. package/build/cjs/shared/apiNamespaces/startsWithApiNamespace.d.cts +2 -0
  31. package/build/cjs/shared/apiNamespaces/startsWithApiNamespace.d.ts.map +1 -0
  32. package/build/cjs/shared/apiNamespaces/startsWithApiNamespace.test.d.cts +2 -0
  33. package/build/cjs/shared/apiNamespaces/startsWithApiNamespace.test.d.ts.map +1 -0
  34. package/build/cjs/shared/getObjectImports.d.cts +4 -0
  35. package/build/cjs/shared/getObjectImports.d.ts.map +1 -0
  36. package/build/cjs/shared/getObjectTypeApiNamesFromQuery.d.cts +4 -0
  37. package/build/cjs/shared/getObjectTypeApiNamesFromQuery.d.ts.map +1 -0
  38. package/build/cjs/shared/getObjectTypesFromQueryDataType.d.cts +3 -0
  39. package/build/cjs/shared/getObjectTypesFromQueryDataType.d.ts.map +1 -0
  40. package/build/cjs/shared/wireQueryDataTypeToQueryDataTypeDefinition.d.ts.map +1 -1
  41. package/build/cjs/util/stringUnionFrom.d.cts +2 -0
  42. package/build/cjs/util/stringUnionFrom.d.ts.map +1 -0
  43. package/build/cjs/util/test/TodoWireOntology.d.cts +60 -4
  44. package/build/cjs/util/test/TodoWireOntology.d.ts.map +1 -1
  45. package/build/cjs/util/test/createMockMinimalFiles.d.ts.map +1 -1
  46. package/build/cjs/util/test/formatTs.d.cts +1 -1
  47. package/build/cjs/util/test/formatTs.d.ts.map +1 -1
  48. package/build/cjs/v1.1/generateClientSdkVersionOneDotOne.d.ts.map +1 -1
  49. package/build/cjs/v1.1/generatePerActionDataFilesV1.d.cts +3 -0
  50. package/build/cjs/v1.1/generatePerActionDataFilesV1.d.ts.map +1 -0
  51. package/build/cjs/v1.1/generatePerActionDataFilesV1.test.d.cts +2 -0
  52. package/build/cjs/v1.1/generatePerActionDataFilesV1.test.d.ts.map +1 -0
  53. package/build/cjs/v1.1/generatePerObjectInterfaceAndDataFiles.d.cts +2 -2
  54. package/build/cjs/v1.1/generatePerObjectInterfaceAndDataFiles.d.ts.map +1 -1
  55. package/build/cjs/v1.1/generatePerQueryDataFiles.d.cts +3 -3
  56. package/build/cjs/v1.1/generatePerQueryDataFiles.d.ts.map +1 -1
  57. package/build/cjs/v1.1/wireObjectTypeV2ToSdkObjectConstV1.d.cts +2 -0
  58. package/build/cjs/v1.1/wireObjectTypeV2ToSdkObjectConstV1.d.ts.map +1 -0
  59. package/build/cjs/v2.0/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.d.ts.map +1 -0
  60. package/build/cjs/v2.0/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.test.d.ts.map +1 -0
  61. package/build/cjs/v2.0/generateClientSdkVersionTwoPointZero.d.cts +1 -1
  62. package/build/cjs/v2.0/generateClientSdkVersionTwoPointZero.d.ts.map +1 -1
  63. package/build/cjs/v2.0/generateMetadata.d.cts +2 -3
  64. package/build/cjs/v2.0/generateMetadata.d.ts.map +1 -1
  65. package/build/cjs/v2.0/generatePerActionDataFiles.d.cts +3 -0
  66. package/build/cjs/v2.0/generatePerActionDataFiles.d.ts.map +1 -0
  67. package/build/cjs/v2.0/generatePerActionDataFiles.test.d.ts.map +1 -0
  68. package/build/cjs/v2.0/generatePerQueryDataFiles.d.cts +9 -0
  69. package/build/cjs/v2.0/generatePerQueryDataFiles.d.ts.map +1 -0
  70. package/build/cjs/v2.0/generatePerQueryDataFiles.test.d.cts +2 -0
  71. package/build/cjs/v2.0/generatePerQueryDataFiles.test.d.ts.map +1 -0
  72. package/build/cjs/v2.0/wireObjectTypeV2ToSdkObjectConstV2.d.cts +13 -0
  73. package/build/cjs/v2.0/wireObjectTypeV2ToSdkObjectConstV2.d.ts.map +1 -0
  74. package/build/esm/GenerateContext/EnhanceCommon.d.ts +9 -0
  75. package/build/esm/GenerateContext/EnhanceCommon.d.ts.map +1 -0
  76. package/build/esm/GenerateContext/EnhancedAction.d.ts +14 -0
  77. package/build/esm/GenerateContext/EnhancedAction.d.ts.map +1 -0
  78. package/build/esm/GenerateContext/EnhancedBase.d.ts +23 -0
  79. package/build/esm/GenerateContext/EnhancedBase.d.ts.map +1 -0
  80. package/build/esm/GenerateContext/EnhancedInterfaceType.d.ts +13 -0
  81. package/build/esm/GenerateContext/EnhancedInterfaceType.d.ts.map +1 -0
  82. package/build/esm/GenerateContext/EnhancedObjectType.d.ts +12 -0
  83. package/build/esm/GenerateContext/EnhancedObjectType.d.ts.map +1 -0
  84. package/build/esm/GenerateContext/EnhancedOntologyDefinition.d.ts +27 -0
  85. package/build/esm/GenerateContext/EnhancedOntologyDefinition.d.ts.map +1 -0
  86. package/build/esm/GenerateContext/EnhancedQuery.d.ts +14 -0
  87. package/build/esm/GenerateContext/EnhancedQuery.d.ts.map +1 -0
  88. package/build/esm/GenerateContext/EnhancedSharedPropertyType.d.ts +8 -0
  89. package/build/esm/GenerateContext/EnhancedSharedPropertyType.d.ts.map +1 -0
  90. package/build/esm/GenerateContext/ForeignType.d.ts +10 -0
  91. package/build/esm/GenerateContext/ForeignType.d.ts.map +1 -0
  92. package/build/esm/GenerateContext/GenerateContext.d.ts +13 -0
  93. package/build/esm/GenerateContext/GenerateContext.d.ts.map +1 -0
  94. package/build/esm/GenerateContext/enhanceOntology.d.ts +4 -0
  95. package/build/esm/GenerateContext/enhanceOntology.d.ts.map +1 -0
  96. package/build/esm/generateClientSdkPackage.d.ts +1 -1
  97. package/build/esm/generateClientSdkPackage.d.ts.map +1 -1
  98. package/build/esm/index.js +1833 -981
  99. package/build/esm/index.js.map +1 -1
  100. package/build/esm/shared/apiNamespaces/startsWithApiNamespace.d.ts +2 -0
  101. package/build/esm/shared/apiNamespaces/startsWithApiNamespace.d.ts.map +1 -0
  102. package/build/esm/shared/apiNamespaces/startsWithApiNamespace.test.d.ts +2 -0
  103. package/build/esm/shared/apiNamespaces/startsWithApiNamespace.test.d.ts.map +1 -0
  104. package/build/esm/shared/getObjectImports.d.ts +4 -0
  105. package/build/esm/shared/getObjectImports.d.ts.map +1 -0
  106. package/build/esm/shared/getObjectTypeApiNamesFromQuery.d.ts +4 -0
  107. package/build/esm/shared/getObjectTypeApiNamesFromQuery.d.ts.map +1 -0
  108. package/build/esm/shared/getObjectTypesFromQueryDataType.d.ts +3 -0
  109. package/build/esm/shared/getObjectTypesFromQueryDataType.d.ts.map +1 -0
  110. package/build/esm/shared/wireQueryDataTypeToQueryDataTypeDefinition.d.ts.map +1 -1
  111. package/build/esm/util/stringUnionFrom.d.ts +2 -0
  112. package/build/esm/util/stringUnionFrom.d.ts.map +1 -0
  113. package/build/esm/util/test/TodoWireOntology.d.ts +60 -4
  114. package/build/esm/util/test/TodoWireOntology.d.ts.map +1 -1
  115. package/build/esm/util/test/createMockMinimalFiles.d.ts.map +1 -1
  116. package/build/esm/util/test/formatTs.d.ts +1 -1
  117. package/build/esm/util/test/formatTs.d.ts.map +1 -1
  118. package/build/esm/v1.1/generateClientSdkVersionOneDotOne.d.ts.map +1 -1
  119. package/build/esm/v1.1/generatePerActionDataFilesV1.d.ts +3 -0
  120. package/build/esm/v1.1/generatePerActionDataFilesV1.d.ts.map +1 -0
  121. package/build/esm/v1.1/generatePerActionDataFilesV1.test.d.ts +2 -0
  122. package/build/esm/v1.1/generatePerActionDataFilesV1.test.d.ts.map +1 -0
  123. package/build/esm/v1.1/generatePerObjectInterfaceAndDataFiles.d.ts +2 -2
  124. package/build/esm/v1.1/generatePerObjectInterfaceAndDataFiles.d.ts.map +1 -1
  125. package/build/esm/v1.1/generatePerQueryDataFiles.d.ts +3 -3
  126. package/build/esm/v1.1/generatePerQueryDataFiles.d.ts.map +1 -1
  127. package/build/esm/v1.1/wireObjectTypeV2ToSdkObjectConstV1.d.ts +2 -0
  128. package/build/esm/v1.1/wireObjectTypeV2ToSdkObjectConstV1.d.ts.map +1 -0
  129. package/build/esm/v2.0/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.d.ts.map +1 -0
  130. package/build/esm/v2.0/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.test.d.ts.map +1 -0
  131. package/build/esm/v2.0/generateClientSdkVersionTwoPointZero.d.ts +1 -1
  132. package/build/esm/v2.0/generateClientSdkVersionTwoPointZero.d.ts.map +1 -1
  133. package/build/esm/v2.0/generateMetadata.d.ts +2 -3
  134. package/build/esm/v2.0/generateMetadata.d.ts.map +1 -1
  135. package/build/esm/v2.0/generatePerActionDataFiles.d.ts +3 -0
  136. package/build/esm/v2.0/generatePerActionDataFiles.d.ts.map +1 -0
  137. package/build/esm/v2.0/generatePerActionDataFiles.test.d.ts.map +1 -0
  138. package/build/esm/v2.0/generatePerQueryDataFiles.d.ts +9 -0
  139. package/build/esm/v2.0/generatePerQueryDataFiles.d.ts.map +1 -0
  140. package/build/esm/v2.0/generatePerQueryDataFiles.test.d.ts +2 -0
  141. package/build/esm/v2.0/generatePerQueryDataFiles.test.d.ts.map +1 -0
  142. package/build/esm/v2.0/wireObjectTypeV2ToSdkObjectConstV2.d.ts +13 -0
  143. package/build/esm/v2.0/wireObjectTypeV2ToSdkObjectConstV2.d.ts.map +1 -0
  144. package/package.json +5 -4
  145. package/build/cjs/shared/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.d.ts.map +0 -1
  146. package/build/cjs/shared/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.test.d.ts.map +0 -1
  147. package/build/cjs/shared/generatePerActionDataFiles.d.cts +0 -4
  148. package/build/cjs/shared/generatePerActionDataFiles.d.ts.map +0 -1
  149. package/build/cjs/shared/generatePerActionDataFiles.test.d.ts.map +0 -1
  150. package/build/cjs/shared/wireObjectTypeV2ToSdkObjectConst.d.cts +0 -2
  151. package/build/cjs/shared/wireObjectTypeV2ToSdkObjectConst.d.ts.map +0 -1
  152. package/build/esm/shared/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.d.ts.map +0 -1
  153. package/build/esm/shared/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.test.d.ts.map +0 -1
  154. package/build/esm/shared/generatePerActionDataFiles.d.ts +0 -4
  155. package/build/esm/shared/generatePerActionDataFiles.d.ts.map +0 -1
  156. package/build/esm/shared/generatePerActionDataFiles.test.d.ts.map +0 -1
  157. package/build/esm/shared/wireObjectTypeV2ToSdkObjectConst.d.ts +0 -2
  158. package/build/esm/shared/wireObjectTypeV2ToSdkObjectConst.d.ts.map +0 -1
  159. /package/build/cjs/{shared → v2.0}/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.d.cts +0 -0
  160. /package/build/cjs/{shared → v2.0}/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.test.d.cts +0 -0
  161. /package/build/cjs/{shared → v2.0}/generatePerActionDataFiles.test.d.cts +0 -0
  162. /package/build/esm/{shared → v2.0}/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.d.ts +0 -0
  163. /package/build/esm/{shared → v2.0}/UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst.test.d.ts +0 -0
  164. /package/build/esm/{shared → v2.0}/generatePerActionDataFiles.test.d.ts +0 -0
@@ -1,136 +1,257 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path16 from 'path';
3
3
  import path16__default, { join } from 'path';
4
+ import { __UNSTABLE_wireInterfaceTypeV2ToSdkObjectDefinition, wireObjectTypeFullMetadataToSdkObjectTypeDefinition } from '@osdk/generator-converters';
4
5
  import { format } from 'prettier';
5
6
  import organizeImports from 'prettier-plugin-organize-imports';
6
- import { wireObjectTypeFullMetadataToSdkObjectTypeDefinition, __UNSTABLE_wireInterfaceTypeV2ToSdkObjectDefinition } from '@osdk/generator-converters';
7
7
  import fastDeepEqual from 'fast-deep-equal';
8
8
  import invariant from 'tiny-invariant';
9
9
 
10
10
  // src/generateClientSdkPackage.ts
11
+ var AbstractImportable = class {
12
+ /**
13
+ * Either a path relative to the ourDir (e.g. "./ontology/objects/foo.js") or a normal
14
+ * module import (e.g. "@something/foo")/
15
+ */
16
+ constructor(common, fullApiName, basePath) {
17
+ this._common = common;
18
+ this.fullApiName = fullApiName;
19
+ [this.apiNamespace, this.shortApiName] = extractNamespace(this.fullApiName);
20
+ const {
21
+ ontologyApiNamespace,
22
+ apiNamespacePackageMap,
23
+ importExt
24
+ } = common;
25
+ this.isLocal = ontologyApiNamespace === this.apiNamespace;
26
+ this.sourcePackage = this.apiNamespace && !this.isLocal ? apiNamespacePackageMap.get(this.apiNamespace) : void 0;
27
+ this.importPath = this.isLocal ? `${basePath}/${this.shortApiName}${importExt}` : this.sourcePackage;
28
+ this.uniqueImportName = this.shortApiName;
29
+ }
30
+ getImportPathRelTo = (filePath) => {
31
+ if (this.importPath.startsWith(".")) {
32
+ const result = path16.relative(path16.dirname(filePath), this.importPath);
33
+ if (result.startsWith(".")) {
34
+ return result;
35
+ } else {
36
+ return `./${result}`;
37
+ }
38
+ } else {
39
+ return this.importPath;
40
+ }
41
+ };
42
+ };
43
+ var EnhancedBase = class extends AbstractImportable {
44
+ constructor(common, og, fullApiName, basePath) {
45
+ super(common, fullApiName, basePath);
46
+ this.og = og;
47
+ if (!this.isLocal && !this.sourcePackage) {
48
+ throw new Error(`Expected { ns:'${this.apiNamespace}', shortName: '${this.shortApiName}'} to be in namespace '${common.ontologyApiNamespace}' or in a provided package mapping`);
49
+ }
50
+ }
51
+ };
52
+ function extractNamespace(fqApiName) {
53
+ const last = fqApiName.lastIndexOf(".");
54
+ if (last === -1) return [void 0, fqApiName];
55
+ return [fqApiName.slice(0, last), fqApiName.slice(last + 1)];
56
+ }
57
+
58
+ // src/GenerateContext/EnhancedAction.ts
59
+ var EnhancedAction = class extends EnhancedBase {
60
+ constructor(common, og) {
61
+ super(common, og, og.apiName, "./ontology/actions");
62
+ this.og = og;
63
+ }
64
+ get description() {
65
+ return this.og.description;
66
+ }
67
+ get parameters() {
68
+ return this.og.parameters;
69
+ }
70
+ get operations() {
71
+ return this.og.operations;
72
+ }
73
+ get paramsIdentifier() {
74
+ return `${this.shortApiName}.Parameters`;
75
+ }
76
+ get definitionIdentifier() {
77
+ return `${this.shortApiName}.Definition`;
78
+ }
79
+ get definitionParamsIdentifier() {
80
+ return `${this.shortApiName}.ParamsDefinition`;
81
+ }
82
+ };
11
83
 
12
84
  // src/util/deleteUndefineds.ts
13
85
  function deleteUndefineds(obj) {
14
86
  return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== void 0));
15
87
  }
16
88
 
17
- // src/util/stringify.ts
18
- var defaultCustomizer = (value, defaultValueFormatter, key, defaultKeyFormatter) => {
19
- return [defaultKeyFormatter(key), defaultValueFormatter(value)];
89
+ // src/GenerateContext/EnhancedInterfaceType.ts
90
+ var EnhancedInterfaceType = class extends EnhancedBase {
91
+ constructor(common, og) {
92
+ super(common, og, og.apiName, "./ontology/interfaces");
93
+ this.og = og;
94
+ }
95
+ getDefinitionIdentifier(v2) {
96
+ return v2 ? this.shortApiName : `${this.shortApiName}Def`;
97
+ }
98
+ getImportedDefinitionIdentifier(v2) {
99
+ return this.getDefinitionIdentifier(v2);
100
+ }
101
+ get properties() {
102
+ return this.og.properties;
103
+ }
104
+ getCleanedUpDefinition(v2) {
105
+ return deleteUndefineds(__UNSTABLE_wireInterfaceTypeV2ToSdkObjectDefinition(this.og, v2));
106
+ }
20
107
  };
21
- function stringify(obj, customizer = {}, separator = ",\n") {
22
- const defaultKeyFormatter = (key) => `${JSON.stringify(key)}`;
23
- const entries = [];
24
- const sortedKeys = Object.keys(obj).sort((a, b) => a.localeCompare(b));
25
- for (const key of sortedKeys) {
26
- const value = obj[key];
27
- const res = (customizer[key] ?? customizer["*"] ?? defaultCustomizer)(value, (value2) => JSON.stringify(value2, null, 2), key, defaultKeyFormatter);
28
- if (res) {
29
- if (typeof res === "string") {
30
- entries.push(`${defaultKeyFormatter(key)}: ${res}`);
31
- } else {
32
- entries.push(`${res[0]}: ${res[1]}`);
33
- }
34
- }
108
+ var EnhancedObjectType = class extends EnhancedBase {
109
+ constructor(common, og) {
110
+ super(common, og, og.objectType.apiName, "./ontology/objects");
111
+ this.og = og;
35
112
  }
36
- return entries.join(separator);
37
- }
38
- function formatTs(contents) {
39
- return format(contents, {
40
- parser: "typescript",
41
- singleQuote: true,
42
- trailingComma: "all",
43
- plugins: [organizeImports],
44
- tabWidth: 2,
45
- printWidth: 120
46
- });
47
- }
113
+ getDefinitionIdentifier(v2) {
114
+ return v2 ? `${this.shortApiName}` : `${this.shortApiName}Def`;
115
+ }
116
+ getImportedDefinitionIdentifier(v2) {
117
+ return this.getDefinitionIdentifier(v2);
118
+ }
119
+ getCleanedUpDefinition(v2) {
120
+ return deleteUndefineds(wireObjectTypeFullMetadataToSdkObjectTypeDefinition(this.og, v2));
121
+ }
122
+ };
48
123
 
49
- // src/util/reservedKeywords.ts
50
- var reservedKeywords = /* @__PURE__ */ new Set(["break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"]);
51
- function isReservedKeyword(name) {
52
- return reservedKeywords.has(name);
53
- }
124
+ // src/GenerateContext/EnhancedQuery.ts
125
+ var EnhancedQuery = class extends EnhancedBase {
126
+ constructor(common, og) {
127
+ super(common, og, og.apiName, "./ontology/queries");
128
+ this.og = og;
129
+ }
130
+ get description() {
131
+ return this.og.description;
132
+ }
133
+ get parameters() {
134
+ return this.og.parameters;
135
+ }
136
+ get output() {
137
+ return this.og.output;
138
+ }
139
+ get paramsIdentifier() {
140
+ return `${this.shortApiName}.Parameters`;
141
+ }
142
+ get definitionIdentifier() {
143
+ return `${this.shortApiName}.Definition`;
144
+ }
145
+ get definitionParamsIdentifier() {
146
+ return `${this.definitionIdentifier}$Params`;
147
+ }
148
+ };
54
149
 
55
- // src/v1.1/wireObjectTypeV2ToV1ObjectInterfaceString.ts
56
- function wireObjectTypeV2ToObjectInterfaceStringV1(objectTypeWithLinks, importExt = "") {
57
- const uniqueLinkTargets = new Set(objectTypeWithLinks.linkTypes.map((a) => a.objectTypeApiName).filter((a) => a !== objectTypeWithLinks.objectType.apiName));
58
- return `import type { OntologyObject, LocalDate, Timestamp, GeoShape, GeoPoint, Attachment, TimeSeries, MultiLink, SingleLink, StringLong } from "@osdk/legacy-client";
59
- ${Array.from(uniqueLinkTargets).map((linkTarget) => `import type { ${linkTarget} } from "./${linkTarget}${importExt}";`).join("\n")}
150
+ // src/GenerateContext/EnhancedSharedPropertyType.ts
151
+ var EnhancedSharedPropertyType = class extends EnhancedBase {
152
+ constructor(common, og) {
153
+ super(common, og, og.apiName, "./ontology/interfaces");
154
+ this.og = og;
155
+ }
156
+ };
60
157
 
61
- ${getDescriptionIfPresent(objectTypeWithLinks.objectType.description)}
62
- export interface ${objectTypeWithLinks.objectType.apiName} extends OntologyObject {
63
- /** @deprecated please migrate to $apiName instead */
64
- readonly __apiName: "${objectTypeWithLinks.objectType.apiName}" & {${objectTypeWithLinks.linkTypes.map((linkType) => {
65
- return `/** @deprecated please migrate to pivotTo(${linkType.apiName}) instead */ searchAround${linkType.apiName.charAt(0).toUpperCase() + linkType.apiName.slice(1)}?: never`;
66
- })}};
67
- /** @deprecated please migrate to $primaryKey instead */
68
- readonly __primaryKey: ${wirePropertyTypeV2ToTypeScriptType(objectTypeWithLinks.objectType.properties[objectTypeWithLinks.objectType.primaryKey].dataType)};
69
- readonly $apiName: "${objectTypeWithLinks.objectType.apiName}";
70
- readonly $primaryKey: ${wirePropertyTypeV2ToTypeScriptType(objectTypeWithLinks.objectType.properties[objectTypeWithLinks.objectType.primaryKey].dataType)};
71
- ${Object.entries(objectTypeWithLinks.objectType.properties).sort((a, b) => a[0].localeCompare(b[0])).flatMap(([propertyName, propertyDefinition]) => {
72
- const propertyType = wirePropertyTypeV2ToTypeScriptType(propertyDefinition.dataType);
73
- const entries = [`${getDescriptionIfPresent(propertyDefinition.description, true)}readonly ${propertyName}: ${propertyType} | undefined`];
74
- if (isReservedKeyword(propertyName)) {
75
- entries.push(`/** @deprecated please migrate to '${propertyName}' instead */
76
- readonly ${propertyName}_: ${propertyType} | undefined`);
158
+ // src/GenerateContext/ForeignType.ts
159
+ var ForeignType = class extends AbstractImportable {
160
+ constructor(_common, type, apiNamespace, shortApiName) {
161
+ super(_common, `${apiNamespace}.${shortApiName}`, _common.apiNamespacePackageMap.get(apiNamespace));
162
+ this._common = _common;
163
+ this.type = type;
164
+ }
165
+ getImportedDefinitionIdentifier(v2) {
166
+ return `$Imported$${this.type}$${this.apiNamespace.replace(/\./g, "$")}$${this.shortApiName}`;
167
+ }
168
+ getDefinitionIdentifier(v2) {
169
+ if (this.type === "objectTypes") {
170
+ return v2 ? this.uniqueImportName : `${this.uniqueImportName}Def`;
171
+ } else {
172
+ return this.uniqueImportName;
77
173
  }
78
- return entries;
79
- }).join(";\n")}
80
- ${objectTypeWithLinks.linkTypes.flatMap((linkType) => {
81
- const entries = [`readonly ${linkType.apiName}: ${linkType.cardinality === "MANY" ? "MultiLink" : "SingleLink"}<${linkType.objectTypeApiName}>`];
82
- return entries;
83
- }).join(";\n")}
174
+ }
175
+ };
176
+
177
+ // src/GenerateContext/EnhancedOntologyDefinition.ts
178
+ var EnhancedOntologyDefinition = class {
179
+ constructor(original, ontologyApiNamespace, apiNamespacePackageMap, importExt) {
180
+ this.common = {
181
+ apiNamespacePackageMap,
182
+ enhancedOntology: this,
183
+ importExt,
184
+ ontologyApiNamespace
185
+ };
186
+ this.og = original;
187
+ this.ontology = original.ontology;
188
+ this.objectTypes = remap(original.objectTypes, this.common, EnhancedObjectType);
189
+ this.actionTypes = remap(original.actionTypes, this.common, EnhancedAction);
190
+ this.queryTypes = remap(original.queryTypes, this.common, EnhancedQuery);
191
+ this.interfaceTypes = remap(original.interfaceTypes, this.common, EnhancedInterfaceType);
192
+ this.sharedPropertyTypes = remap(original.sharedPropertyTypes, this.common, EnhancedSharedPropertyType);
193
+ }
194
+ #createRequireType = (type) => {
195
+ return (fullApiName, localOnly) => {
196
+ const ret = this[type][fullApiName];
197
+ if (!ret) {
198
+ const [apiNamespace, shortApiName] = extractNamespace(fullApiName);
199
+ if (localOnly || !apiNamespace) {
200
+ throw new Error(`Unable to find ${type}: No entry for '${fullApiName}`);
201
+ }
202
+ if (!this.common.apiNamespacePackageMap.has(apiNamespace)) {
203
+ throw new Error(`Unable to find ${type}: Unknown namespace '${apiNamespace}'`);
204
+ }
205
+ return new ForeignType(this.common, type, apiNamespace, shortApiName);
206
+ }
207
+ return ret;
208
+ };
209
+ };
210
+ requireObjectType = this.#createRequireType("objectTypes");
211
+ requireInterfaceType = this.#createRequireType("interfaceTypes");
212
+ requireActionType = this.#createRequireType("actionTypes");
213
+ requireQueryType = this.#createRequireType("queryTypes");
214
+ requireSharedPropertyType = this.#createRequireType("sharedPropertyTypes");
215
+ };
216
+ function remap(r, common, Constructor) {
217
+ return Object.fromEntries(Object.entries(r ?? {}).map(([fullApiName, v]) => {
218
+ return [fullApiName, new Constructor(common, v)];
219
+ }).sort((a, b) => a[0].localeCompare(b[0])));
84
220
  }
85
- `;
221
+
222
+ // src/GenerateContext/enhanceOntology.ts
223
+ function enhanceOntology(sanitized, ontologyApiNamespace, apiNamespacePackageMap, importExt) {
224
+ return new EnhancedOntologyDefinition(sanitized, ontologyApiNamespace, apiNamespacePackageMap, importExt);
86
225
  }
87
- function wirePropertyTypeV2ToTypeScriptType(property) {
88
- switch (property.type) {
89
- case "string":
90
- return "string";
91
- case "boolean":
92
- return "boolean";
93
- case "array":
94
- return wirePropertyTypeV2ToTypeScriptType(property.subType) + "[]";
95
- case "integer":
96
- return "number";
97
- case "attachment":
98
- return "Attachment";
99
- case "byte":
100
- return "number";
101
- case "date":
102
- return "LocalDate";
103
- case "decimal":
104
- return "string";
105
- case "double":
106
- return "number";
107
- case "float":
108
- return "number";
109
- case "geopoint":
110
- return "GeoPoint";
111
- case "geoshape":
112
- return "GeoShape";
113
- case "long":
114
- return "StringLong";
115
- case "short":
116
- return "number";
117
- case "timestamp":
118
- return "Timestamp";
119
- case "timeseries":
120
- return property.itemType.type === "string" ? `TimeSeries<string>` : `TimeSeries<number>`;
121
- case "marking":
122
- return "string";
123
- default:
124
- throw new Error(`Unknown property type ${property}`);
125
- }
226
+
227
+ // src/shared/sanitizeMetadata.ts
228
+ function sanitizeMetadata(ontology) {
229
+ return {
230
+ ...ontology,
231
+ actionTypes: Object.fromEntries(Object.values(ontology.actionTypes).map((actionType) => {
232
+ return [camelize(actionType.apiName), {
233
+ ...actionType,
234
+ apiName: camelize(actionType.apiName)
235
+ }];
236
+ }))
237
+ };
126
238
  }
127
- function getDescriptionIfPresent(description, includeNewline) {
128
- if (description) {
129
- return `/**
130
- * ${description}
131
- */${includeNewline ? "\n" : ""}`;
239
+ function camelize(name) {
240
+ return name.replace(/-./g, (segment) => segment[1].toUpperCase());
241
+ }
242
+
243
+ // src/util/verifyOutDir.ts
244
+ async function verifyOutDir(outDir, fs2) {
245
+ try {
246
+ const contents = await fs2.readdir(outDir);
247
+ if (contents.length !== 0) {
248
+ throw new Error(`outDir ${outDir} is not empty, please delete its contents and try again`);
249
+ }
250
+ } catch (e) {
251
+ if (e.code === "ENOENT") ; else {
252
+ throw e;
253
+ }
132
254
  }
133
- return "";
134
255
  }
135
256
 
136
257
  // src/shared/getEditedEntities.ts
@@ -152,350 +273,24 @@ function getModifiedEntityTypes(action) {
152
273
  modifiedObjects
153
274
  };
154
275
  }
155
-
156
- // src/shared/wireActionTypeV2ToSdkActionDefinition.ts
157
- function wireActionTypeV2ToSdkActionDefinition(input) {
158
- const modifiedEntityTypes = getModifiedEntityTypes(input);
159
- return {
160
- type: "action",
161
- apiName: input.apiName,
162
- parameters: Object.fromEntries(Object.entries(input.parameters).map(([key, value]) => [key, wireActionParameterV2ToSdkParameterDefinition(value)])),
163
- displayName: input.displayName,
164
- description: input.description,
165
- modifiedEntities: createModifiedEntities(modifiedEntityTypes.addedObjects, modifiedEntityTypes.modifiedObjects)
166
- };
167
- }
168
- function wireActionParameterV2ToSdkParameterDefinition(value) {
169
- return {
170
- multiplicity: value.dataType.type === "array",
171
- type: actionPropertyToSdkPropertyDefinition(value.dataType.type === "array" ? value.dataType.subType : value.dataType),
172
- nullable: !value.required,
173
- description: value.description
174
- };
175
- }
176
- function actionPropertyToSdkPropertyDefinition(parameterType) {
177
- switch (parameterType.type) {
178
- case "string":
179
- case "boolean":
180
- case "attachment":
181
- case "double":
182
- case "integer":
183
- case "long":
184
- case "timestamp":
185
- case "marking":
186
- return parameterType.type;
187
- case "date":
188
- return "datetime";
189
- case "objectSet":
190
- return {
191
- type: "objectSet",
192
- objectSet: parameterType.objectTypeApiName
193
- };
194
- case "object":
195
- return {
196
- type: "object",
197
- object: parameterType.objectTypeApiName
198
- };
199
- case "array":
200
- return actionPropertyToSdkPropertyDefinition(parameterType.subType);
201
- }
202
- }
203
- function createModifiedEntities(addedObjects, modifiedObjects) {
204
- let entities = {};
205
- for (const key of addedObjects) {
206
- entities[key] = {
207
- created: true,
208
- modified: false
209
- };
210
- }
211
- for (const key of modifiedObjects) {
212
- if (entities[key]) {
213
- entities[key].modified = true;
214
- } else {
215
- entities[key] = {
216
- created: false,
217
- modified: true
218
- };
219
- }
276
+ function formatTs(contents) {
277
+ try {
278
+ return format(contents, {
279
+ parser: "typescript",
280
+ singleQuote: true,
281
+ trailingComma: "all",
282
+ plugins: [organizeImports],
283
+ tabWidth: 2,
284
+ printWidth: 120
285
+ });
286
+ } catch (e) {
287
+ console.error("Failed to format file", e);
288
+ console.log(contents);
289
+ return contents;
220
290
  }
221
- return entities;
222
291
  }
223
292
 
224
- // src/shared/propertyJsdoc.ts
225
- function propertyJsdoc(property, {
226
- isInherited,
227
- apiName
228
- }) {
229
- let ret = `/**
230
- `;
231
- const renderDisplayName = property.displayName && property.displayName !== apiName;
232
- if (isInherited || renderDisplayName || property.description) {
233
- if (isInherited) {
234
- ret += ` * (inherited from parent)
235
- `;
236
- }
237
- if (renderDisplayName) {
238
- ret += ` * display name: '${property.displayName}'${property.description ? "," : ""}
239
- `;
240
- }
241
- if (property.description) {
242
- ret += ` * description: ${property.description}
243
- `;
244
- }
245
- } else {
246
- ret += ` * (no ontology metadata)
247
- `;
248
- }
249
- ret += ` */
250
- `;
251
- return ret;
252
- }
253
-
254
- // src/shared/wireObjectTypeV2ToSdkObjectConst.ts
255
- function getObjectDefIdentifier(name, v2) {
256
- return v2 ? name : `${name}Def`;
257
- }
258
- function wireObjectTypeV2ToSdkObjectConst(object, importExt, v2 = false) {
259
- const uniqueLinkTargetTypes = new Set(object.linkTypes.map((a) => a.objectTypeApiName));
260
- const definition = deleteUndefineds(wireObjectTypeFullMetadataToSdkObjectTypeDefinition(object, v2));
261
- const objectDefIdentifier = getObjectDefIdentifier(object.objectType.apiName, v2);
262
- function getV1Types() {
263
- return `
264
- export interface ${objectDefIdentifier} extends ObjectTypeDefinition<"${object.objectType.apiName}", ${object.objectType.apiName}> {
265
- ${stringify(definition, {
266
- osdkMetadata: () => void 0,
267
- // not used in v1
268
- links: (_value) => `{
269
- ${stringify(definition.links, {
270
- "*": (definition2) => `ObjectTypeLinkDefinition<${getObjectDefIdentifier(definition2.targetType, v2)}, ${definition2.multiplicity}>`
271
- })}
272
- }`
273
- })}
274
- }
275
- `;
276
- }
277
- function getV2Types() {
278
- return `
279
- export interface ${objectDefIdentifier} extends ObjectTypeDefinition<"${object.objectType.apiName}", ${object.objectType.apiName}>, VersionBound<$ExpectedClientVersion> {
280
- osdkMetadata: typeof $osdkMetadata;
281
- ${stringify(definition, {
282
- osdkMetadata: () => void 0,
283
- // we are going to reference another object instead
284
- type: () => void 0,
285
- apiName: () => void 0,
286
- links: (_value) => `{
287
- ${stringify(definition.links, {
288
- "*": (definition2) => `ObjectTypeLinkDefinition<${getObjectDefIdentifier(definition2.targetType, v2)}, ${definition2.multiplicity}>`
289
- })}
290
- }`,
291
- properties: (_value) => `{
292
- ${stringify(definition.properties, {
293
- "*": (propertyDefinition, _, apiName) => [`${propertyJsdoc(propertyDefinition, {
294
- apiName
295
- })}${apiName}`, `PropertyDef<"${propertyDefinition.type}", "${propertyDefinition.nullable ? "nullable" : "non-nullable"}", "${propertyDefinition.multiplicity ? "array" : "single"}">`]
296
- })}
297
- }`
298
- })}
299
-
300
- }
301
-
302
- `;
303
- }
304
- const imports = Array.from(uniqueLinkTargetTypes).filter((type) => type !== definition.apiName).map((type) => `import type { ${getObjectDefIdentifier(type, v2)} } from "./${type}${importExt}";`);
305
- return `${imports.join("\n")}
306
-
307
- ${v2 ? getV2Types() : getV1Types()}
308
-
309
- export const ${object.objectType.apiName}: ${objectDefIdentifier} = {
310
- ${v2 ? `osdkMetadata: $osdkMetadata,` : ""}
311
- ${stringify(definition, {
312
- osdkMetadata: (value) => void 0
313
- })}
314
-
315
- };`;
316
- }
317
-
318
- // src/shared/generatePerActionDataFiles.ts
319
- async function generatePerActionDataFiles(ontology, fs2, outDir, importExt, v2) {
320
- await fs2.mkdir(outDir, {
321
- recursive: true
322
- });
323
- await Promise.all(Object.values(ontology.actionTypes).map(async (action) => {
324
- const uniqueApiNames = new Set(extractReferencedObjectsFromAction(action));
325
- const uniqueApiNamesString = uniqueApiNames.size > 0 ? [...uniqueApiNames].map((apiName) => `"${apiName}"`).join("|") : "never";
326
- const fullActionDef = deleteUndefineds(wireActionTypeV2ToSdkActionDefinition(action));
327
- const {
328
- parameters,
329
- ...actionDefSansParameters
330
- } = fullActionDef;
331
- const actionDefIdentifier = `ActionDef$${action.apiName}`;
332
- const paramsDefIdentifier = `${actionDefIdentifier}$Params`;
333
- const paramsIdentifier = `${action.apiName}$Params`;
334
- function createParamsDef() {
335
- const entries = Object.entries(parameters);
336
- entries.sort((a, b) => a[0].localeCompare(b[0]));
337
- if (entries.length === 0) {
338
- return `// Represents the definition of the parameters for the action
339
- export type ${paramsDefIdentifier} = Record<string, never>;`;
340
- }
341
- return `// Represents the definition of the parameters for the action
342
- export type ${paramsDefIdentifier} = {
343
- ${entries.map(([key, value]) => {
344
- return `"${key}": {
345
- ${stringify(value, {
346
- description: (value2, d) => value2 ? d(value2) : void 0,
347
- // trick to remove undefineds
348
- type: (type) => {
349
- if (typeof type === "string") {
350
- return JSON.stringify(type);
351
- } else if (type.type === "object") {
352
- return `ObjectActionDataType<"${type.object}", ${getObjectDefIdentifier(type.object, v2)}>`;
353
- } else if (type.type === "objectSet") {
354
- return `ObjectSetActionDataType<"${type.objectSet}", ${getObjectDefIdentifier(type.objectSet, v2)}>`;
355
- }
356
- return void 0;
357
- }
358
- })}
359
- }`;
360
- }).join(";\n")}
361
- }`;
362
- }
363
- function createV2Types() {
364
- return `
365
-
366
- ${createParamsDef()}
367
-
368
-
369
- // Represents the runtime arguments for the action
370
- export type ${paramsIdentifier} = NOOP<OsdkActionParameters<${paramsDefIdentifier}>> | NOOP<OsdkActionParameters<${paramsDefIdentifier}>>[];
371
-
372
-
373
- // Represents a fqn of the action
374
- export interface ${action.apiName} {
375
- ${getDescriptionIfPresent(action.description)}
376
- <P extends ${paramsIdentifier}, OP extends P extends NOOP<OsdkActionParameters<${paramsDefIdentifier}>>[]? ApplyBatchActionOptions: ApplyActionOptions>(args: P, options?: OP): Promise<ActionReturnTypeForOptions<OP>>;
377
- }
378
-
379
-
380
- // Represents the definition of the action
381
- export interface ${actionDefIdentifier} extends ActionDefinition<"${action.apiName}", ${uniqueApiNamesString}, ${action.apiName}>, VersionBound<$ExpectedClientVersion> {
382
- ${Object.entries(actionDefSansParameters).sort((a, b) => a[0].localeCompare(b[0])).map(([key, value]) => {
383
- return `${key}: ${JSON.stringify(value)};`;
384
- }).join("\n")}
385
- parameters: ${paramsDefIdentifier};
386
- osdkMetadata: typeof $osdkMetadata;
387
- }`;
388
- }
389
- function createV2Object() {
390
- return ` export const ${action.apiName}: ${actionDefIdentifier} =
391
- {
392
- ${stringify(fullActionDef)},
393
- osdkMetadata: $osdkMetadata
394
- }
395
- `;
396
- }
397
- function createV1Object() {
398
- return ` export const ${action.apiName} = ${JSON.stringify(fullActionDef, null, 2)} satisfies ActionDefinition<"${action.apiName}", ${uniqueApiNamesString}>;`;
399
- }
400
- const referencedObjectDefs = /* @__PURE__ */ new Set();
401
- for (const p of Object.values(action.parameters)) {
402
- if (p.dataType.type === "object" || p.dataType.type === "objectSet") {
403
- referencedObjectDefs.add(getObjectDefIdentifier(p.dataType.objectApiName, v2));
404
- referencedObjectDefs.add(getObjectDefIdentifier(p.dataType.objectTypeApiName, v2));
405
- }
406
- if (p.dataType.type === "array" && (p.dataType.subType.type === "object" || p.dataType.subType.type === "objectSet")) {
407
- referencedObjectDefs.add(getObjectDefIdentifier(p.dataType.subType.objectApiName, v2));
408
- referencedObjectDefs.add(getObjectDefIdentifier(p.dataType.subType.objectTypeApiName, v2));
409
- }
410
- }
411
- const importObjects = referencedObjectDefs.size > 0 ? `import type {${[...referencedObjectDefs].join(",")}} from "../objects${importExt}";` : "";
412
- await fs2.writeFile(path16__default.join(outDir, `${action.apiName}.ts`), await formatTs(`
413
- import type { ActionDefinition, ObjectActionDataType, ObjectSetActionDataType, VersionBound} from "@osdk/api";
414
- import type { ActionSignature, ApplyActionOptions, ApplyBatchActionOptions, OsdkActionParameters,ActionReturnTypeForOptions, NOOP } from '@osdk/client.api';
415
- import { $osdkMetadata} from "../../OntologyMetadata${importExt}";
416
- import type { $ExpectedClientVersion } from "../../OntologyMetadata${importExt}";
417
- ${importObjects}
418
-
419
-
420
- ${v2 ? createV2Types() : ""}
421
-
422
- ${v2 ? createV2Object() : createV1Object()}
423
- `));
424
- }));
425
- await fs2.writeFile(path16__default.join(outDir, `index.ts`), await formatTs(`
426
- ${Object.values(ontology.actionTypes).map((action) => `export {${action.apiName}} from "./${action.apiName}${importExt}";`).join("\n")}
427
- ${Object.keys(ontology.actionTypes).length === 0 ? "export {};" : ""}
428
- `));
429
- }
430
- function extractReferencedObjectsFromAction(actionType) {
431
- const referencedObjectsInParameters = Object.values(actionType.parameters).flatMap(({
432
- dataType
433
- }) => {
434
- const objectTypeReference = extractReferencedObjectsFromActionParameter(dataType);
435
- return objectTypeReference ? [objectTypeReference] : [];
436
- });
437
- const referenceObjectsInEdits = actionType.operations.flatMap((value) => {
438
- switch (value.type) {
439
- case "createObject":
440
- return [value.objectTypeApiName];
441
- case "modifyObject":
442
- return [value.objectTypeApiName];
443
- case "deleteObject":
444
- case "createLink":
445
- case "deleteLink":
446
- return [];
447
- }
448
- });
449
- return [...referenceObjectsInEdits, ...referencedObjectsInParameters];
450
- }
451
- function extractReferencedObjectsFromActionParameter(actionParameter) {
452
- switch (actionParameter.type) {
453
- case "objectSet":
454
- case "object":
455
- return actionParameter.objectTypeApiName;
456
- case "array":
457
- return extractReferencedObjectsFromActionParameter(actionParameter.subType);
458
- case "string":
459
- case "boolean":
460
- case "attachment":
461
- case "date":
462
- case "double":
463
- case "integer":
464
- case "long":
465
- case "timestamp":
466
- return void 0;
467
- }
468
- }
469
-
470
- // src/shared/sanitizeMetadata.ts
471
- function sanitizeMetadata(ontology) {
472
- return {
473
- ...ontology,
474
- actionTypes: Object.fromEntries(Object.values(ontology.actionTypes).map((actionType) => {
475
- return [camelize(actionType.apiName), {
476
- ...actionType,
477
- apiName: camelize(actionType.apiName)
478
- }];
479
- }))
480
- };
481
- }
482
- function camelize(name) {
483
- return name.replace(/-./g, (segment) => segment[1].toUpperCase());
484
- }
485
-
486
- // src/util/verifyOutDir.ts
487
- async function verifyOutDir(outDir, fs2) {
488
- try {
489
- const contents = await fs2.readdir(outDir);
490
- if (contents.length !== 0) {
491
- throw new Error(`outDir ${outDir} is not empty, please delete its contents and try again`);
492
- }
493
- } catch (e) {
494
- if (e.code === "ENOENT") ; else {
495
- throw e;
496
- }
497
- }
498
- }
293
+ // src/v1.1/generateActions.ts
499
294
  async function generateActions(ontology, fs2, outDir, importExt = "") {
500
295
  const importedObjects = /* @__PURE__ */ new Set();
501
296
  let actionSignatures = [];
@@ -1242,455 +1037,1497 @@ async function generateOntologyIndexFile(fs2, outDir) {
1242
1037
  export type { ObjectSet } from "@osdk/legacy-client";
1243
1038
  `));
1244
1039
  }
1245
- async function generatePerObjectInterfaceAndDataFiles(ontology, fs2, outDir, importExt = "") {
1246
- await fs2.mkdir(outDir, {
1247
- recursive: true
1248
- });
1249
- await Promise.all(Object.values(ontology.objectTypes).map(async (object) => {
1250
- object.linkTypes;
1251
- await fs2.writeFile(path16__default.join(outDir, `${object.objectType.apiName}.ts`), await formatTs(`
1252
- import type { ObjectTypeDefinition, ObjectTypeLinkDefinition, PropertyDef } from "@osdk/api";
1253
- ${wireObjectTypeV2ToObjectInterfaceStringV1(object, importExt)}
1254
-
1255
- ${wireObjectTypeV2ToSdkObjectConst(object, importExt)}
1256
- `));
1257
- }));
1258
- await fs2.writeFile(path16__default.join(outDir, "index.ts"), await formatTs(`
1259
- ${Object.keys(ontology.objectTypes).map((apiName) => `export * from "./${apiName}${importExt}";`).join("\n")}
1260
- export type { ObjectSet } from "@osdk/legacy-client";
1261
1040
 
1262
- `));
1041
+ // src/shared/getObjectImports.ts
1042
+ function getObjectImports(objects, curApiName, currentFilePath, v2) {
1043
+ return Array.from(objects).filter((obj) => obj.fullApiName !== curApiName).map((obj) => {
1044
+ return `import type { ${obj.getDefinitionIdentifier(v2)} as ${obj.getImportedDefinitionIdentifier(v2)} } from "${obj.getImportPathRelTo("./" + currentFilePath)}";`;
1045
+ }).join("\n");
1263
1046
  }
1264
1047
 
1265
- // src/shared/isNullableQueryDataType.ts
1266
- function isNullableQueryDataType(input) {
1267
- if (input.type === "null") {
1268
- return true;
1269
- }
1270
- if (input.type === "union") {
1271
- return input.unionTypes.some((t) => isNullableQueryDataType(t));
1272
- }
1273
- return false;
1048
+ // src/shared/wireActionTypeV2ToSdkActionDefinition.ts
1049
+ function wireActionTypeV2ToSdkActionDefinition(input) {
1050
+ const modifiedEntityTypes = getModifiedEntityTypes(input);
1051
+ return {
1052
+ type: "action",
1053
+ apiName: input.apiName,
1054
+ parameters: Object.fromEntries(Object.entries(input.parameters).map(([key, value]) => [key, wireActionParameterV2ToSdkParameterDefinition(value)])),
1055
+ displayName: input.displayName,
1056
+ description: input.description,
1057
+ modifiedEntities: createModifiedEntities(modifiedEntityTypes.addedObjects, modifiedEntityTypes.modifiedObjects)
1058
+ };
1274
1059
  }
1275
-
1276
- // src/shared/wireQueryDataTypeToQueryDataTypeDefinition.ts
1277
- function wireQueryDataTypeToQueryDataTypeDefinition(input) {
1278
- switch (input.type) {
1279
- case "double":
1280
- case "float":
1281
- case "integer":
1282
- case "long":
1283
- case "attachment":
1284
- case "boolean":
1285
- case "date":
1286
- case "string":
1287
- case "timestamp":
1288
- return {
1289
- type: input.type,
1290
- nullable: false
1291
- };
1292
- case "object":
1293
- return {
1294
- type: "object",
1295
- object: input.objectTypeApiName,
1296
- nullable: false
1297
- };
1060
+ function wireActionParameterV2ToSdkParameterDefinition(value) {
1061
+ return {
1062
+ multiplicity: value.dataType.type === "array",
1063
+ type: actionPropertyToSdkPropertyDefinition(value.dataType.type === "array" ? value.dataType.subType : value.dataType),
1064
+ nullable: !value.required,
1065
+ description: value.description
1066
+ };
1067
+ }
1068
+ function actionPropertyToSdkPropertyDefinition(parameterType) {
1069
+ switch (parameterType.type) {
1070
+ case "string":
1071
+ case "boolean":
1072
+ case "attachment":
1073
+ case "double":
1074
+ case "integer":
1075
+ case "long":
1076
+ case "timestamp":
1077
+ case "marking":
1078
+ return parameterType.type;
1079
+ case "date":
1080
+ return "datetime";
1298
1081
  case "objectSet":
1299
1082
  return {
1300
1083
  type: "objectSet",
1301
- objectSet: input.objectTypeApiName,
1302
- nullable: false
1303
- };
1304
- case "array":
1305
- return {
1306
- ...wireQueryDataTypeToQueryDataTypeDefinition(input.subType),
1307
- multiplicity: true
1308
- };
1309
- case "set":
1310
- return {
1311
- type: "set",
1312
- set: wireQueryDataTypeToQueryDataTypeDefinition(input.subType),
1313
- nullable: false
1314
- };
1315
- case "union":
1316
- const allowNulls = isNullableQueryDataType(input);
1317
- if (allowNulls && input.unionTypes.length === 2) {
1318
- const nonNull = input.unionTypes.find((t) => t.type != null);
1319
- if (nonNull) {
1320
- return {
1321
- ...wireQueryDataTypeToQueryDataTypeDefinition(nonNull),
1322
- nullable: true
1323
- };
1324
- }
1325
- }
1326
- return {
1327
- type: "union",
1328
- union: input.unionTypes.reduce((acc, t) => {
1329
- if (t.type === "null") {
1330
- return acc;
1331
- }
1332
- acc.push(wireQueryDataTypeToQueryDataTypeDefinition(t));
1333
- return acc;
1334
- }, []),
1335
- nullable: allowNulls
1336
- };
1337
- case "struct":
1338
- return {
1339
- type: "struct",
1340
- struct: Object.fromEntries(input.fields.map((f) => [f.name, wireQueryDataTypeToQueryDataTypeDefinition(f.fieldType)])),
1341
- nullable: false
1342
- };
1343
- case "twoDimensionalAggregation":
1344
- return {
1345
- type: "twoDimensionalAggregation",
1346
- twoDimensionalAggregation: get2DQueryAggregationProps(input),
1347
- nullable: false
1084
+ objectSet: parameterType.objectTypeApiName
1348
1085
  };
1349
- case "threeDimensionalAggregation":
1086
+ case "object":
1350
1087
  return {
1351
- type: "threeDimensionalAggregation",
1352
- threeDimensionalAggregation: get3DQueryAggregationProps(input),
1353
- nullable: false
1088
+ type: "object",
1089
+ object: parameterType.objectTypeApiName
1354
1090
  };
1355
- case "null":
1356
- case "unsupported":
1357
- throw new Error(`Accidentally tried to handle QueryDataType.type ${input.type}`);
1358
- default:
1359
- throw new Error(`Unsupported QueryDataType.type ${input.type}`);
1091
+ case "array":
1092
+ return actionPropertyToSdkPropertyDefinition(parameterType.subType);
1360
1093
  }
1361
1094
  }
1362
- function get2DQueryAggregationProps(input) {
1363
- if (input.keyType.type === "range") {
1364
- return {
1365
- keyType: input.keyType.type,
1366
- keySubtype: input.keyType.subType.type,
1367
- valueType: input.valueType.type
1095
+ function createModifiedEntities(addedObjects, modifiedObjects) {
1096
+ let entities = {};
1097
+ for (const key of addedObjects) {
1098
+ entities[key] = {
1099
+ created: true,
1100
+ modified: false
1368
1101
  };
1369
- } else {
1370
- if (guardInvalidKeyTypes(input.keyType)) {
1371
- return {
1372
- keyType: input.keyType.type,
1373
- valueType: input.valueType.type
1374
- };
1375
- }
1376
- throw new Error(`Cannot create 2D aggregation with ${input.keyType.type} as its type`);
1377
1102
  }
1378
- }
1379
- function get3DQueryAggregationProps(input) {
1380
- if (input.keyType.type === "range") {
1381
- return {
1382
- keyType: input.keyType.type,
1383
- keySubtype: input.keyType.subType.type,
1384
- valueType: get2DQueryAggregationProps(input.valueType)
1385
- };
1386
- } else {
1387
- if (guardInvalidKeyTypes(input.keyType)) {
1388
- return {
1389
- keyType: input.keyType.type,
1390
- valueType: get2DQueryAggregationProps(input.valueType)
1103
+ for (const key of modifiedObjects) {
1104
+ if (entities[key]) {
1105
+ entities[key].modified = true;
1106
+ } else {
1107
+ entities[key] = {
1108
+ created: false,
1109
+ modified: true
1391
1110
  };
1392
1111
  }
1393
- throw new Error(`Cannot create 3D aggregation with ${input.keyType.type} as its type`);
1394
1112
  }
1395
- }
1396
- function guardInvalidKeyTypes(key) {
1397
- return key.type === "string" || key.type === "boolean";
1113
+ return entities;
1398
1114
  }
1399
1115
 
1400
- // src/shared/wireQueryTypeV2ToSdkQueryDefinition.ts
1401
- function wireQueryTypeV2ToSdkQueryDefinition(input) {
1402
- return {
1403
- type: "query",
1404
- apiName: input.apiName,
1405
- description: input.description,
1406
- displayName: input.displayName,
1407
- version: input.version,
1408
- parameters: Object.fromEntries(Object.entries(input.parameters).map(([name, parameter]) => [name, wireQueryParameterV2ToQueryParameterDefinition(parameter)])),
1409
- output: wireQueryDataTypeToQueryDataTypeDefinition(input.output)
1410
- };
1411
- }
1412
- function wireQueryTypeV2ToSdkQueryDefinitionNoParams(input) {
1413
- return {
1414
- type: "query",
1415
- apiName: input.apiName,
1416
- description: input.description,
1417
- displayName: input.displayName,
1418
- version: input.version
1419
- };
1420
- }
1421
- function wireQueryParameterV2ToQueryParameterDefinition(parameter) {
1422
- return {
1423
- description: parameter.description,
1424
- ...wireQueryDataTypeToQueryDataTypeDefinition(parameter.dataType)
1425
- };
1116
+ // src/util/stringUnionFrom.ts
1117
+ function stringUnionFrom2(values) {
1118
+ if (values.length === 0) {
1119
+ return "never";
1120
+ } else {
1121
+ return values.map((v) => `"${v}"`).join("|");
1122
+ }
1426
1123
  }
1427
1124
 
1428
- // src/v1.1/generatePerQueryDataFiles.ts
1429
- async function generatePerQueryDataFiles(ontology, fs2, outDir, importExt = "", v2 = false) {
1125
+ // src/v1.1/generatePerActionDataFilesV1.ts
1126
+ async function generatePerActionDataFilesV1({
1127
+ sanitizedOntology: ontology,
1128
+ fs: fs2,
1129
+ outDir: rootOutDir,
1130
+ importExt = "",
1131
+ ontology: enhancedOntology
1132
+ }) {
1133
+ const outDir = path16__default.join(rootOutDir, "ontology", "actions");
1430
1134
  await fs2.mkdir(outDir, {
1431
1135
  recursive: true
1432
1136
  });
1433
- await Promise.all(Object.values(ontology.queryTypes).map(async (query) => {
1434
- const objectTypes = getObjectTypesFromQuery(query);
1435
- const importObjects = objectTypes.length > 0 ? `import {${[...objectTypes].join(",")}} from "../objects${importExt}";` : "";
1436
- if (v2) {
1437
- await fs2.writeFile(path16__default.join(outDir, `${query.apiName}.ts`), await formatTs(`
1438
- import { QueryDefinition } from "@osdk/api";
1439
- ${importObjects}
1440
- export const ${query.apiName} = {
1441
- ${stringify(deleteUndefineds(wireQueryTypeV2ToSdkQueryDefinitionNoParams(query)))},
1442
- parameters: {${Object.entries(query.parameters).map(([name, parameter]) => {
1443
- return `${name} : {${stringify(deleteUndefineds(wireQueryParameterV2ToQueryParameterDefinition(parameter)))},
1444
- ${parameter.dataType.type === "object" || parameter.dataType.type === "objectSet" ? getOsdkTargetTypeIfPresent(parameter.dataType.objectTypeApiName, v2) : ``}}`;
1445
- })}},
1446
- output: {${stringify(deleteUndefineds(wireQueryDataTypeToQueryDataTypeDefinition(query.output)))},
1447
- ${query.output.type === "object" || query.output.type === "objectSet" ? getOsdkTargetTypeIfPresent(query.output.objectTypeApiName, v2) : ``}}
1448
- } ${getQueryDefSatisfies(query.apiName, objectTypes)}`));
1449
- } else {
1450
- await fs2.writeFile(path16__default.join(outDir, `${query.apiName}.ts`), await formatTs(`
1451
- import { QueryDefinition } from "@osdk/api";
1452
-
1453
- export const ${query.apiName} = ${JSON.stringify(wireQueryTypeV2ToSdkQueryDefinition(query))} ${getQueryDefSatisfies(query.apiName, objectTypes)}`));
1137
+ await Promise.all(Object.values(enhancedOntology.actionTypes).map(async (action) => {
1138
+ const currentFilePath = `${path16__default.join("ontology", "actions", `${action.shortApiName}.ts`)}`;
1139
+ const uniqueApiNamesArray = extractReferencedObjectsFromAction(action.og);
1140
+ const uniqueApiNames = new Set(uniqueApiNamesArray);
1141
+ const uniqueApiNamesString = stringUnionFrom2([...uniqueApiNames]);
1142
+ const fullActionDef = deleteUndefineds(wireActionTypeV2ToSdkActionDefinition(action.og));
1143
+ function createV1Object() {
1144
+ return ` export const ${action.shortApiName} = ${JSON.stringify(fullActionDef, null, 2)} satisfies ActionDefinition<"${action.shortApiName}", ${uniqueApiNamesString}>;`;
1145
+ }
1146
+ const referencedObjectDefs = /* @__PURE__ */ new Set();
1147
+ for (const p of Object.values(action.parameters)) {
1148
+ if (p.dataType.type === "object" || p.dataType.type === "objectSet") {
1149
+ if (p.dataType.objectApiName) {
1150
+ referencedObjectDefs.add(enhancedOntology.requireObjectType(p.dataType.objectApiName));
1151
+ }
1152
+ if (p.dataType.objectTypeApiName) {
1153
+ referencedObjectDefs.add(enhancedOntology.requireObjectType(p.dataType.objectTypeApiName));
1154
+ }
1155
+ }
1156
+ if (p.dataType.type === "array" && (p.dataType.subType.type === "object" || p.dataType.subType.type === "objectSet")) {
1157
+ if (p.dataType.subType.objectApiName) {
1158
+ referencedObjectDefs.add(enhancedOntology.requireObjectType(p.dataType.subType.objectApiName));
1159
+ }
1160
+ if (p.dataType.subType.objectTypeApiName) {
1161
+ referencedObjectDefs.add(enhancedOntology.requireObjectType(p.dataType.subType.objectTypeApiName));
1162
+ }
1163
+ }
1454
1164
  }
1165
+ const imports = getObjectImports(referencedObjectDefs, void 0, currentFilePath, false);
1166
+ await fs2.writeFile(path16__default.join(rootOutDir, currentFilePath), await formatTs(`
1167
+ import type { ActionDefinition, ObjectActionDataType, ObjectSetActionDataType, VersionBound} from "@osdk/api";
1168
+ import type { ApplyActionOptions, ApplyBatchActionOptions, ActionReturnTypeForOptions, ActionParam } from '@osdk/client.api';
1169
+ import { $osdkMetadata} from "../../OntologyMetadata${importExt}";
1170
+ import type { $ExpectedClientVersion } from "../../OntologyMetadata${importExt}";
1171
+ ${imports}
1172
+
1173
+ ${createV1Object()}
1174
+ `));
1455
1175
  }));
1456
- await fs2.writeFile(path16__default.join(outDir, "index.ts"), await formatTs(`
1457
- ${Object.values(ontology.queryTypes).map((query) => `export * from "./${query.apiName}${importExt}";`).join("\n")}
1458
- ${Object.keys(ontology.queryTypes).length === 0 ? "export {};" : ""}
1459
- `));
1176
+ const indexFileRelPath = path16__default.join("ontology", "actions", `index.ts`);
1177
+ await fs2.writeFile(path16__default.join(rootOutDir, indexFileRelPath), await formatTs(`
1178
+ ${Object.values(enhancedOntology.actionTypes).map((action) => {
1179
+ const exportConstLine = `export {${action.shortApiName} } from "${action.getImportPathRelTo(indexFileRelPath)}";`;
1180
+ `export type { ${action.paramsIdentifier} } from "${action.getImportPathRelTo(indexFileRelPath)}";`;
1181
+ return exportConstLine;
1182
+ }).join("\n")}
1183
+ ${Object.keys(ontology.actionTypes).length === 0 ? "export {};" : ""}
1184
+ `));
1460
1185
  }
1461
- function getObjectTypesFromQuery(query) {
1462
- const types = /* @__PURE__ */ new Set();
1463
- for (const {
1186
+ function extractReferencedObjectsFromAction(actionType) {
1187
+ const referencedObjectsInParameters = Object.values(actionType.parameters).flatMap(({
1464
1188
  dataType
1465
- } of Object.values(query.parameters)) {
1466
- getObjectTypesFromDataType(dataType, types);
1467
- }
1468
- getObjectTypesFromDataType(query.output, types);
1469
- return Array.from(types);
1189
+ }) => {
1190
+ const objectTypeReference = extractReferencedObjectsFromActionParameter(dataType);
1191
+ return objectTypeReference ? [objectTypeReference] : [];
1192
+ });
1193
+ const referenceObjectsInEdits = actionType.operations.flatMap((value) => {
1194
+ switch (value.type) {
1195
+ case "createObject":
1196
+ return [value.objectTypeApiName];
1197
+ case "modifyObject":
1198
+ return [value.objectTypeApiName];
1199
+ case "deleteObject":
1200
+ case "createLink":
1201
+ case "deleteLink":
1202
+ return [];
1203
+ }
1204
+ });
1205
+ return [...referenceObjectsInEdits, ...referencedObjectsInParameters];
1470
1206
  }
1471
- function getObjectTypesFromDataType(dataType, types) {
1472
- switch (dataType.type) {
1473
- case "array":
1474
- case "set":
1475
- getObjectTypesFromDataType(dataType.subType, types);
1476
- return;
1477
- case "object":
1478
- types.add(dataType.objectTypeApiName);
1479
- return;
1207
+ function extractReferencedObjectsFromActionParameter(actionParameter) {
1208
+ switch (actionParameter.type) {
1480
1209
  case "objectSet":
1481
- types.add(dataType.objectTypeApiName);
1482
- return;
1483
- case "struct":
1484
- for (const prop of Object.values(dataType.fields)) {
1485
- getObjectTypesFromDataType(prop.fieldType, types);
1486
- }
1487
- return;
1488
- case "union":
1489
- for (const type of dataType.unionTypes) {
1490
- getObjectTypesFromDataType(type, types);
1491
- }
1492
- return;
1493
- case "attachment":
1210
+ case "object":
1211
+ return actionParameter.objectTypeApiName;
1212
+ case "array":
1213
+ return extractReferencedObjectsFromActionParameter(actionParameter.subType);
1214
+ case "string":
1494
1215
  case "boolean":
1216
+ case "attachment":
1495
1217
  case "date":
1496
1218
  case "double":
1497
- case "float":
1498
1219
  case "integer":
1499
1220
  case "long":
1500
- case "null":
1501
- case "string":
1502
- case "threeDimensionalAggregation":
1503
1221
  case "timestamp":
1504
- case "twoDimensionalAggregation":
1505
- case "unsupported":
1506
- return;
1507
- default:
1508
- throw new Error(`Cannot find object types from unsupported QueryDataType ${dataType.type}`);
1222
+ return void 0;
1509
1223
  }
1510
1224
  }
1511
- function getQueryDefSatisfies(apiName, objectTypes) {
1512
- return `satisfies QueryDefinition<"${apiName}", ${objectTypes.length > 0 ? objectTypes.map((apiNameObj) => `"${apiNameObj}"`).join("|") : "never"}>;`;
1225
+
1226
+ // src/util/stringify.ts
1227
+ var defaultCustomizer = (value, defaultValueFormatter, key, defaultKeyFormatter) => {
1228
+ return [defaultKeyFormatter(key), defaultValueFormatter(value)];
1229
+ };
1230
+ function stringify(obj, customizer = {}, separator = ",\n") {
1231
+ const defaultKeyFormatter = (key) => `${JSON.stringify(key)}`;
1232
+ const entries = [];
1233
+ const sortedKeys = Object.keys(obj).sort((a, b) => a.localeCompare(b));
1234
+ for (const key of sortedKeys) {
1235
+ const value = obj[key];
1236
+ const res = (customizer[key] ?? customizer["*"] ?? defaultCustomizer)(value, (value2) => JSON.stringify(value2, null, 2), key, defaultKeyFormatter);
1237
+ if (res) {
1238
+ if (typeof res === "string") {
1239
+ entries.push(`${defaultKeyFormatter(key)}: ${res}`);
1240
+ } else {
1241
+ entries.push(`${res[0]}: ${res[1]}`);
1242
+ }
1243
+ }
1244
+ }
1245
+ return entries.join(separator);
1513
1246
  }
1514
- function getOsdkTargetTypeIfPresent(objectTypeApiName, v2) {
1515
- return `
1516
- __OsdkTargetType: ${getObjectDefIdentifier(objectTypeApiName, v2)}
1247
+
1248
+ // src/v1.1/wireObjectTypeV2ToSdkObjectConstV1.ts
1249
+ function wireObjectTypeV2ToSdkObjectConstV1(wireObject, {
1250
+ ontology
1251
+ }, currentFilePath) {
1252
+ const object = ontology.requireObjectType(wireObject.objectType.apiName, true);
1253
+ const uniqueLinkTargetTypes = new Set(wireObject.linkTypes.map((a) => ontology.requireObjectType(a.objectTypeApiName, false)));
1254
+ const definition = deleteUndefineds(wireObjectTypeFullMetadataToSdkObjectTypeDefinition(object.og, false));
1255
+ const objectDefIdentifier = object.getDefinitionIdentifier(false);
1256
+ function getV1Types() {
1257
+ return `
1258
+ export interface ${objectDefIdentifier} extends ObjectTypeDefinition<"${object.fullApiName}", ${object.uniqueImportName}> {
1259
+ ${stringify(definition, {
1260
+ osdkMetadata: () => void 0,
1261
+ // not used in v1
1262
+ links: (_value) => `{
1263
+ ${stringify(definition.links, {
1264
+ "*": (definition2) => `ObjectTypeLinkDefinition<${ontology.requireObjectType(definition2.targetType).getImportedDefinitionIdentifier(false)}, ${definition2.multiplicity}>`
1265
+ })}
1266
+ }`
1267
+ })}
1268
+ }
1517
1269
  `;
1270
+ }
1271
+ const imports = getObjectImports(uniqueLinkTargetTypes, definition.apiName, currentFilePath, false);
1272
+ return `${imports}${getV1Types()}
1273
+
1274
+ export const ${object.shortApiName}: ${objectDefIdentifier} = {
1275
+ ${stringify(definition, {
1276
+ osdkMetadata: (value) => void 0
1277
+ })}
1278
+
1279
+ };`;
1518
1280
  }
1519
- async function generateQueries(ontology, fs2, outDir, importExt = "") {
1520
- const importedObjects = /* @__PURE__ */ new Set();
1521
- const signatures = [];
1522
- for (const query of Object.values(ontology.queryTypes)) {
1523
- const jsDocBlock = ["/**"];
1524
- if (query.description) {
1525
- jsDocBlock.push(`* ${query.description}`);
1526
- }
1527
- const outputType = handleQueryDataType(query.output, importedObjects, true);
1528
- const paramEntries = [];
1529
- for (const [name, parameter] of Object.entries(query.parameters)) {
1530
- const nullable = isNullableQueryDataType(parameter.dataType);
1531
- const type = handleQueryDataType(parameter.dataType, importedObjects, false);
1532
- paramEntries.push(`"${name}"${nullable ? "?" : ""}: ${type}`);
1533
- jsDocBlock.push(`* @param {${sanitizeDocTypeName(type)}} params.${name}${parameter.description ? ` - ${parameter.description}` : ""}`);
1281
+
1282
+ // src/util/reservedKeywords.ts
1283
+ var reservedKeywords = /* @__PURE__ */ new Set(["break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"]);
1284
+ function isReservedKeyword(name) {
1285
+ return reservedKeywords.has(name);
1286
+ }
1287
+
1288
+ // src/v1.1/wireObjectTypeV2ToV1ObjectInterfaceString.ts
1289
+ function wireObjectTypeV2ToObjectInterfaceStringV1(objectTypeWithLinks, importExt = "") {
1290
+ const uniqueLinkTargets = new Set(objectTypeWithLinks.linkTypes.map((a) => a.objectTypeApiName).filter((a) => a !== objectTypeWithLinks.objectType.apiName));
1291
+ return `import type { OntologyObject, LocalDate, Timestamp, GeoShape, GeoPoint, Attachment, TimeSeries, MultiLink, SingleLink, StringLong } from "@osdk/legacy-client";
1292
+ ${Array.from(uniqueLinkTargets).map((linkTarget) => `import type { ${linkTarget} } from "./${linkTarget}${importExt}";`).join("\n")}
1293
+
1294
+ ${getDescriptionIfPresent(objectTypeWithLinks.objectType.description)}
1295
+ export interface ${objectTypeWithLinks.objectType.apiName} extends OntologyObject {
1296
+ /** @deprecated please migrate to $apiName instead */
1297
+ readonly __apiName: "${objectTypeWithLinks.objectType.apiName}" & {${objectTypeWithLinks.linkTypes.map((linkType) => {
1298
+ return `/** @deprecated please migrate to pivotTo(${linkType.apiName}) instead */ searchAround${linkType.apiName.charAt(0).toUpperCase() + linkType.apiName.slice(1)}?: never`;
1299
+ })}};
1300
+ /** @deprecated please migrate to $primaryKey instead */
1301
+ readonly __primaryKey: ${wirePropertyTypeV2ToTypeScriptType(objectTypeWithLinks.objectType.properties[objectTypeWithLinks.objectType.primaryKey].dataType)};
1302
+ readonly $apiName: "${objectTypeWithLinks.objectType.apiName}";
1303
+ readonly $primaryKey: ${wirePropertyTypeV2ToTypeScriptType(objectTypeWithLinks.objectType.properties[objectTypeWithLinks.objectType.primaryKey].dataType)};
1304
+ ${Object.entries(objectTypeWithLinks.objectType.properties).sort((a, b) => a[0].localeCompare(b[0])).flatMap(([propertyName, propertyDefinition]) => {
1305
+ const propertyType = wirePropertyTypeV2ToTypeScriptType(propertyDefinition.dataType);
1306
+ const entries = [`${getDescriptionIfPresent(propertyDefinition.description, true)}readonly ${propertyName}: ${propertyType} | undefined`];
1307
+ if (isReservedKeyword(propertyName)) {
1308
+ entries.push(`/** @deprecated please migrate to '${propertyName}' instead */
1309
+ readonly ${propertyName}_: ${propertyType} | undefined`);
1534
1310
  }
1535
- const param = paramEntries.length === 0 ? "" : `params: { ${paramEntries.join("; ")} }`;
1536
- jsDocBlock.push(`* @returns ${sanitizeDocTypeName(outputType)}`, "*/");
1537
- signatures.push(`
1538
- ${jsDocBlock.join("\n")}
1539
- ${query.apiName}(${param}): Promise<Result<QueryResponse<${outputType}>, QueryError>>;
1540
- `);
1311
+ return entries;
1312
+ }).join(";\n")}
1313
+ ${objectTypeWithLinks.linkTypes.flatMap((linkType) => {
1314
+ const entries = [`readonly ${linkType.apiName}: ${linkType.cardinality === "MANY" ? "MultiLink" : "SingleLink"}<${linkType.objectTypeApiName}>`];
1315
+ return entries;
1316
+ }).join(";\n")}
1317
+ }
1318
+ `;
1319
+ }
1320
+ function wirePropertyTypeV2ToTypeScriptType(property) {
1321
+ switch (property.type) {
1322
+ case "string":
1323
+ return "string";
1324
+ case "boolean":
1325
+ return "boolean";
1326
+ case "array":
1327
+ return wirePropertyTypeV2ToTypeScriptType(property.subType) + "[]";
1328
+ case "integer":
1329
+ return "number";
1330
+ case "attachment":
1331
+ return "Attachment";
1332
+ case "byte":
1333
+ return "number";
1334
+ case "date":
1335
+ return "LocalDate";
1336
+ case "decimal":
1337
+ return "string";
1338
+ case "double":
1339
+ return "number";
1340
+ case "float":
1341
+ return "number";
1342
+ case "geopoint":
1343
+ return "GeoPoint";
1344
+ case "geoshape":
1345
+ return "GeoShape";
1346
+ case "long":
1347
+ return "StringLong";
1348
+ case "short":
1349
+ return "number";
1350
+ case "timestamp":
1351
+ return "Timestamp";
1352
+ case "timeseries":
1353
+ return property.itemType.type === "string" ? `TimeSeries<string>` : `TimeSeries<number>`;
1354
+ case "marking":
1355
+ return "string";
1356
+ default:
1357
+ throw new Error(`Unknown property type ${property}`);
1358
+ }
1359
+ }
1360
+ function getDescriptionIfPresent(description, includeNewline) {
1361
+ if (description) {
1362
+ return `/**
1363
+ * ${description}
1364
+ */${includeNewline ? "\n" : ""}`;
1541
1365
  }
1366
+ return "";
1367
+ }
1368
+
1369
+ // src/v1.1/generatePerObjectInterfaceAndDataFiles.ts
1370
+ async function generatePerObjectInterfaceAndDataFiles(ontology, fs2, outDir, importExt = "") {
1542
1371
  await fs2.mkdir(outDir, {
1543
1372
  recursive: true
1544
1373
  });
1545
- await fs2.writeFile(path16__default.join(outDir, "Queries.ts"), await formatTs(`
1546
- import type { QueryResponse, QueryError, Result, Timestamp, LocalDate, Range, Attachment, ObjectSet, TwoDimensionalAggregation, ThreeDimensionalAggregation } from "@osdk/legacy-client";
1547
- ${Array.from(importedObjects).map((importedObject) => `import type { ${importedObject} } from "../objects/${importedObject}${importExt}";`).join("\n")}
1374
+ await Promise.all(Object.values(ontology.og.objectTypes).map(async (object) => {
1375
+ const relPath = path16__default.join(".", "ontology", `objects`, `${object.objectType.apiName}.ts`);
1376
+ await fs2.writeFile(path16__default.join(outDir, `${object.objectType.apiName}.ts`), await formatTs(`
1377
+ import type { ObjectTypeDefinition, ObjectTypeLinkDefinition, PropertyDef } from "@osdk/api";
1378
+ ${wireObjectTypeV2ToObjectInterfaceStringV1(object, importExt)}
1548
1379
 
1549
- export interface Queries {
1550
- ${signatures.join("\n")}
1551
- }
1552
- `));
1380
+ ${wireObjectTypeV2ToSdkObjectConstV1(object, {
1381
+ ontology
1382
+ }, relPath)}
1383
+ `));
1384
+ }));
1385
+ await fs2.writeFile(path16__default.join(outDir, "index.ts"), await formatTs(`
1386
+ ${Object.keys(ontology.og.objectTypes).map((apiName) => `export * from "./${apiName}${importExt}";`).join("\n")}
1387
+ export type { ObjectSet } from "@osdk/legacy-client";
1388
+
1389
+ `));
1553
1390
  }
1554
- function handleQueryDataType(dataType, importedObjects, isReturnValue) {
1391
+
1392
+ // src/shared/getObjectTypesFromQueryDataType.ts
1393
+ function getObjectTypesFromQueryDataType(dataType, types) {
1555
1394
  switch (dataType.type) {
1395
+ case "array":
1396
+ case "set":
1397
+ getObjectTypesFromQueryDataType(dataType.subType, types);
1398
+ return;
1399
+ case "object":
1400
+ types.add(dataType.objectTypeApiName);
1401
+ return;
1402
+ case "objectSet":
1403
+ types.add(dataType.objectTypeApiName);
1404
+ return;
1405
+ case "struct":
1406
+ for (const prop of Object.values(dataType.fields)) {
1407
+ getObjectTypesFromQueryDataType(prop.fieldType, types);
1408
+ }
1409
+ return;
1410
+ case "union":
1411
+ for (const type of dataType.unionTypes) {
1412
+ getObjectTypesFromQueryDataType(type, types);
1413
+ }
1414
+ return;
1415
+ case "attachment":
1556
1416
  case "boolean":
1557
- return "boolean";
1417
+ case "date":
1418
+ case "double":
1419
+ case "float":
1420
+ case "integer":
1421
+ case "long":
1422
+ case "null":
1558
1423
  case "string":
1559
- return "string";
1424
+ case "threeDimensionalAggregation":
1425
+ case "timestamp":
1426
+ case "twoDimensionalAggregation":
1427
+ case "unsupported":
1428
+ return;
1429
+ default:
1430
+ throw new Error(`Cannot find object types from unsupported QueryDataType ${dataType.type}`);
1431
+ }
1432
+ }
1433
+
1434
+ // src/shared/getObjectTypeApiNamesFromQuery.ts
1435
+ function getObjectTypeApiNamesFromQuery(query) {
1436
+ const types = /* @__PURE__ */ new Set();
1437
+ for (const {
1438
+ dataType
1439
+ } of Object.values(query.parameters)) {
1440
+ getObjectTypesFromQueryDataType(dataType, types);
1441
+ }
1442
+ getObjectTypesFromQueryDataType(query.output, types);
1443
+ return Array.from(types);
1444
+ }
1445
+
1446
+ // src/shared/isNullableQueryDataType.ts
1447
+ function isNullableQueryDataType(input) {
1448
+ if (input.type === "null") {
1449
+ return true;
1450
+ }
1451
+ if (input.type === "union") {
1452
+ return input.unionTypes.some((t) => isNullableQueryDataType(t));
1453
+ }
1454
+ return false;
1455
+ }
1456
+
1457
+ // src/shared/wireQueryDataTypeToQueryDataTypeDefinition.ts
1458
+ function wireQueryDataTypeToQueryDataTypeDefinition(input) {
1459
+ switch (input.type) {
1460
+ case "double":
1461
+ case "float":
1462
+ case "integer":
1463
+ case "long":
1464
+ case "attachment":
1465
+ case "boolean":
1466
+ case "date":
1467
+ case "string":
1468
+ case "timestamp":
1469
+ return {
1470
+ type: input.type,
1471
+ nullable: false
1472
+ };
1473
+ case "object":
1474
+ return {
1475
+ type: "object",
1476
+ object: input.objectTypeApiName,
1477
+ nullable: false
1478
+ };
1479
+ case "objectSet":
1480
+ return {
1481
+ type: "objectSet",
1482
+ objectSet: input.objectTypeApiName,
1483
+ nullable: false
1484
+ };
1485
+ case "array":
1486
+ return {
1487
+ ...wireQueryDataTypeToQueryDataTypeDefinition(input.subType),
1488
+ multiplicity: true
1489
+ };
1490
+ case "set":
1491
+ return {
1492
+ type: "set",
1493
+ set: wireQueryDataTypeToQueryDataTypeDefinition(input.subType),
1494
+ nullable: false
1495
+ };
1496
+ case "union":
1497
+ const allowNulls = isNullableQueryDataType(input);
1498
+ if (allowNulls && input.unionTypes.length === 2) {
1499
+ const nonNull = input.unionTypes.find((t) => t.type != null);
1500
+ if (nonNull) {
1501
+ return {
1502
+ ...wireQueryDataTypeToQueryDataTypeDefinition(nonNull),
1503
+ nullable: true
1504
+ };
1505
+ }
1506
+ }
1507
+ return {
1508
+ type: "union",
1509
+ union: input.unionTypes.reduce((acc, t) => {
1510
+ if (t.type === "null") {
1511
+ return acc;
1512
+ }
1513
+ acc.push(wireQueryDataTypeToQueryDataTypeDefinition(t));
1514
+ return acc;
1515
+ }, []),
1516
+ nullable: allowNulls
1517
+ };
1518
+ case "struct":
1519
+ return {
1520
+ type: "struct",
1521
+ struct: Object.fromEntries(input.fields.map((f) => [f.name, wireQueryDataTypeToQueryDataTypeDefinition(f.fieldType)])),
1522
+ nullable: false
1523
+ };
1524
+ case "twoDimensionalAggregation":
1525
+ return {
1526
+ type: "twoDimensionalAggregation",
1527
+ twoDimensionalAggregation: get2DQueryAggregationProps(input),
1528
+ nullable: false
1529
+ };
1530
+ case "threeDimensionalAggregation":
1531
+ return {
1532
+ type: "threeDimensionalAggregation",
1533
+ threeDimensionalAggregation: get3DQueryAggregationProps(input),
1534
+ nullable: false
1535
+ };
1536
+ case "null":
1537
+ case "unsupported":
1538
+ throw new Error(`Accidentally tried to handle QueryDataType.type ${input.type}`);
1539
+ default:
1540
+ throw new Error(`Unsupported QueryDataType.type ${input.type}`);
1541
+ }
1542
+ }
1543
+ function get2DQueryAggregationProps(input) {
1544
+ if (input.keyType.type === "range") {
1545
+ return {
1546
+ keyType: input.keyType.type,
1547
+ keySubtype: input.keyType.subType.type,
1548
+ valueType: input.valueType.type
1549
+ };
1550
+ } else {
1551
+ if (guardInvalidKeyTypes(input.keyType)) {
1552
+ return {
1553
+ keyType: input.keyType.type,
1554
+ valueType: input.valueType.type
1555
+ };
1556
+ }
1557
+ throw new Error(`Cannot create 2D aggregation with ${input.keyType.type} as its type`);
1558
+ }
1559
+ }
1560
+ function get3DQueryAggregationProps(input) {
1561
+ if (input.keyType.type === "range") {
1562
+ return {
1563
+ keyType: input.keyType.type,
1564
+ keySubtype: input.keyType.subType.type,
1565
+ valueType: get2DQueryAggregationProps(input.valueType)
1566
+ };
1567
+ } else {
1568
+ if (guardInvalidKeyTypes(input.keyType)) {
1569
+ return {
1570
+ keyType: input.keyType.type,
1571
+ valueType: get2DQueryAggregationProps(input.valueType)
1572
+ };
1573
+ }
1574
+ throw new Error(`Cannot create 3D aggregation with ${input.keyType.type} as its type`);
1575
+ }
1576
+ }
1577
+ function guardInvalidKeyTypes(key) {
1578
+ return key.type === "string" || key.type === "boolean";
1579
+ }
1580
+
1581
+ // src/shared/wireQueryTypeV2ToSdkQueryDefinition.ts
1582
+ function wireQueryTypeV2ToSdkQueryDefinition(input) {
1583
+ return {
1584
+ type: "query",
1585
+ apiName: input.apiName,
1586
+ description: input.description,
1587
+ displayName: input.displayName,
1588
+ version: input.version,
1589
+ parameters: Object.fromEntries(Object.entries(input.parameters).map(([name, parameter]) => [name, wireQueryParameterV2ToQueryParameterDefinition(parameter)])),
1590
+ output: wireQueryDataTypeToQueryDataTypeDefinition(input.output)
1591
+ };
1592
+ }
1593
+ function wireQueryTypeV2ToSdkQueryDefinitionNoParams(input) {
1594
+ return {
1595
+ type: "query",
1596
+ apiName: input.apiName,
1597
+ description: input.description,
1598
+ displayName: input.displayName,
1599
+ version: input.version
1600
+ };
1601
+ }
1602
+ function wireQueryParameterV2ToQueryParameterDefinition(parameter) {
1603
+ return {
1604
+ description: parameter.description,
1605
+ ...wireQueryDataTypeToQueryDataTypeDefinition(parameter.dataType)
1606
+ };
1607
+ }
1608
+
1609
+ // src/v1.1/generatePerQueryDataFiles.ts
1610
+ async function generatePerQueryDataFiles({
1611
+ fs: fs2,
1612
+ outDir: rootOutDir,
1613
+ ontology
1614
+ }, v2) {
1615
+ const relOutDir = path16__default.join(".", "ontology", "queries");
1616
+ const outDir = path16__default.join(rootOutDir, "ontology", "queries");
1617
+ await fs2.mkdir(outDir, {
1618
+ recursive: true
1619
+ });
1620
+ await Promise.all(Object.values(ontology.queryTypes).map(async (query) => {
1621
+ await generateV1QueryFile(fs2, outDir, query);
1622
+ }));
1623
+ await fs2.writeFile(path16__default.join(outDir, "index.ts"), await formatTs(`
1624
+ ${Object.values(ontology.queryTypes).map((query) => `export * from "${query.getImportPathRelTo(path16__default.join(relOutDir, "index.ts"))}";`).join("\n")}
1625
+ ${Object.keys(ontology.queryTypes).length === 0 ? "export {};" : ""}
1626
+ `));
1627
+ }
1628
+ async function generateV1QueryFile(fs2, outDir, query) {
1629
+ const objectTypes = getObjectTypeApiNamesFromQuery(query);
1630
+ await fs2.writeFile(path16__default.join(outDir, `${query.shortApiName}.ts`), await formatTs(`
1631
+ import { QueryDefinition } from "@osdk/api";
1632
+
1633
+ export const ${query.shortApiName} = ${JSON.stringify(wireQueryTypeV2ToSdkQueryDefinition(query.og))} ${getQueryDefSatisfies(query.fullApiName, objectTypes)}`));
1634
+ }
1635
+ function getQueryDefSatisfies(apiName, objectTypes) {
1636
+ return `satisfies QueryDefinition<"${apiName}", ${objectTypes.length > 0 ? objectTypes.map((apiNameObj) => `"${apiNameObj}"`).join("|") : "never"}>;`;
1637
+ }
1638
+ async function generateQueries(ontology, fs2, outDir, importExt = "") {
1639
+ const importedObjects = /* @__PURE__ */ new Set();
1640
+ const signatures = [];
1641
+ for (const query of Object.values(ontology.queryTypes)) {
1642
+ const jsDocBlock = ["/**"];
1643
+ if (query.description) {
1644
+ jsDocBlock.push(`* ${query.description}`);
1645
+ }
1646
+ const outputType = handleQueryDataType(query.output, importedObjects, true);
1647
+ const paramEntries = [];
1648
+ for (const [name, parameter] of Object.entries(query.parameters)) {
1649
+ const nullable = isNullableQueryDataType(parameter.dataType);
1650
+ const type = handleQueryDataType(parameter.dataType, importedObjects, false);
1651
+ paramEntries.push(`"${name}"${nullable ? "?" : ""}: ${type}`);
1652
+ jsDocBlock.push(`* @param {${sanitizeDocTypeName(type)}} params.${name}${parameter.description ? ` - ${parameter.description}` : ""}`);
1653
+ }
1654
+ const param = paramEntries.length === 0 ? "" : `params: { ${paramEntries.join("; ")} }`;
1655
+ jsDocBlock.push(`* @returns ${sanitizeDocTypeName(outputType)}`, "*/");
1656
+ signatures.push(`
1657
+ ${jsDocBlock.join("\n")}
1658
+ ${query.apiName}(${param}): Promise<Result<QueryResponse<${outputType}>, QueryError>>;
1659
+ `);
1660
+ }
1661
+ await fs2.mkdir(outDir, {
1662
+ recursive: true
1663
+ });
1664
+ await fs2.writeFile(path16__default.join(outDir, "Queries.ts"), await formatTs(`
1665
+ import type { QueryResponse, QueryError, Result, Timestamp, LocalDate, Range, Attachment, ObjectSet, TwoDimensionalAggregation, ThreeDimensionalAggregation } from "@osdk/legacy-client";
1666
+ ${Array.from(importedObjects).map((importedObject) => `import type { ${importedObject} } from "../objects/${importedObject}${importExt}";`).join("\n")}
1667
+
1668
+ export interface Queries {
1669
+ ${signatures.join("\n")}
1670
+ }
1671
+ `));
1672
+ }
1673
+ function handleQueryDataType(dataType, importedObjects, isReturnValue) {
1674
+ switch (dataType.type) {
1675
+ case "boolean":
1676
+ return "boolean";
1677
+ case "string":
1678
+ return "string";
1679
+ case "double":
1680
+ case "float":
1681
+ case "integer":
1682
+ return "number";
1683
+ case "long":
1684
+ return isReturnValue ? "string" : "string | number";
1685
+ case "date":
1686
+ return "LocalDate";
1687
+ case "timestamp":
1688
+ return "Timestamp";
1689
+ case "attachment":
1690
+ return "Attachment";
1691
+ case "array":
1692
+ return `Array<${handleQueryDataType(dataType.subType, importedObjects, isReturnValue)}>`;
1693
+ case "object": {
1694
+ const objectType = dataType.objectTypeApiName;
1695
+ importedObjects.add(objectType);
1696
+ return isReturnValue ? objectType : `${objectType} | ${objectType}["__primaryKey"]`;
1697
+ }
1698
+ case "objectSet": {
1699
+ const objectType = dataType.objectTypeApiName;
1700
+ importedObjects.add(objectType);
1701
+ return `ObjectSet<${objectType}>`;
1702
+ }
1703
+ case "set":
1704
+ return `Set<${handleQueryDataType(dataType.subType, importedObjects, isReturnValue)}>`;
1705
+ case "struct":
1706
+ const properties = dataType.fields.map((field) => {
1707
+ const isNullable = isNullableQueryDataType(field.fieldType);
1708
+ return `${field.name}${isNullable ? "?" : ""}: ${handleQueryDataType(field.fieldType, importedObjects, isReturnValue)}`;
1709
+ });
1710
+ return `{ ${properties.join(",\n")} }`;
1711
+ case "union":
1712
+ return dataType.unionTypes.map((type) => handleQueryDataType(type, importedObjects, isReturnValue)).filter((type) => type !== "null").join("|");
1713
+ case "twoDimensionalAggregation":
1714
+ dataType.valueType;
1715
+ return `TwoDimensionalAggregation<
1716
+ ${aggregationKeyToTypescriptType(dataType.keyType)},
1717
+ ${aggregationValueToTypescriptType(dataType.valueType)}
1718
+ >`;
1719
+ case "threeDimensionalAggregation":
1720
+ return `ThreeDimensionalAggregation<
1721
+ ${aggregationKeyToTypescriptType(dataType.keyType)},
1722
+ ${aggregationKeyToTypescriptType(dataType.valueType.keyType)},
1723
+ ${aggregationValueToTypescriptType(dataType.valueType.valueType)}
1724
+ >`;
1725
+ case "null":
1726
+ return "null";
1727
+ case "unsupported":
1728
+ throw new Error("Cannot generate queries for unsupported type");
1729
+ default:
1730
+ throw new Error(`Cannot generate queries for type ${dataType.type}`);
1731
+ }
1732
+ }
1733
+ function aggregationKeyToTypescriptType(keyType) {
1734
+ switch (keyType.type) {
1735
+ case "boolean":
1736
+ return "boolean";
1737
+ case "double":
1738
+ case "integer":
1739
+ return "number";
1740
+ case "string":
1741
+ return "string";
1742
+ case "date":
1743
+ return "LocalDate";
1744
+ case "timestamp":
1745
+ return "Timestamp";
1746
+ case "range":
1747
+ return `Range<${aggregationRangeToTypescriptType(keyType.subType)}>`;
1748
+ default:
1749
+ throw new Error(`Unknown TwoDimensionalAggregation keyType ${keyType.type}`);
1750
+ }
1751
+ }
1752
+ function aggregationRangeToTypescriptType(subType) {
1753
+ switch (subType.type) {
1754
+ case "date":
1755
+ return "LocalDate";
1756
+ case "double":
1757
+ case "integer":
1758
+ return "number";
1759
+ case "timestamp":
1760
+ return "Timestamp";
1761
+ default:
1762
+ throw new Error(`Unsupported QueryAggregationRangeSubType ${subType.type}`);
1763
+ }
1764
+ }
1765
+ function aggregationValueToTypescriptType(valueType) {
1766
+ switch (valueType.type) {
1767
+ case "date":
1768
+ return "LocalDate";
1769
+ case "double":
1770
+ return "number";
1771
+ case "timestamp":
1772
+ return "Timestamp";
1773
+ default:
1774
+ throw new Error(`Unsupported QueryAggregationValueType ${valueType.type}`);
1775
+ }
1776
+ }
1777
+ function sanitizeDocTypeName(type) {
1778
+ return type.replace(/\s/g, "");
1779
+ }
1780
+
1781
+ // src/v1.1/generateClientSdkVersionOneDotOne.ts
1782
+ async function generateClientSdkVersionOneDotOne(ontology, userAgent, fs2, outDir, packageType = "commonjs") {
1783
+ const importExt = packageType === "module" ? ".js" : "";
1784
+ const objectsDir = path16.join(outDir, "ontology", "objects");
1785
+ const actionsDir = path16.join(outDir, "ontology", "actions");
1786
+ const queriesDir = path16.join(outDir, "ontology", "queries");
1787
+ await verifyOutDir(outDir, fs2);
1788
+ await fs2.mkdir(outDir, {
1789
+ recursive: true
1790
+ });
1791
+ const sanitizedOntology = sanitizeMetadata(ontology);
1792
+ const enhancedOntology = enhanceOntology(sanitizedOntology, void 0, /* @__PURE__ */ new Map(), importExt);
1793
+ await generateFoundryClientFile(fs2, outDir, importExt);
1794
+ await generateMetadataFile(sanitizedOntology, userAgent, fs2, outDir, importExt);
1795
+ await generateOntologyIndexFile(fs2, path16.join(outDir, "ontology"));
1796
+ await generateObjectsInterfaceFile(sanitizedOntology, fs2, objectsDir, importExt);
1797
+ await generateObjectsInterfaceSupportFiles(sanitizedOntology, fs2, path16.join(objectsDir, "objects-api"), importExt);
1798
+ await generatePerObjectInterfaceAndDataFiles(enhancedOntology, fs2, objectsDir, importExt);
1799
+ const common = {
1800
+ sanitizedOntology,
1801
+ fs: fs2,
1802
+ outDir,
1803
+ ontology: enhancedOntology
1804
+ };
1805
+ await generateActions(sanitizedOntology, fs2, actionsDir, importExt);
1806
+ await generateBatchActions(sanitizedOntology, fs2, actionsDir, importExt);
1807
+ await generateBulkActions(sanitizedOntology, fs2, actionsDir, importExt);
1808
+ await generatePerActionDataFilesV1(common);
1809
+ await generateQueries(sanitizedOntology, fs2, queriesDir, importExt);
1810
+ await generatePerQueryDataFiles(common);
1811
+ await generateIndexFile(fs2, outDir, importExt);
1812
+ await generateBackCompatDeprecatedExports(fs2, outDir, importExt);
1813
+ }
1814
+ var ExpectedOsdkVersion = "0.22.0";
1815
+ async function generateOntologyMetadataFile({
1816
+ fs: fs2,
1817
+ outDir,
1818
+ ontology,
1819
+ ontologyApiNamespace
1820
+ }, userAgent) {
1821
+ fs2.writeFile(path16__default.join(outDir, "OntologyMetadata.ts"), await formatTs(`
1822
+ export type $ExpectedClientVersion = "${ExpectedOsdkVersion}";
1823
+ export const $osdkMetadata = { extraUserAgent: "${userAgent}" };
1824
+ ${ontologyApiNamespace == null ? `
1825
+ export const $ontologyRid = "${ontology.ontology.rid}";
1826
+ ` : ""}
1827
+ `));
1828
+ }
1829
+
1830
+ // src/shared/propertyJsdoc.ts
1831
+ function propertyJsdoc(property, {
1832
+ isInherited,
1833
+ apiName
1834
+ }) {
1835
+ let ret = `/**
1836
+ `;
1837
+ const renderDisplayName = property.displayName && property.displayName !== apiName;
1838
+ if (isInherited || renderDisplayName || property.description) {
1839
+ if (isInherited) {
1840
+ ret += ` * (inherited from parent)
1841
+ `;
1842
+ }
1843
+ if (renderDisplayName) {
1844
+ ret += ` * display name: '${property.displayName}'${property.description ? "," : ""}
1845
+ `;
1846
+ }
1847
+ if (property.description) {
1848
+ ret += ` * description: ${property.description}
1849
+ `;
1850
+ }
1851
+ } else {
1852
+ ret += ` * (no ontology metadata)
1853
+ `;
1854
+ }
1855
+ ret += ` */
1856
+ `;
1857
+ return ret;
1858
+ }
1859
+
1860
+ // src/v2.0/wireObjectTypeV2ToSdkObjectConstV2.ts
1861
+ function getObjectDefIdentifier(name, v2) {
1862
+ return v2 ? name : `${name}Def`;
1863
+ }
1864
+ function wireObjectTypeV2ToSdkObjectConstV2(wireObject, {
1865
+ ontology
1866
+ }, currentFilePath) {
1867
+ const object = ontology.requireObjectType(wireObject.objectType.apiName, true);
1868
+ const uniqueLinkTargetTypes = new Set(wireObject.linkTypes.map((a) => ontology.requireObjectType(a.objectTypeApiName, false)));
1869
+ const definition = deleteUndefineds(wireObjectTypeFullMetadataToSdkObjectTypeDefinition(object.og, true));
1870
+ const objectDefIdentifier = object.getDefinitionIdentifier(true);
1871
+ const objectSetIdentifier = `${object.shortApiName}.ObjectSet`;
1872
+ const propertyKeysIdentifier = `${object.shortApiName}.PropertyKeys`;
1873
+ const osdkObjectPropsIdentifier = `${object.shortApiName}.Props`;
1874
+ const osdkObjectStrictPropsIdentifier = `${object.shortApiName}.StrictProps`;
1875
+ const osdkObjectLinksIdentifier = `${object.shortApiName}.Links`;
1876
+ const osdkObjectIdentifier = `${object.shortApiName}.OsdkObject`;
1877
+ const identifiers = {
1878
+ objectDefIdentifier: `${object.shortApiName}.Definition`,
1879
+ osdkObjectLinksIdentifier,
1880
+ osdkObjectPropsIdentifier,
1881
+ osdkObjectStrictPropsIdentifier,
1882
+ objectSetIdentifier,
1883
+ osdkObjectIdentifier,
1884
+ propertyKeysIdentifier
1885
+ };
1886
+ function getV2Types() {
1887
+ return `import type {
1888
+ AggregateOpts as $AggregateOpts,
1889
+ AggregateOptsThatErrorsAndDisallowsOrderingWithMultipleGroupBy as $AggregateOptsThatErrorsAndDisallowsOrderingWithMultipleGroupBy,
1890
+ AggregationsResults as $AggregationsResults,
1891
+ Augments as $Augments,
1892
+ ConvertProps as $ConvertProps,
1893
+ DefaultToFalse as $DefaultToFalse,
1894
+ FetchPageArgs as $FetchPageArgs,
1895
+ FetchPageResult as $FetchPageResult,
1896
+ LinkedType as $LinkedType,
1897
+ LinkNames as $LinkNames,
1898
+ NullabilityAdherence as $NullabilityAdherence,
1899
+ NullabilityAdherenceDefault as $NullabilityAdherenceDefault,
1900
+ ObjectSet as $ObjectSet,
1901
+ Osdk as $Osdk,
1902
+ OsdkObject as $OsdkObject,
1903
+ OsdkObjectLinksEntry as $OsdkObjectLinksEntry,
1904
+ OsdkObjectLinksObject as $OsdkObjectLinksObject,
1905
+ OsdkObjectPropertyType as $OsdkObjectPropertyType,
1906
+ PageResult as $PageResult,
1907
+ PropertyValueClientToWire as $PropertyValueClientToWire,
1908
+ PropertyValueWireToClient as $PropType,
1909
+ Result as $Result,
1910
+ SelectArg as $SelectArg,
1911
+ SingleLinkAccessor as $SingleLinkAccessor,
1912
+ SingleLinkAccessor as $SingleLinkAccessor
1913
+ SingleOsdkResult as $SingleOsdkResult,
1914
+ ValidToFrom as $ValidToFrom,
1915
+ WhereClause as $WhereClause,
1916
+ } from "@osdk/client.api";
1917
+ import type * as $clientApi from "@osdk/client.api";
1918
+ import type {
1919
+ ObjectOrInterfacePropertyKeysFrom2 as $ObjectOrInterfacePropertyKeysFrom2,
1920
+ ObjectTypeDefinition as $ObjectTypeDefinition,
1921
+ ObjectTypeLinkDefinition as $ObjectTypeLinkDefinition,
1922
+ } from "@osdk/api";
1923
+
1924
+ export namespace ${object.shortApiName} {
1925
+
1926
+ ${createPropertyKeys(object)}
1927
+
1928
+
1929
+ ${createLinks(ontology, object, "Links")}
1930
+
1931
+ ${createProps(object, "Props", false)}
1932
+ ${createProps(object, "StrictProps", true)}
1933
+
1934
+ ${createObjectSet(object, identifiers)}
1935
+
1936
+ ${createDefinition(object, ontology, "Definition", identifiers)}
1937
+ ${createOsdkObject(object, "OsdkObject", identifiers)}
1938
+ }
1939
+
1940
+
1941
+
1942
+
1943
+ /** @deprecated use ${object.shortApiName}.Definition **/
1944
+ export type ${objectDefIdentifier} = ${object.shortApiName}.Definition;
1945
+
1946
+
1947
+ `;
1948
+ }
1949
+ const imports = getObjectImports(uniqueLinkTargetTypes, definition.apiName, currentFilePath, true);
1950
+ return `${imports}${getV2Types()}
1951
+
1952
+ export const ${object.shortApiName}: ${objectDefIdentifier} & $VersionBound<$ExpectedClientVersion>
1953
+ = {
1954
+ osdkMetadata: $osdkMetadata,
1955
+ objectSet: undefined as any,
1956
+ props: undefined as any,
1957
+ strictProps: undefined as any,
1958
+ ${stringify(definition, {
1959
+ osdkMetadata: (value) => void 0
1960
+ })}
1961
+
1962
+ };`;
1963
+ }
1964
+ function createOsdkObject(object, identifier, {
1965
+ osdkObjectPropsIdentifier,
1966
+ objectDefIdentifier,
1967
+ osdkObjectStrictPropsIdentifier,
1968
+ osdkObjectLinksIdentifier
1969
+ }) {
1970
+ const definition = object.getCleanedUpDefinition(true);
1971
+ return `
1972
+ export type ${identifier}<
1973
+ OPTIONS extends "$strict" | "$notStrict" | "$rid" = "$strict",
1974
+ K extends keyof ${osdkObjectPropsIdentifier}= keyof ${osdkObjectPropsIdentifier},
1975
+
1976
+ >
1977
+ = $Osdk<
1978
+ ${objectDefIdentifier},
1979
+ K | OPTIONS
1980
+ > & Pick<
1981
+ OPTIONS extends "$notStrict" ? ${osdkObjectPropsIdentifier} : ${osdkObjectStrictPropsIdentifier}
1982
+ , K
1983
+ > & {
1984
+ readonly $link: ${osdkObjectLinksIdentifier};
1985
+ readonly $title: string | undefined; // FIXME
1986
+ readonly $primaryKey: ${"primaryKeyApiName" in definition ? `
1987
+ $OsdkObjectPropertyType<${JSON.stringify(definition.properties[definition.primaryKeyApiName])},${true}>` : "string | number"}
1988
+ ;
1989
+
1990
+ readonly $as: <NEW_Q extends $ValidToFrom<${objectDefIdentifier}>>(type: NEW_Q | string) => $Osdk<
1991
+ NEW_Q,
1992
+ $ConvertProps<${objectDefIdentifier}, NEW_Q, K>
1993
+ >;
1994
+ } & $OsdkObject<"${object.fullApiName}">;`;
1995
+ }
1996
+ function createObjectSet(object, {
1997
+ objectDefIdentifier,
1998
+ objectSetIdentifier,
1999
+ propertyKeysIdentifier,
2000
+ osdkObjectIdentifier
2001
+ }) {
2002
+ return `
2003
+ export interface ObjectSet extends
2004
+ $ObjectSet<${objectDefIdentifier},
2005
+
2006
+ ${objectSetIdentifier}
2007
+ >
2008
+ {
2009
+ readonly aggregate: <AO extends $AggregateOpts<${objectDefIdentifier}>>(
2010
+ req: $AggregateOptsThatErrorsAndDisallowsOrderingWithMultipleGroupBy<${objectDefIdentifier}, AO>,
2011
+ ) => Promise<$AggregationsResults<${objectDefIdentifier}, AO>>;
2012
+
2013
+
2014
+ readonly pivotTo: <L extends $LinkNames<${objectDefIdentifier}>>(type: L) => $LinkedType<${objectDefIdentifier}, L>["objectSet"];
2015
+ ${object instanceof EnhancedObjectType ? `
2016
+ readonly fetchOne: <
2017
+ L extends ${propertyKeysIdentifier},
2018
+ R extends boolean,
2019
+ S extends false | "throw" = $NullabilityAdherenceDefault,
2020
+ >(
2021
+ primaryKey: $PropertyValueClientToWire[${objectDefIdentifier}["primaryKeyType"]],
2022
+ options?: $SelectArg<${objectDefIdentifier}, L, R, S>,
2023
+ ) => Promise<
2024
+ ${osdkObjectIdentifier}<
2025
+ (S extends false ? "$notStrict" : "$strict") | ($DefaultToFalse<R> extends false? never: "$rid" ),
2026
+ L
2027
+ >>
2028
+ ;
2029
+
2030
+ readonly fetchOneWithErrors: <
2031
+ L extends ${propertyKeysIdentifier},
2032
+ R extends boolean,
2033
+ S extends false | "throw" = $NullabilityAdherenceDefault,
2034
+ >(
2035
+ primaryKey: $PropertyValueClientToWire[${objectDefIdentifier}["primaryKeyType"]],
2036
+ options?: $SelectArg<${objectDefIdentifier}, L, R, S>,
2037
+ ) => Promise<$Result<
2038
+ ${osdkObjectIdentifier}<
2039
+ (S extends false ? "$notStrict" : "$strict") | ($DefaultToFalse<R> extends false?never: "$rid"),
2040
+ L
2041
+ >
2042
+ >>
2043
+
2044
+ ;
2045
+
2046
+ ` : ""}
2047
+
2048
+ readonly fetchPage: <
2049
+ L extends ${propertyKeysIdentifier},
2050
+ R extends boolean,
2051
+ const A extends $Augments,
2052
+ S extends $NullabilityAdherence = $NullabilityAdherenceDefault,
2053
+ >(
2054
+ args?: $FetchPageArgs<${objectDefIdentifier}, L, R, A, S>,
2055
+ ) => Promise<
2056
+ $PageResult<${osdkObjectIdentifier}<
2057
+ (S extends false ? "$notStrict" : "$strict") | ($DefaultToFalse<R> extends false? never: "$rid"),
2058
+ L
2059
+ >>
2060
+ >;
2061
+
2062
+ readonly fetchPageWithErrors: <
2063
+ L extends ${propertyKeysIdentifier},
2064
+ R extends boolean,
2065
+ const A extends $Augments,
2066
+ S extends $NullabilityAdherence = $NullabilityAdherenceDefault,
2067
+ >(
2068
+ args?: $FetchPageArgs<${objectDefIdentifier}, L, R, A, S>,
2069
+ ) => Promise<$Result<
2070
+ $PageResult<${osdkObjectIdentifier}<
2071
+ (S extends false ? "$notStrict" : "$strict") | ($DefaultToFalse<R> extends false? never : "$rid"),
2072
+ L>>
2073
+ >>;
2074
+
2075
+ readonly asyncIter: () => AsyncIterableIterator<${osdkObjectIdentifier}>;
2076
+ }
2077
+ `;
2078
+ }
2079
+ function maybeStripNamespace(type, q) {
2080
+ if (type.apiNamespace && q.startsWith(`${type.apiNamespace}.`)) {
2081
+ return q.slice(type.apiNamespace.length + 1);
2082
+ } else {
2083
+ return q;
2084
+ }
2085
+ }
2086
+ function createProps(type, identifier, strict) {
2087
+ const definition = type.getCleanedUpDefinition(true);
2088
+ return `export interface ${identifier} {
2089
+ ${stringify(definition.properties, {
2090
+ "*": (propertyDefinition, _, apiName) => {
2091
+ return [`readonly "${maybeStripNamespace(type, apiName)}"${// after we convert everything over we can do this:
2092
+ // !strict || propertyDefinition.nullable ? "?" : ""
2093
+ ""}`, `$PropType[${JSON.stringify(propertyDefinition.type)}]${propertyDefinition.multiplicity ? "[]" : ""}${propertyDefinition.nullable || !strict ? `| undefined` : ""}`];
2094
+ }
2095
+ })}
2096
+ }`;
2097
+ }
2098
+ function createDefinition(object, ontology, identifier, {
2099
+ objectDefIdentifier,
2100
+ objectSetIdentifier,
2101
+ osdkObjectPropsIdentifier,
2102
+ osdkObjectStrictPropsIdentifier
2103
+ }) {
2104
+ const definition = object.getCleanedUpDefinition(true);
2105
+ return `
2106
+ export interface ${identifier} extends ${object instanceof EnhancedObjectType ? `$ObjectTypeDefinition` : `$InterfaceDefinition`}<"${object.fullApiName}", ${objectDefIdentifier}>, $VersionBound<$ExpectedClientVersion> {
2107
+ osdkMetadata: typeof $osdkMetadata;
2108
+ objectSet: ${objectSetIdentifier};
2109
+ props: ${osdkObjectPropsIdentifier};
2110
+ strictProps: ${osdkObjectStrictPropsIdentifier};
2111
+ ${stringify(definition, {
2112
+ osdkMetadata: () => void 0,
2113
+ // we are going to reference another object instead
2114
+ type: () => void 0,
2115
+ apiName: () => void 0,
2116
+ links: (_value) => `{
2117
+ ${stringify(definition.links, {
2118
+ "*": (definition2) => `$ObjectTypeLinkDefinition<${ontology.requireObjectType(definition2.targetType).getImportedDefinitionIdentifier(true)}, ${definition2.multiplicity}>`
2119
+ })}
2120
+ }`,
2121
+ properties: (_value) => `{
2122
+ ${stringify(definition.properties, {
2123
+ "*": (propertyDefinition, _, apiName) => [`${propertyJsdoc(propertyDefinition, {
2124
+ apiName
2125
+ })}"${maybeStripNamespace(object, apiName)}"`, `$PropertyDef<"${propertyDefinition.type}", "${propertyDefinition.nullable ? "nullable" : "non-nullable"}", "${propertyDefinition.multiplicity ? "array" : "single"}">`]
2126
+ })}
2127
+ }`
2128
+ })}
2129
+ }
2130
+ `;
2131
+ }
2132
+ function createLinks(ontology, object, identifier) {
2133
+ const definition = object.getCleanedUpDefinition(true);
2134
+ return `
2135
+ ${Object.keys(definition.links).length === 0 ? `export type ${identifier} = never;` : `
2136
+ export interface ${identifier} {
2137
+ ${stringify(definition.links, {
2138
+ "*": (definition2, _, key) => {
2139
+ const linkTarget = ontology.requireObjectType(definition2.targetType).getImportedDefinitionIdentifier(true);
2140
+ return [`readonly ${key}`, `${definition2.multiplicity ? `${linkTarget}.ObjectSet` : `$SingleLinkAccessor<${linkTarget}.Definition>`}
2141
+ `];
2142
+ }
2143
+ })}
2144
+ }
2145
+ `}`;
2146
+ }
2147
+ function createPropertyKeys(type) {
2148
+ return `export type PropertyKeys = ${Object.keys(type.getCleanedUpDefinition(true).properties).map((a) => maybeStripNamespace(type, a)).map((a) => `"${a}"`).join("|")};`;
2149
+ }
2150
+
2151
+ // src/v2.0/generatePerActionDataFiles.ts
2152
+ async function generatePerActionDataFiles({
2153
+ sanitizedOntology: ontology,
2154
+ fs: fs2,
2155
+ outDir: rootOutDir,
2156
+ importExt = "",
2157
+ ontology: enhancedOntology
2158
+ }) {
2159
+ const outDir = path16__default.join(rootOutDir, "ontology", "actions");
2160
+ await fs2.mkdir(outDir, {
2161
+ recursive: true
2162
+ });
2163
+ await Promise.all(Object.values(enhancedOntology.actionTypes).map(async (action) => {
2164
+ const currentFilePath = `${path16__default.join("ontology", "actions", `${action.shortApiName}.ts`)}`;
2165
+ const uniqueApiNamesArray = extractReferencedObjectsFromAction2(action.og);
2166
+ const uniqueApiNames = new Set(uniqueApiNamesArray);
2167
+ const uniqueApiNamesString = stringUnionFrom2([...uniqueApiNames]);
2168
+ const fullActionDef = deleteUndefineds(wireActionTypeV2ToSdkActionDefinition(action.og));
2169
+ const {
2170
+ parameters,
2171
+ ...actionDefSansParameters
2172
+ } = fullActionDef;
2173
+ function createParamsDef() {
2174
+ const entries = Object.entries(parameters);
2175
+ entries.sort((a, b) => a[0].localeCompare(b[0]));
2176
+ if (entries.length === 0) {
2177
+ return `// Represents the definition of the parameters for the action
2178
+ export type ParamsDefinition = Record<string, never>;`;
2179
+ }
2180
+ return `// Represents the definition of the parameters for the action
2181
+ export type ParamsDefinition = {
2182
+ ${entries.map(([key, value]) => {
2183
+ return `"${key}": {
2184
+ ${stringify(value, {
2185
+ description: (value2, d) => value2 ? d(value2) : void 0,
2186
+ // trick to remove undefineds
2187
+ type: (type) => {
2188
+ if (typeof type === "string") {
2189
+ return JSON.stringify(type);
2190
+ } else if (type.type === "object") {
2191
+ const obj = enhancedOntology.requireObjectType(type.object);
2192
+ return `ObjectActionDataType<"${obj.fullApiName}", ${obj.getImportedDefinitionIdentifier(true)}>`;
2193
+ } else if (type.type === "objectSet") {
2194
+ return `ObjectSetActionDataType<"${type.objectSet}", ${getObjectDefIdentifier(type.objectSet, true)}>`;
2195
+ }
2196
+ return void 0;
2197
+ }
2198
+ })}
2199
+ }`;
2200
+ }).join(";\n")}
2201
+ }`;
2202
+ }
2203
+ function getActionParamType(input) {
2204
+ if (typeof input === "string") {
2205
+ return `ActionParam.PrimitiveType<${JSON.stringify(input)}>`;
2206
+ } else if (input.type === "object") {
2207
+ return `ActionParam.ObjectType<${enhancedOntology.requireObjectType(input.object).getImportedDefinitionIdentifier(true)}>`;
2208
+ } else if (input.type === "objectSet") {
2209
+ return `ActionParam.ObjectSetType<${enhancedOntology.requireObjectType(input.objectSet).getImportedDefinitionIdentifier(true)}>`;
2210
+ }
2211
+ }
2212
+ function createV2Types() {
2213
+ const oldParamsIdentifier = `${action.shortApiName}$Params`;
2214
+ return `
2215
+
2216
+ export namespace ${action.shortApiName}{
2217
+ ${createParamsDef()}
2218
+
2219
+ ${getDescriptionIfPresent(action.description)}
2220
+ export interface Parameters {
2221
+ ${stringify(parameters, {
2222
+ "*": (ogValue, _, ogKey) => {
2223
+ const key = `${getDescriptionIfPresent(ogValue.description)}
2224
+ readonly "${ogKey}"${ogValue.nullable ? "?" : ""}`;
2225
+ const value = ogValue.multiplicity ? `ReadonlyArray<${getActionParamType(ogValue.type)}>` : `${getActionParamType(ogValue.type)}`;
2226
+ return [key, value];
2227
+ }
2228
+ })}
2229
+ }
2230
+
2231
+
2232
+ // Represents the definition of the action
2233
+ export interface Definition extends ActionDefinition<"${action.shortApiName}", ${uniqueApiNamesString}, ${action.shortApiName}>, VersionBound<$ExpectedClientVersion> {
2234
+ ${Object.entries(actionDefSansParameters).sort((a, b) => a[0].localeCompare(b[0])).map(([key, value]) => {
2235
+ return `${key}: ${JSON.stringify(value)};`;
2236
+ }).join("\n")}
2237
+ parameters: ${action.definitionParamsIdentifier};
2238
+ osdkMetadata: typeof $osdkMetadata;
2239
+ }
2240
+
2241
+ // Represents a fqn of the action
2242
+ export interface Signature {
2243
+ ${getDescriptionIfPresent(action.description)}
2244
+ <P extends ${action.paramsIdentifier} | ReadonlyArray<${action.paramsIdentifier}>, OP extends (P extends ReadonlyArray<${action.paramsIdentifier}> ? ApplyBatchActionOptions: ApplyActionOptions)>(args: P, options?: OP): Promise<ActionReturnTypeForOptions<OP>>;
2245
+ }
2246
+
2247
+ }
2248
+
2249
+ /**
2250
+ * @deprecated Use \`${action.paramsIdentifier}\`
2251
+ */
2252
+ export type ${oldParamsIdentifier} = ${action.paramsIdentifier} | ReadonlyArray<${action.paramsIdentifier}>;
2253
+
2254
+ /** @deprecated Use \`${action.definitionIdentifier}\` **/
2255
+ export type ${action.shortApiName} = ${action.shortApiName}.Signature;
2256
+ `;
2257
+ }
2258
+ function createV2Object() {
2259
+ return ` export const ${action.shortApiName}: ${action.definitionIdentifier} =
2260
+ {
2261
+ ${stringify(fullActionDef)},
2262
+ osdkMetadata: $osdkMetadata
2263
+ }
2264
+ `;
2265
+ }
2266
+ const referencedObjectDefs = /* @__PURE__ */ new Set();
2267
+ for (const p of Object.values(action.parameters)) {
2268
+ if (p.dataType.type === "object" || p.dataType.type === "objectSet") {
2269
+ if (p.dataType.objectApiName) {
2270
+ referencedObjectDefs.add(enhancedOntology.requireObjectType(p.dataType.objectApiName));
2271
+ }
2272
+ if (p.dataType.objectTypeApiName) {
2273
+ referencedObjectDefs.add(enhancedOntology.requireObjectType(p.dataType.objectTypeApiName));
2274
+ }
2275
+ }
2276
+ if (p.dataType.type === "array" && (p.dataType.subType.type === "object" || p.dataType.subType.type === "objectSet")) {
2277
+ if (p.dataType.subType.objectApiName) {
2278
+ referencedObjectDefs.add(enhancedOntology.requireObjectType(p.dataType.subType.objectApiName));
2279
+ }
2280
+ if (p.dataType.subType.objectTypeApiName) {
2281
+ referencedObjectDefs.add(enhancedOntology.requireObjectType(p.dataType.subType.objectTypeApiName));
2282
+ }
2283
+ }
2284
+ }
2285
+ const imports = getObjectImports(referencedObjectDefs, void 0, currentFilePath, true);
2286
+ await fs2.writeFile(path16__default.join(rootOutDir, currentFilePath), await formatTs(`
2287
+ import type { ActionDefinition, ObjectActionDataType, ObjectSetActionDataType, VersionBound} from "@osdk/api";
2288
+ import type { ApplyActionOptions, ApplyBatchActionOptions, ActionReturnTypeForOptions, ActionParam } from '@osdk/client.api';
2289
+ import { $osdkMetadata} from "../../OntologyMetadata${importExt}";
2290
+ import type { $ExpectedClientVersion } from "../../OntologyMetadata${importExt}";
2291
+ ${imports}
2292
+
2293
+
2294
+ ${createV2Types()}
2295
+
2296
+ ${createV2Object()}
2297
+ `));
2298
+ }));
2299
+ const indexFileRelPath = path16__default.join("ontology", "actions.ts");
2300
+ await fs2.writeFile(path16__default.join(rootOutDir, indexFileRelPath), await formatTs(`
2301
+ ${Object.values(enhancedOntology.actionTypes).map((action) => {
2302
+ const exportConstLine = `export {${action.shortApiName} } from "${action.getImportPathRelTo(indexFileRelPath)}";`;
2303
+ return exportConstLine;
2304
+ }).join("\n")}
2305
+ ${Object.keys(ontology.actionTypes).length === 0 ? "export {};" : ""}
2306
+ `));
2307
+ }
2308
+ function extractReferencedObjectsFromAction2(actionType) {
2309
+ const referencedObjectsInParameters = Object.values(actionType.parameters).flatMap(({
2310
+ dataType
2311
+ }) => {
2312
+ const objectTypeReference = extractReferencedObjectsFromActionParameter2(dataType);
2313
+ return objectTypeReference ? [objectTypeReference] : [];
2314
+ });
2315
+ const referenceObjectsInEdits = actionType.operations.flatMap((value) => {
2316
+ switch (value.type) {
2317
+ case "createObject":
2318
+ return [value.objectTypeApiName];
2319
+ case "modifyObject":
2320
+ return [value.objectTypeApiName];
2321
+ case "deleteObject":
2322
+ case "createLink":
2323
+ case "deleteLink":
2324
+ return [];
2325
+ }
2326
+ });
2327
+ return [...referenceObjectsInEdits, ...referencedObjectsInParameters];
2328
+ }
2329
+ function extractReferencedObjectsFromActionParameter2(actionParameter) {
2330
+ switch (actionParameter.type) {
2331
+ case "objectSet":
2332
+ case "object":
2333
+ return actionParameter.objectTypeApiName;
2334
+ case "array":
2335
+ return extractReferencedObjectsFromActionParameter2(actionParameter.subType);
2336
+ case "string":
2337
+ case "boolean":
2338
+ case "attachment":
2339
+ case "date":
1560
2340
  case "double":
1561
- case "float":
1562
2341
  case "integer":
1563
- return "number";
1564
2342
  case "long":
1565
- return isReturnValue ? "string" : "string | number";
1566
- case "date":
1567
- return "LocalDate";
1568
2343
  case "timestamp":
1569
- return "Timestamp";
1570
- case "attachment":
1571
- return "Attachment";
1572
- case "array":
1573
- return `Array<${handleQueryDataType(dataType.subType, importedObjects, isReturnValue)}>`;
1574
- case "object": {
1575
- const objectType = dataType.objectTypeApiName;
1576
- importedObjects.add(objectType);
1577
- return isReturnValue ? objectType : `${objectType} | ${objectType}["__primaryKey"]`;
2344
+ return void 0;
2345
+ }
2346
+ }
2347
+ async function generatePerQueryDataFilesV2({
2348
+ fs: fs2,
2349
+ outDir: rootOutDir,
2350
+ ontology,
2351
+ importExt = ""
2352
+ }, v2) {
2353
+ const relOutDir = path16__default.join(".", "ontology", "queries");
2354
+ const outDir = path16__default.join(rootOutDir, "ontology", "queries");
2355
+ await fs2.mkdir(outDir, {
2356
+ recursive: true
2357
+ });
2358
+ await Promise.all(Object.values(ontology.queryTypes).map(async (query) => {
2359
+ await generateV2QueryFile(fs2, outDir, relOutDir, query, importExt, ontology);
2360
+ }));
2361
+ const indexFilePath = `${outDir}.ts`;
2362
+ await fs2.writeFile(indexFilePath, await formatTs(`
2363
+ ${Object.values(ontology.queryTypes).map((query) => `export * from "${query.getImportPathRelTo(relOutDir)}";`).join("\n")}
2364
+ ${Object.keys(ontology.queryTypes).length === 0 ? "export {};" : ""}
2365
+ `));
2366
+ }
2367
+ async function generateV2QueryFile(fs2, outDir, relOutDir, query, importExt, ontology) {
2368
+ const relFilePath = path16__default.join(relOutDir, `${query.shortApiName}.ts`);
2369
+ const objectTypes = getObjectTypeApiNamesFromQuery(query);
2370
+ const importObjects = getObjectImports2(ontology, objectTypes, relFilePath);
2371
+ const baseProps = deleteUndefineds(wireQueryTypeV2ToSdkQueryDefinitionNoParams(query.og));
2372
+ const outputBase = deleteUndefineds(wireQueryDataTypeToQueryDataTypeDefinition(query.output));
2373
+ const referencedObjectTypes = objectTypes.length > 0 ? objectTypes.map((apiNameObj) => `"${apiNameObj}"`).join("|") : "never";
2374
+ await fs2.writeFile(path16__default.join(outDir, `${query.shortApiName}.ts`), await formatTs(`
2375
+ import type { QueryDefinition , VersionBound} from "@osdk/api";
2376
+ import type { QueryParam, QueryResult } from "@osdk/client.api";
2377
+ import type { $ExpectedClientVersion } from "../../OntologyMetadata${importExt}";
2378
+ ${importObjects}
2379
+
2380
+ export namespace ${query.shortApiName} {
2381
+ export interface Signature {
2382
+ ${getDescriptionIfPresent(query.description)}
2383
+ (${Object.keys(query.parameters).length > 0 ? `query: ${query.paramsIdentifier}` : ""}): Promise<${getQueryParamType(ontology, wireQueryParameterV2ToQueryParameterDefinition({
2384
+ dataType: query.output
2385
+ }), "Result")}>
2386
+ }
2387
+
2388
+ ${Object.keys(query.parameters).length > 0 ? `
2389
+ export interface Parameters {
2390
+ ${stringify(query.parameters, {
2391
+ "*": (parameter, formatter, apiName) => {
2392
+ const q = wireQueryParameterV2ToQueryParameterDefinition(parameter);
2393
+ return [`
2394
+ ${queryParamJsDoc(wireQueryParameterV2ToQueryParameterDefinition(parameter), {
2395
+ apiName
2396
+ })}readonly "${apiName}"${q.nullable ? "?" : ""}`, `${getQueryParamType(ontology, q, "Param")}`];
1578
2397
  }
1579
- case "objectSet": {
1580
- const objectType = dataType.objectTypeApiName;
1581
- importedObjects.add(objectType);
1582
- return `ObjectSet<${objectType}>`;
2398
+ })}
2399
+ }
2400
+
2401
+ ` : ""}
2402
+
2403
+ export interface Definition extends QueryDefinition<
2404
+ "${query.fullApiName}",
2405
+ ${referencedObjectTypes},
2406
+ ${query.shortApiName}.Signature
2407
+ >, VersionBound<$ExpectedClientVersion>{
2408
+ ${stringify(baseProps)},
2409
+ parameters: {
2410
+ ${parameterDefsForType(ontology, query)}
2411
+ };
2412
+ output: {
2413
+ ${stringify(outputBase)},
2414
+ ${getLineFor__OsdkTargetType(ontology, query.output)}
2415
+ };
2416
+ }
2417
+
2418
+ }
2419
+
2420
+ /** @deprecated use \`${query.shortApiName}.Signature' instead */
2421
+ export type ${query.shortApiName} = ${query.shortApiName}.Signature;
2422
+
2423
+
2424
+
2425
+
2426
+
2427
+ export const ${query.shortApiName}: ${query.definitionIdentifier} = {
2428
+ ${stringify(baseProps)},
2429
+ parameters: {
2430
+ ${parametersForConst(query)}
2431
+ },
2432
+ output: {
2433
+ ${stringify(outputBase)},
2434
+ }
2435
+ };
2436
+ `));
2437
+ }
2438
+ function parametersForConst(query) {
2439
+ return stringify(query.parameters, {
2440
+ "*": (parameter, formatter) => formatter(deleteUndefineds(wireQueryParameterV2ToQueryParameterDefinition(parameter)))
2441
+ });
2442
+ }
2443
+ function parameterDefsForType(ontology, query) {
2444
+ return stringify(query.parameters, {
2445
+ "*": (parameter, valueFormatter, apiName) => [`${queryParamJsDoc(wireQueryParameterV2ToQueryParameterDefinition(parameter), {
2446
+ apiName
2447
+ })} ${apiName}`, ` {
2448
+ ${stringify(deleteUndefineds(wireQueryParameterV2ToQueryParameterDefinition(parameter)))},
2449
+ ${getLineFor__OsdkTargetType(ontology, parameter.dataType)}
2450
+ }`]
2451
+ });
2452
+ }
2453
+ function getLineFor__OsdkTargetType(ontology, qdt) {
2454
+ if (qdt.type === "object" || qdt.type === "objectSet") {
2455
+ return `__OsdkTargetType?: ${ontology.requireObjectType(qdt.objectTypeApiName).getImportedDefinitionIdentifier(true)}`;
2456
+ }
2457
+ return "";
2458
+ }
2459
+ function queryParamJsDoc(param, {
2460
+ apiName
2461
+ }) {
2462
+ let ret = `/**
2463
+ `;
2464
+ if (param.description) {
2465
+ if (param.description) {
2466
+ ret += ` * description: ${param.description}
2467
+ `;
1583
2468
  }
1584
- case "set":
1585
- return `Set<${handleQueryDataType(dataType.subType, importedObjects, isReturnValue)}>`;
1586
- case "struct":
1587
- const properties = dataType.fields.map((field) => {
1588
- const isNullable = isNullableQueryDataType(field.fieldType);
1589
- return `${field.name}${isNullable ? "?" : ""}: ${handleQueryDataType(field.fieldType, importedObjects, isReturnValue)}`;
1590
- });
1591
- return `{ ${properties.join(",\n")} }`;
1592
- case "union":
1593
- return dataType.unionTypes.map((type) => handleQueryDataType(type, importedObjects, isReturnValue)).filter((type) => type !== "null").join("|");
1594
- case "twoDimensionalAggregation":
1595
- dataType.valueType;
1596
- return `TwoDimensionalAggregation<
1597
- ${aggregationKeyToTypescriptType(dataType.keyType)},
1598
- ${aggregationValueToTypescriptType(dataType.valueType)}
1599
- >`;
1600
- case "threeDimensionalAggregation":
1601
- return `ThreeDimensionalAggregation<
1602
- ${aggregationKeyToTypescriptType(dataType.keyType)},
1603
- ${aggregationKeyToTypescriptType(dataType.valueType.keyType)},
1604
- ${aggregationValueToTypescriptType(dataType.valueType.valueType)}
1605
- >`;
1606
- case "null":
1607
- return "null";
1608
- case "unsupported":
1609
- throw new Error("Cannot generate queries for unsupported type");
1610
- default:
1611
- throw new Error(`Cannot generate queries for type ${dataType.type}`);
2469
+ } else {
2470
+ ret += ` * (no ontology metadata)
2471
+ `;
1612
2472
  }
2473
+ ret += ` */
2474
+ `;
2475
+ return ret;
1613
2476
  }
1614
- function aggregationKeyToTypescriptType(keyType) {
1615
- switch (keyType.type) {
1616
- case "boolean":
1617
- return "boolean";
1618
- case "double":
1619
- case "integer":
1620
- return "number";
1621
- case "string":
1622
- return "string";
1623
- case "date":
1624
- return "LocalDate";
1625
- case "timestamp":
1626
- return "Timestamp";
1627
- case "range":
1628
- return `Range<${aggregationRangeToTypescriptType(keyType.subType)}>`;
1629
- default:
1630
- throw new Error(`Unknown TwoDimensionalAggregation keyType ${keyType.type}`);
2477
+ function getObjectImports2(enhancedOntology, objectTypes, filePath) {
2478
+ let ret = "";
2479
+ for (const fqObjectApiName of objectTypes) {
2480
+ const obj = enhancedOntology.requireObjectType(fqObjectApiName);
2481
+ ret += `import type { ${obj.getDefinitionIdentifier(true)} as ${obj.getImportedDefinitionIdentifier(true)} } from "${obj.getImportPathRelTo(filePath)}";
2482
+ `;
1631
2483
  }
2484
+ return ret;
1632
2485
  }
1633
- function aggregationRangeToTypescriptType(subType) {
1634
- switch (subType.type) {
2486
+ function getQueryParamType(enhancedOntology, input, type) {
2487
+ let inner = `unknown /* ${input.type} */`;
2488
+ switch (input.type) {
1635
2489
  case "date":
1636
- return "LocalDate";
2490
+ inner = `Query${type}.PrimitiveType<${JSON.stringify("datetime")}>`;
2491
+ break;
2492
+ case "attachment":
2493
+ case "boolean":
1637
2494
  case "double":
2495
+ case "float":
1638
2496
  case "integer":
1639
- return "number";
2497
+ case "long":
2498
+ case "string":
2499
+ case "struct":
2500
+ case "threeDimensionalAggregation":
1640
2501
  case "timestamp":
1641
- return "Timestamp";
1642
- default:
1643
- throw new Error(`Unsupported QueryAggregationRangeSubType ${subType.type}`);
2502
+ case "twoDimensionalAggregation":
2503
+ inner = `Query${type}.PrimitiveType<${JSON.stringify(input.type)}>`;
2504
+ break;
2505
+ case "object":
2506
+ inner = `Query${type}.ObjectType<${enhancedOntology.requireObjectType(input.object).getImportedDefinitionIdentifier(true)}>`;
2507
+ break;
2508
+ case "objectSet":
2509
+ inner = `Query${type}.ObjectSetType<${enhancedOntology.requireObjectType(input.objectSet).getImportedDefinitionIdentifier(true)}>`;
2510
+ break;
2511
+ case "set":
2512
+ inner = `${type === "Param" ? "Readonly" : ""}Set<${getQueryParamType(enhancedOntology, input.set, type)}>`;
2513
+ break;
2514
+ case "union":
2515
+ inner = input.union.map((u) => getQueryParamType(enhancedOntology, u, type)).join(" | ");
2516
+ break;
1644
2517
  }
1645
- }
1646
- function aggregationValueToTypescriptType(valueType) {
1647
- switch (valueType.type) {
1648
- case "date":
1649
- return "LocalDate";
1650
- case "double":
1651
- return "number";
1652
- case "timestamp":
1653
- return "Timestamp";
1654
- default:
1655
- throw new Error(`Unsupported QueryAggregationValueType ${valueType.type}`);
2518
+ if (input.multiplicity && type === "Param") {
2519
+ return `ReadonlyArray<${inner}>`;
2520
+ } else if (input.multiplicity) {
2521
+ return `Array<${inner}>`;
1656
2522
  }
1657
- }
1658
- function sanitizeDocTypeName(type) {
1659
- return type.replace(/\s/g, "");
1660
- }
1661
-
1662
- // src/v1.1/generateClientSdkVersionOneDotOne.ts
1663
- async function generateClientSdkVersionOneDotOne(ontology, userAgent, fs2, outDir, packageType = "commonjs") {
1664
- const importExt = packageType === "module" ? ".js" : "";
1665
- const objectsDir = path16.join(outDir, "ontology", "objects");
1666
- const actionsDir = path16.join(outDir, "ontology", "actions");
1667
- const queriesDir = path16.join(outDir, "ontology", "queries");
1668
- await verifyOutDir(outDir, fs2);
1669
- await fs2.mkdir(outDir, {
1670
- recursive: true
1671
- });
1672
- const sanitizedOntology = sanitizeMetadata(ontology);
1673
- await generateFoundryClientFile(fs2, outDir, importExt);
1674
- await generateMetadataFile(sanitizedOntology, userAgent, fs2, outDir, importExt);
1675
- await generateOntologyIndexFile(fs2, path16.join(outDir, "ontology"));
1676
- await generateObjectsInterfaceFile(sanitizedOntology, fs2, objectsDir, importExt);
1677
- await generateObjectsInterfaceSupportFiles(sanitizedOntology, fs2, path16.join(objectsDir, "objects-api"), importExt);
1678
- await generatePerObjectInterfaceAndDataFiles(sanitizedOntology, fs2, objectsDir, importExt);
1679
- await generateActions(sanitizedOntology, fs2, actionsDir, importExt);
1680
- await generateBatchActions(sanitizedOntology, fs2, actionsDir, importExt);
1681
- await generateBulkActions(sanitizedOntology, fs2, actionsDir, importExt);
1682
- await generatePerActionDataFiles(sanitizedOntology, fs2, actionsDir, importExt, false);
1683
- await generateQueries(sanitizedOntology, fs2, queriesDir, importExt);
1684
- await generatePerQueryDataFiles(sanitizedOntology, fs2, queriesDir, importExt);
1685
- await generateIndexFile(fs2, outDir, importExt);
1686
- await generateBackCompatDeprecatedExports(fs2, outDir, importExt);
2523
+ return inner;
1687
2524
  }
1688
2525
  function __UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst(interfaceDef, ontology, v2 = false) {
1689
- const definition = deleteUndefineds(__UNSTABLE_wireInterfaceTypeV2ToSdkObjectDefinition(interfaceDef, v2));
1690
- const objectDefIdentifier = getObjectDefIdentifier(interfaceDef.apiName, v2);
2526
+ const definition = deleteUndefineds(__UNSTABLE_wireInterfaceTypeV2ToSdkObjectDefinition(interfaceDef.og, v2));
2527
+ const objectDefIdentifier = interfaceDef.getDefinitionIdentifier(v2);
1691
2528
  const parents = definition.implements?.map((p) => {
1692
2529
  !(ontology.interfaceTypes[p] != null) ? process.env.NODE_ENV !== "production" ? invariant(false, `Expected to find a parent interface named ${p} in the ontology and did not.`) : invariant(false) : void 0;
1693
- const it = deleteUndefineds(__UNSTABLE_wireInterfaceTypeV2ToSdkObjectDefinition(ontology.interfaceTypes[p], v2));
2530
+ const it = deleteUndefineds(__UNSTABLE_wireInterfaceTypeV2ToSdkObjectDefinition(ontology.requireInterfaceType(p, true).og, v2));
1694
2531
  return it;
1695
2532
  }) ?? [];
1696
2533
  const mergedProperties = {
@@ -1706,215 +2543,230 @@ function __UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst(interfaceDef, ontology,
1706
2543
  mergedProperties[apiName] = parent.properties[apiName];
1707
2544
  }
1708
2545
  }
1709
- const ogProperties = definition.properties;
2546
+ definition.properties;
1710
2547
  definition.properties = mergedProperties;
1711
- function localPropertyJsdoc(apiName) {
1712
- const property = definition.properties[apiName];
1713
- const isInherited = ogProperties[apiName] == null;
1714
- return propertyJsdoc(property, {
1715
- isInherited,
1716
- apiName
1717
- });
2548
+ function maybeStripNamespace2(q) {
2549
+ if (interfaceDef.apiNamespace && q.startsWith(`${interfaceDef.apiNamespace}.`)) {
2550
+ return q.slice(interfaceDef.apiNamespace.length + 1);
2551
+ } else {
2552
+ return q;
2553
+ }
1718
2554
  }
2555
+ const objectSetIdentifier = `${interfaceDef.shortApiName}.ObjectSet`;
2556
+ const propertyKeysIdentifier = `${interfaceDef.shortApiName}.PropertyKeys`;
2557
+ const osdkObjectPropsIdentifier = `${interfaceDef.shortApiName}.Props`;
2558
+ const osdkObjectStrictPropsIdentifier = `${interfaceDef.shortApiName}.StrictProps`;
2559
+ const osdkObjectLinksIdentifier = `OsdkObjectLinks$${objectDefIdentifier}`;
2560
+ const osdkObjectIdentifier = `${interfaceDef.shortApiName}.OsdkObject`;
2561
+ const ids = {
2562
+ objectDefIdentifier: `${interfaceDef.shortApiName}.Definition`,
2563
+ osdkObjectLinksIdentifier,
2564
+ osdkObjectPropsIdentifier,
2565
+ osdkObjectStrictPropsIdentifier,
2566
+ objectSetIdentifier,
2567
+ osdkObjectIdentifier,
2568
+ propertyKeysIdentifier
2569
+ };
1719
2570
  function getV2Types() {
1720
- return `
1721
- export interface ${objectDefIdentifier} extends InterfaceDefinition<"${interfaceDef.apiName}", ${interfaceDef.apiName}>, VersionBound<$ExpectedClientVersion> {
1722
- osdkMetadata: typeof $osdkMetadata;
1723
- ${stringify(definition, {
1724
- osdkMetadata: () => void 0,
1725
- type: () => void 0,
1726
- apiName: () => void 0,
1727
- links: (_value) => `{
1728
- ${stringify(definition.links, {
1729
- "*": (definition2) => `ObjectTypeLinkDefinition<${getObjectDefIdentifier(definition2.targetType, v2)}, ${definition2.multiplicity}>`
1730
- })}
1731
- }`,
1732
- properties: (properties) => `{
1733
- ${stringify(properties, {
1734
- "*": (propertyDefinition, _, key) => [`${localPropertyJsdoc(key)}${key}`, `PropertyDef<"${propertyDefinition.type}", "${propertyDefinition.nullable ? "nullable" : "non-nullable"}", "${propertyDefinition.multiplicity ? "array" : "single"}">`]
1735
- })}
1736
- }`
2571
+ return `import type {
2572
+ AggregateOpts as $AggregateOpts,
2573
+ AggregateOptsThatErrorsAndDisallowsOrderingWithMultipleGroupBy as $AggregateOptsThatErrorsAndDisallowsOrderingWithMultipleGroupBy,
2574
+ AggregationsResults as $AggregationsResults,
2575
+ Augments as $Augments,
2576
+ ConvertProps as $ConvertProps,
2577
+ DefaultToFalse as $DefaultToFalse,
2578
+ FetchPageArgs as $FetchPageArgs,
2579
+ FetchPageResult as $FetchPageResult,
2580
+ LinkedType as $LinkedType,
2581
+ LinkNames as $LinkNames,
2582
+ NullabilityAdherence as $NullabilityAdherence,
2583
+ NullabilityAdherenceDefault as $NullabilityAdherenceDefault,
2584
+ ObjectSet as $ObjectSet,
2585
+ Osdk as $Osdk,
2586
+ OsdkObject as $OsdkObject,
2587
+ OsdkObjectLinksEntry as $OsdkObjectLinksEntry,
2588
+ OsdkObjectLinksObject as $OsdkObjectLinksObject,
2589
+ OsdkObjectPropertyType as $OsdkObjectPropertyType,
2590
+ PageResult as $PageResult,
2591
+ PropertyValueClientToWire as $PropertyValueClientToWire,
2592
+ PropertyValueWireToClient as $PropType,
2593
+ Result as $Result,
2594
+ SelectArg as $SelectArg,
2595
+ SingleLinkAccessor as $SingleLinkAccessor,
2596
+ SingleOsdkResult as $SingleOsdkResult,
2597
+ ValidToFrom as $ValidToFrom,
2598
+ WhereClause as $WhereClause,
2599
+ } from "@osdk/client.api";
2600
+ import type * as $clientApi from "@osdk/client.api";
2601
+ import type {
2602
+ ObjectOrInterfacePropertyKeysFrom2 as $ObjectOrInterfacePropertyKeysFrom2,
2603
+ ObjectTypeLinkDefinition as $ObjectTypeLinkDefinition,
2604
+ ObjectTypeDefinition as $ObjectTypeDefinition,
2605
+ InterfaceDefinition as $InterfaceDefinition,
2606
+ } from "@osdk/api";
2607
+
2608
+
2609
+
2610
+ ${Object.keys(definition.links).length === 0 ? `export type ${osdkObjectLinksIdentifier} = never;` : `
2611
+ export interface ${osdkObjectLinksIdentifier} {
2612
+ ${stringify(definition.links, {
2613
+ "*": (definition2) => {
2614
+ const linkTarget = ontology.requireObjectType(definition2.targetType).getImportedDefinitionIdentifier(v2);
2615
+ return `${definition2.multiplicity ? `${linkTarget}["objectSet"]` : `SingleLinkAccessor<${linkTarget}>`}
2616
+ `;
2617
+ }
1737
2618
  })}
1738
- }
2619
+ }
2620
+ `}
2621
+
2622
+ export namespace ${interfaceDef.shortApiName} {
2623
+
2624
+ ${createPropertyKeys(interfaceDef)}
2625
+
2626
+
2627
+ ${createProps(interfaceDef, "Props", false)}
2628
+ ${createProps(interfaceDef, "StrictProps", true)}
2629
+
2630
+
2631
+ ${createObjectSet(interfaceDef, ids)}
2632
+
2633
+ ${createDefinition(interfaceDef, ontology, "Definition", ids)}
2634
+
2635
+ ${createOsdkObject(interfaceDef, "OsdkObject", ids)}
2636
+
2637
+ }
2638
+
2639
+
2640
+
2641
+
2642
+ /** @deprecated use ${interfaceDef.shortApiName}.Definition **/
2643
+ export type ${objectDefIdentifier} = ${interfaceDef.shortApiName}.Definition;
2644
+
2645
+
2646
+
1739
2647
 
1740
2648
  `;
1741
2649
  }
1742
2650
  const imports = [];
1743
2651
  return `${imports.join("\n")}
1744
-
1745
2652
  ${v2 ? getV2Types() : ""}
1746
2653
 
1747
- export const ${definition.apiName}: ${objectDefIdentifier} = {
2654
+ export const ${interfaceDef.shortApiName}: ${interfaceDef.shortApiName}.Definition = {
1748
2655
  osdkMetadata: $osdkMetadata,
2656
+ objectSet: undefined as any,
2657
+ props: undefined as any,
2658
+ strictProps: undefined as any,
1749
2659
  ${stringify(definition, {
1750
- osdkMetadata: () => void 0
2660
+ osdkMetadata: () => void 0,
2661
+ properties: (properties) => `{
2662
+ ${stringify(properties, {
2663
+ "*": (propertyDefinition, _, key) => [`"${maybeStripNamespace2(key)}"`, _(propertyDefinition)]
2664
+ })}
2665
+ }`
1751
2666
  })}
1752
2667
 
1753
2668
  };`;
1754
2669
  }
1755
- var ExpectedOsdkVersion = "0.21.0";
1756
- async function generateOntologyMetadataFile(ontology, userAgent, fs2, outDir) {
1757
- fs2.writeFile(path16__default.join(outDir, "OntologyMetadata.ts"), await formatTs(`
1758
- import { OntologyMetadata as OM } from "@osdk/api";
1759
-
1760
- export type $ExpectedClientVersion = "${ExpectedOsdkVersion}";
1761
- export const $osdkMetadata = { extraUserAgent: "${userAgent}" };
1762
-
1763
- export interface OntologyMetadata extends OM<$ExpectedClientVersion> {};
1764
-
1765
- export const OntologyMetadata: OntologyMetadata = {
1766
- expectsClientVersion: "${ExpectedOsdkVersion}",
1767
- ontologyRid: "${ontology.ontology.rid}",
1768
- ontologyApiName: "${ontology.ontology.apiName}",
1769
- userAgent: "${userAgent}",
1770
- };
1771
- `));
1772
- }
1773
2670
 
1774
2671
  // src/v2.0/generateClientSdkVersionTwoPointZero.ts
1775
- async function generateClientSdkVersionTwoPointZero(ontology, userAgent, fs2, outDir, packageType = "commonjs") {
1776
- await verifyOutDir(outDir, fs2);
1777
- const sanitizedOntology = sanitizeMetadata(ontology);
1778
- const objectNames = Object.keys(sanitizedOntology.objectTypes).sort((a, b) => a.localeCompare(b));
1779
- const actionNames = Object.keys(sanitizedOntology.actionTypes).sort((a, b) => a.localeCompare(b));
1780
- const queryNames = Object.keys(sanitizedOntology.queryTypes).sort((a, b) => a.localeCompare(b));
1781
- const interfaceNames = Object.keys(sanitizedOntology.interfaceTypes ?? {}).sort((a, b) => a.localeCompare(b));
1782
- const importExt = packageType === "module" ? ".js" : "";
1783
- await fs2.mkdir(outDir, {
1784
- recursive: true
1785
- });
1786
- fs2.writeFile(path16__default.join(outDir, "index.ts"), await formatTs(`
1787
- export { Ontology } from "./Ontology${importExt}";
1788
- export * from "./ontology/actions/index${importExt}";
2672
+ async function generateRootIndexTsFile({
2673
+ fs: fs2,
2674
+ outDir,
2675
+ importExt,
2676
+ ontologyApiNamespace
2677
+ }) {
2678
+ fs2.writeFile(path16__default.join(outDir, "index.ts"), await formatTs(`${ontologyApiNamespace == null ? `export { $ontologyRid } from "./OntologyMetadata${importExt}";` : ``}
2679
+ export * from "./ontology/actions${importExt}";
1789
2680
  export * from "./ontology/objects${importExt}";
1790
2681
  export * from "./ontology/interfaces${importExt}";
1791
- export * from "./ontology/queries/index${importExt}";
1792
- `));
1793
- await generateOntologyMetadataFile(sanitizedOntology, userAgent, fs2, outDir);
1794
- await fs2.writeFile(path16__default.join(outDir, "Ontology.ts"), await formatTs(`
1795
- import type { OntologyDefinition } from "@osdk/api";
1796
- import * as Actions from "./ontology/actions/index${importExt}";
1797
- import * as Objects from "./ontology/objects${importExt}";
1798
- import * as Interfaces from "./ontology/interfaces${importExt}";
1799
- import * as Queries from "./ontology/queries/index${importExt}";
1800
- import { OntologyMetadata } from "./OntologyMetadata${importExt}";
1801
-
1802
- export interface Ontology extends OntologyDefinition<${stringUnionFrom2(objectNames)}> {
1803
- metadata: OntologyMetadata,
1804
- objects: {
1805
- ${objectNames.map((objectName) => {
1806
- return `${objectName}: Objects.${objectName}`;
1807
- }).join(",\n")}
1808
- },
1809
- actions: {
1810
- ${actionNames.map((actionName) => {
1811
- return `${actionName}: typeof Actions.${actionName}`;
1812
- }).join(",\n")}
1813
- },
1814
- queries: {
1815
- ${queryNames.map((queryName) => {
1816
- return `${queryName}: typeof Queries.${queryName}`;
1817
- }).join(",\n")}
1818
- },
1819
- interfaces: {
1820
- ${interfaceNames.map((objectName) => {
1821
- return `${objectName}: Interfaces.${objectName}`;
1822
- }).join(",\n")}
1823
- }
1824
- }
1825
-
1826
- export const Ontology: Ontology = {
1827
- metadata: OntologyMetadata,
1828
- objects: {
1829
- ${objectNames.map((objectName) => {
1830
- return `${objectName}: Objects.${objectName}`;
1831
- }).join(",\n")}
1832
-
1833
- },
1834
- actions: {
1835
- ${actionNames.map((actionName) => {
1836
- return `${actionName}: Actions.${actionName}`;
1837
- }).join(",\n")}
1838
- },
1839
- queries: {
1840
- ${queryNames.map((queryName) => {
1841
- return `${queryName}: Queries.${queryName}`;
1842
- }).join(",\n")}
1843
- },
1844
- interfaces: {
1845
- ${interfaceNames.map((objectName) => {
1846
- return `${objectName}: Interfaces.${objectName}`;
1847
- }).join(",\n")}
1848
-
1849
- }
1850
- };
1851
-
2682
+ export * from "./ontology/queries${importExt}";
1852
2683
  `));
2684
+ }
2685
+ async function generateEachObjectFile(ctx) {
2686
+ const {
2687
+ fs: fs2,
2688
+ outDir,
2689
+ ontology,
2690
+ importExt
2691
+ } = ctx;
1853
2692
  await fs2.mkdir(path16__default.join(outDir, "ontology", "objects"), {
1854
2693
  recursive: true
1855
2694
  });
1856
- for (const name of objectNames) {
1857
- const obj = ontology.objectTypes[name];
1858
- await fs2.writeFile(path16__default.join(outDir, "ontology", `objects`, `${name}.ts`), await formatTs(`
1859
- import type { ObjectTypeDefinition, VersionBound, ObjectTypeLinkDefinition, PropertyDef } from "@osdk/api";
1860
- import { Osdk } from "@osdk/client.api";
2695
+ for (const obj of Object.values(ontology.objectTypes)) {
2696
+ const relPath = path16__default.join(".", "ontology", `objects`, `${obj.shortApiName}.ts`);
2697
+ const outFilePath = path16__default.join(outDir, relPath);
2698
+ await fs2.writeFile(outFilePath, await formatTs(`
2699
+ import type { VersionBound as $VersionBound, PropertyDef as $PropertyDef } from "@osdk/api";
2700
+ import type { Osdk } from "@osdk/client.api";
1861
2701
  import { $osdkMetadata } from "../../OntologyMetadata${importExt}";
1862
2702
  import type { $ExpectedClientVersion } from "../../OntologyMetadata${importExt}";
1863
-
1864
- ${wireObjectTypeV2ToSdkObjectConst(obj, importExt, true)}
2703
+ ${wireObjectTypeV2ToSdkObjectConstV2(obj.og, ctx, relPath)}
1865
2704
  `));
1866
2705
  }
1867
- await generateOntologyInterfaces(fs2, outDir, interfaceNames, ontology, importExt);
2706
+ }
2707
+ async function generateClientSdkVersionTwoPointZero(ontology, userAgent, fs2, outDir, packageType = "commonjs", ontologyApiNamespace, apiNamespacePackageMap = /* @__PURE__ */ new Map()) {
2708
+ const importExt = packageType === "module" ? ".js" : "";
2709
+ await verifyOutDir(outDir, fs2);
2710
+ const sanitizedOntology = sanitizeMetadata(ontology);
2711
+ await fs2.mkdir(outDir, {
2712
+ recursive: true
2713
+ });
2714
+ const enhancedOntology = enhanceOntology(sanitizedOntology, ontologyApiNamespace, apiNamespacePackageMap, importExt);
2715
+ const ctx = {
2716
+ sanitizedOntology,
2717
+ ontology: enhancedOntology,
2718
+ importExt,
2719
+ fs: fs2,
2720
+ outDir,
2721
+ ontologyApiNamespace,
2722
+ apiNamespacePackageMap
2723
+ };
2724
+ await generateRootIndexTsFile(ctx);
2725
+ await generateOntologyMetadataFile(ctx, userAgent);
2726
+ await generateEachObjectFile(ctx);
2727
+ await generateOntologyInterfaces(ctx);
1868
2728
  const actionsDir = path16__default.join(outDir, "ontology", "actions");
1869
2729
  await fs2.mkdir(actionsDir, {
1870
2730
  recursive: true
1871
2731
  });
1872
- await generatePerActionDataFiles(sanitizedOntology, fs2, actionsDir, importExt, true);
2732
+ await generatePerActionDataFiles(ctx);
1873
2733
  await fs2.writeFile(path16__default.join(outDir, "ontology", "objects.ts"), await formatTs(`
1874
- ${Object.keys(ontology.objectTypes).sort((a, b) => a.localeCompare(b)).map((apiName) => `export * from "./objects/${apiName}${importExt}";`).join("\n")}
2734
+ ${Object.values(enhancedOntology.objectTypes).map((objType) => `export * from "./objects/${objType.shortApiName}${importExt}";`).join("\n")}
1875
2735
  ${Object.keys(ontology.objectTypes).length === 0 ? "export {};" : ""}
1876
2736
  `));
1877
- const queriesDir = path16__default.join(outDir, "ontology", "queries");
1878
- await fs2.mkdir(queriesDir, {
1879
- recursive: true
1880
- });
1881
- await generatePerQueryDataFiles(sanitizedOntology, fs2, queriesDir, importExt, true);
1882
- }
1883
- function stringUnionFrom2(values) {
1884
- if (values.length === 0) {
1885
- return "never";
1886
- } else {
1887
- return values.map((v) => `"${v}"`).join("|");
1888
- }
2737
+ await generatePerQueryDataFilesV2(ctx);
1889
2738
  }
1890
- async function generateOntologyInterfaces(fs2, outDir, interfaceNames, ontology, importExt) {
2739
+ async function generateOntologyInterfaces({
2740
+ fs: fs2,
2741
+ outDir,
2742
+ ontology,
2743
+ importExt
2744
+ }) {
1891
2745
  const interfacesDir = path16__default.join(outDir, "ontology", "interfaces");
1892
2746
  await fs2.mkdir(interfacesDir, {
1893
2747
  recursive: true
1894
2748
  });
1895
- for (const name of interfaceNames) {
1896
- const obj = ontology.interfaceTypes[name];
1897
- await fs2.writeFile(path16__default.join(interfacesDir, `${name}.ts`), await formatTs(`
2749
+ for (const obj of Object.values(ontology.interfaceTypes)) {
2750
+ await fs2.writeFile(path16__default.join(interfacesDir, `${obj.shortApiName}.ts`), await formatTs(`
1898
2751
 
1899
- import type { InterfaceDefinition, PropertyDef, VersionBound } from "@osdk/api";
2752
+ import type { PropertyDef as $PropertyDef, VersionBound as $VersionBound } from "@osdk/api";
1900
2753
  import { $osdkMetadata, $expectedClientVersion } from "../../OntologyMetadata${importExt}";
1901
2754
  import type { $ExpectedClientVersion } from "../../OntologyMetadata${importExt}";
1902
-
1903
2755
  ${__UNSTABLE_wireInterfaceTypeV2ToSdkObjectConst(obj, ontology, true)}
1904
2756
  `));
1905
2757
  }
1906
2758
  await fs2.writeFile(interfacesDir + ".ts", await formatTs(`
1907
- ${Object.keys(ontology.interfaceTypes ?? {}).map((apiName) => `export * from "./interfaces/${apiName}${importExt}";`).join("\n")}
1908
- ${Object.keys(ontology.interfaceTypes ?? {}).length === 0 ? "export {}" : ""}
2759
+ ${Object.values(ontology.interfaceTypes).map((interfaceType) => `export * from "./interfaces/${interfaceType.shortApiName}${importExt}";`).join("\n")}
2760
+ ${Object.keys(ontology.interfaceTypes).length === 0 ? "export {}" : ""}
1909
2761
  `));
1910
2762
  }
1911
2763
 
1912
2764
  // src/generateClientSdkPackage.ts
1913
- async function generateClientSdkPackage(packageName, packageVersion, sdkVersion, baseOutDir, ontology, minimalFs, dependencyVersions, cliVersion) {
2765
+ async function generateClientSdkPackage(packageName, packageVersion, sdkVersion, baseOutDir, ontology, minimalFs, dependencyVersions, cliVersion, ontologyApiNamespace, apiNamespacePackageMap) {
1914
2766
  if (!packageName) throw new Error("Package name is require");
1915
2767
  for (const packageType of ["module", "commonjs"]) {
1916
2768
  const outDir = path16.join(baseOutDir, "dist", packageType);
1917
- await (sdkVersion === "1.1" ? generateClientSdkVersionOneDotOne : sdkVersion === "2.0" ? generateClientSdkVersionTwoPointZero : void 0)(ontology, `typescript-sdk/${packageVersion} osdk-cli/${cliVersion}`, minimalFs, outDir, packageType);
2769
+ await (sdkVersion === "1.1" ? generateClientSdkVersionOneDotOne : sdkVersion === "2.0" ? generateClientSdkVersionTwoPointZero : void 0)(ontology, `typescript-sdk/${packageVersion} osdk-cli/${cliVersion}`, minimalFs, outDir, packageType, ontologyApiNamespace, apiNamespacePackageMap);
1918
2770
  await fs.promises.mkdir(outDir, {
1919
2771
  recursive: true
1920
2772
  });