@servicenow/sdk-build-plugins 2.0.1

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 (166) hide show
  1. package/dist/AttachmentPlugin.d.ts +253 -0
  2. package/dist/AttachmentPlugin.js +216 -0
  3. package/dist/AttachmentPlugin.js.map +1 -0
  4. package/dist/BusinessRulePlugin.d.ts +56 -0
  5. package/dist/BusinessRulePlugin.js +171 -0
  6. package/dist/BusinessRulePlugin.js.map +1 -0
  7. package/dist/CrossScopePrivilegePlugin.d.ts +22 -0
  8. package/dist/CrossScopePrivilegePlugin.js +42 -0
  9. package/dist/CrossScopePrivilegePlugin.js.map +1 -0
  10. package/dist/DefaultPlugin.d.ts +71 -0
  11. package/dist/DefaultPlugin.js +238 -0
  12. package/dist/DefaultPlugin.js.map +1 -0
  13. package/dist/IdPlugin.d.ts +17 -0
  14. package/dist/IdPlugin.js +45 -0
  15. package/dist/IdPlugin.js.map +1 -0
  16. package/dist/ListPlugin.d.ts +91 -0
  17. package/dist/ListPlugin.js +398 -0
  18. package/dist/ListPlugin.js.map +1 -0
  19. package/dist/PropertyPlugin.d.ts +122 -0
  20. package/dist/PropertyPlugin.js +165 -0
  21. package/dist/PropertyPlugin.js.map +1 -0
  22. package/dist/ScriptTemplatePlugin.d.ts +31 -0
  23. package/dist/ScriptTemplatePlugin.js +208 -0
  24. package/dist/ScriptTemplatePlugin.js.map +1 -0
  25. package/dist/UserPreferencePlugin.d.ts +16 -0
  26. package/dist/UserPreferencePlugin.js +30 -0
  27. package/dist/UserPreferencePlugin.js.map +1 -0
  28. package/dist/aclAndRole/AclPlugin.d.ts +117 -0
  29. package/dist/aclAndRole/AclPlugin.js +285 -0
  30. package/dist/aclAndRole/AclPlugin.js.map +1 -0
  31. package/dist/aclAndRole/RolePlugin.d.ts +58 -0
  32. package/dist/aclAndRole/RolePlugin.js +152 -0
  33. package/dist/aclAndRole/RolePlugin.js.map +1 -0
  34. package/dist/aclAndRole/Util.d.ts +3 -0
  35. package/dist/aclAndRole/Util.js +106 -0
  36. package/dist/aclAndRole/Util.js.map +1 -0
  37. package/dist/app/ApplicationMenuPlugin.d.ts +32 -0
  38. package/dist/app/ApplicationMenuPlugin.js +106 -0
  39. package/dist/app/ApplicationMenuPlugin.js.map +1 -0
  40. package/dist/atf/ATFComposer.d.ts +492 -0
  41. package/dist/atf/ATFComposer.js +2717 -0
  42. package/dist/atf/ATFComposer.js.map +1 -0
  43. package/dist/atf/TestPlugin.d.ts +31 -0
  44. package/dist/atf/TestPlugin.js +95 -0
  45. package/dist/atf/TestPlugin.js.map +1 -0
  46. package/dist/atf/index.d.ts +1 -0
  47. package/dist/atf/index.js +9 -0
  48. package/dist/atf/index.js.map +1 -0
  49. package/dist/db/ColumnPlugins.d.ts +278 -0
  50. package/dist/db/ColumnPlugins.js +112 -0
  51. package/dist/db/ColumnPlugins.js.map +1 -0
  52. package/dist/db/RecordPlugin.d.ts +208 -0
  53. package/dist/db/RecordPlugin.js +287 -0
  54. package/dist/db/RecordPlugin.js.map +1 -0
  55. package/dist/db/TablePlugin.d.ts +742 -0
  56. package/dist/db/TablePlugin.js +1249 -0
  57. package/dist/db/TablePlugin.js.map +1 -0
  58. package/dist/db/index.d.ts +3 -0
  59. package/dist/db/index.js +27 -0
  60. package/dist/db/index.js.map +1 -0
  61. package/dist/index.d.ts +16 -0
  62. package/dist/index.js +51 -0
  63. package/dist/index.js.map +1 -0
  64. package/dist/scriptedRESTAPI/RESTDeserializationUtils.d.ts +12 -0
  65. package/dist/scriptedRESTAPI/RESTDeserializationUtils.js +371 -0
  66. package/dist/scriptedRESTAPI/RESTDeserializationUtils.js.map +1 -0
  67. package/dist/scriptedRESTAPI/RESTSerializationUtils.d.ts +15 -0
  68. package/dist/scriptedRESTAPI/RESTSerializationUtils.js +177 -0
  69. package/dist/scriptedRESTAPI/RESTSerializationUtils.js.map +1 -0
  70. package/dist/scriptedRESTAPI/RestApiPlugin.d.ts +144 -0
  71. package/dist/scriptedRESTAPI/RestApiPlugin.js +318 -0
  72. package/dist/scriptedRESTAPI/RestApiPlugin.js.map +1 -0
  73. package/dist/scriptedRESTAPI/RestSchemaUtils.d.ts +190 -0
  74. package/dist/scriptedRESTAPI/RestSchemaUtils.js +53 -0
  75. package/dist/scriptedRESTAPI/RestSchemaUtils.js.map +1 -0
  76. package/dist/scriptedRESTAPI/RestUtils.d.ts +75 -0
  77. package/dist/scriptedRESTAPI/RestUtils.js +469 -0
  78. package/dist/scriptedRESTAPI/RestUtils.js.map +1 -0
  79. package/dist/scripts/ClientScriptPlugin.d.ts +43 -0
  80. package/dist/scripts/ClientScriptPlugin.js +190 -0
  81. package/dist/scripts/ClientScriptPlugin.js.map +1 -0
  82. package/dist/scripts/scriptUtils.d.ts +15 -0
  83. package/dist/scripts/scriptUtils.js +83 -0
  84. package/dist/scripts/scriptUtils.js.map +1 -0
  85. package/dist/uxf/ExperiencePlugin.d.ts +22 -0
  86. package/dist/uxf/ExperiencePlugin.js +55 -0
  87. package/dist/uxf/ExperiencePlugin.js.map +1 -0
  88. package/dist/uxf/RoutesPlugin.d.ts +22 -0
  89. package/dist/uxf/RoutesPlugin.js +176 -0
  90. package/dist/uxf/RoutesPlugin.js.map +1 -0
  91. package/dist/uxf/UxfFormulaParser/cleanUxValue.d.ts +4 -0
  92. package/dist/uxf/UxfFormulaParser/cleanUxValue.js +65 -0
  93. package/dist/uxf/UxfFormulaParser/cleanUxValue.js.map +1 -0
  94. package/dist/uxf/UxfFormulaParser/grammerParser/api.d.ts +189 -0
  95. package/dist/uxf/UxfFormulaParser/grammerParser/api.js +158 -0
  96. package/dist/uxf/UxfFormulaParser/grammerParser/api.js.map +1 -0
  97. package/dist/uxf/UxfFormulaParser/grammerParser/clientTransformMap.d.ts +13 -0
  98. package/dist/uxf/UxfFormulaParser/grammerParser/clientTransformMap.js +604 -0
  99. package/dist/uxf/UxfFormulaParser/grammerParser/clientTransformMap.js.map +1 -0
  100. package/dist/uxf/UxfFormulaParser/grammerParser/grammarParser.d.ts +12 -0
  101. package/dist/uxf/UxfFormulaParser/grammerParser/grammarParser.js +551 -0
  102. package/dist/uxf/UxfFormulaParser/grammerParser/grammarParser.js.map +1 -0
  103. package/dist/uxf/UxfFormulaParser/grammerParser/spanHelpers.d.ts +31 -0
  104. package/dist/uxf/UxfFormulaParser/grammerParser/spanHelpers.js +64 -0
  105. package/dist/uxf/UxfFormulaParser/grammerParser/spanHelpers.js.map +1 -0
  106. package/dist/uxf/UxfFormulaParser/index.d.ts +3 -0
  107. package/dist/uxf/UxfFormulaParser/index.js +11 -0
  108. package/dist/uxf/UxfFormulaParser/index.js.map +1 -0
  109. package/dist/uxf/UxfFormulaParser/parser.d.ts +8 -0
  110. package/dist/uxf/UxfFormulaParser/parser.js +87 -0
  111. package/dist/uxf/UxfFormulaParser/parser.js.map +1 -0
  112. package/dist/uxf/UxfFormulaParser/utils/getErrorMsg.d.ts +8 -0
  113. package/dist/uxf/UxfFormulaParser/utils/getErrorMsg.js +17 -0
  114. package/dist/uxf/UxfFormulaParser/utils/getErrorMsg.js.map +1 -0
  115. package/dist/uxf/constants.d.ts +2 -0
  116. package/dist/uxf/constants.js +8 -0
  117. package/dist/uxf/constants.js.map +1 -0
  118. package/dist/uxf/index.d.ts +2 -0
  119. package/dist/uxf/index.js +11 -0
  120. package/dist/uxf/index.js.map +1 -0
  121. package/dist/uxf/tectonicIdGenerator.d.ts +12 -0
  122. package/dist/uxf/tectonicIdGenerator.js +102 -0
  123. package/dist/uxf/tectonicIdGenerator.js.map +1 -0
  124. package/license +9 -0
  125. package/package.json +42 -0
  126. package/src/AttachmentPlugin.ts +262 -0
  127. package/src/BusinessRulePlugin.ts +251 -0
  128. package/src/CrossScopePrivilegePlugin.ts +54 -0
  129. package/src/DefaultPlugin.ts +272 -0
  130. package/src/IdPlugin.ts +47 -0
  131. package/src/ListPlugin.ts +497 -0
  132. package/src/PropertyPlugin.ts +218 -0
  133. package/src/ScriptTemplatePlugin.ts +223 -0
  134. package/src/UserPreferencePlugin.ts +36 -0
  135. package/src/aclAndRole/AclPlugin.ts +410 -0
  136. package/src/aclAndRole/RolePlugin.ts +225 -0
  137. package/src/aclAndRole/Util.ts +104 -0
  138. package/src/app/ApplicationMenuPlugin.ts +158 -0
  139. package/src/atf/ATFComposer.ts +3356 -0
  140. package/src/atf/TestPlugin.ts +119 -0
  141. package/src/atf/index.ts +1 -0
  142. package/src/db/ColumnPlugins.ts +117 -0
  143. package/src/db/RecordPlugin.ts +391 -0
  144. package/src/db/TablePlugin.ts +1581 -0
  145. package/src/db/index.ts +3 -0
  146. package/src/index.ts +16 -0
  147. package/src/scriptedRESTAPI/RESTDeserializationUtils.ts +410 -0
  148. package/src/scriptedRESTAPI/RESTSerializationUtils.ts +227 -0
  149. package/src/scriptedRESTAPI/RestApiPlugin.ts +438 -0
  150. package/src/scriptedRESTAPI/RestSchemaUtils.ts +72 -0
  151. package/src/scriptedRESTAPI/RestUtils.ts +507 -0
  152. package/src/scripts/ClientScriptPlugin.ts +251 -0
  153. package/src/scripts/scriptUtils.ts +81 -0
  154. package/src/uxf/ExperiencePlugin.ts +64 -0
  155. package/src/uxf/RoutesPlugin.ts +215 -0
  156. package/src/uxf/UxfFormulaParser/cleanUxValue.ts +73 -0
  157. package/src/uxf/UxfFormulaParser/grammerParser/api.js +166 -0
  158. package/src/uxf/UxfFormulaParser/grammerParser/clientTransformMap.js +606 -0
  159. package/src/uxf/UxfFormulaParser/grammerParser/grammarParser.js +551 -0
  160. package/src/uxf/UxfFormulaParser/grammerParser/spanHelpers.js +65 -0
  161. package/src/uxf/UxfFormulaParser/index.ts +4 -0
  162. package/src/uxf/UxfFormulaParser/parser.ts +64 -0
  163. package/src/uxf/UxfFormulaParser/utils/getErrorMsg.ts +13 -0
  164. package/src/uxf/constants.ts +4 -0
  165. package/src/uxf/index.ts +2 -0
  166. package/src/uxf/tectonicIdGenerator.ts +81 -0
@@ -0,0 +1,1249 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.dynamic_value_mapping = exports.ColumnSchemaBootstrapAttributes = exports.TableSchemaBootstrapAttributes = exports.Documentation = exports.TableSchemaBootstrap = exports.ColumnSchema = exports.TableSchemaFull = exports.callerAccess = void 0;
27
+ exports.transformColumnData = transformColumnData;
28
+ exports.SysNumber = SysNumber;
29
+ exports.generateColumnExpression = generateColumnExpression;
30
+ exports.createObjectExpression = createObjectExpression;
31
+ exports.factoryCreateValue = factoryCreateValue;
32
+ exports.getCallExpressionFromType = getCallExpressionFromType;
33
+ const db_1 = require("@servicenow/sdk-core/runtime/db");
34
+ const sdk_build_core_1 = require("@servicenow/sdk-build-core");
35
+ const fast_xml_parser_1 = require("fast-xml-parser");
36
+ const lodash_1 = require("lodash");
37
+ const zod_1 = require("zod");
38
+ const RecordPlugin_1 = require("./RecordPlugin");
39
+ const scriptUtils_1 = require("../scripts/scriptUtils");
40
+ const ts_morph_1 = require("ts-morph");
41
+ const sdk_project_1 = require("@servicenow/sdk-project");
42
+ const ScriptTemplatePlugin_1 = require("../ScriptTemplatePlugin");
43
+ const os = __importStar(require("os"));
44
+ const path = __importStar(require("path"));
45
+ /**
46
+ * The access levels are mapped to the following values on the platform
47
+ *
48
+ * - `none`: 0
49
+ * - `tracking`: 1
50
+ * - `restricted`: 2
51
+ *
52
+ */
53
+ exports.callerAccess = ['none', 'tracking', 'restricted'];
54
+ // Basic info needed for table references
55
+ exports.TableSchemaFull = zod_1.z.object({
56
+ /** lowercase, one word name. Numbers, letters and underscores only */
57
+ name: zod_1.z.string(),
58
+ /** Object literal of column names with <type>Column() calls as values.
59
+ * Ex. { column_name_1: StringColumn({...args}), column_name_2: IntegerColumn({...args}), }
60
+ * Import column definitions from `@servicenow/sdk-core/db`
61
+ */
62
+ schema: zod_1.z.record(zod_1.z.record(zod_1.z.any())).default({}),
63
+ /** Table as a string, this table will inherit schema from extends table.
64
+ * Escape with `` (import from `@servicenow/sdk-core/global`)
65
+ * if table definition not present locally */
66
+ extends: zod_1.z.string().optional(),
67
+ /** Will match name if not provided, cannot exceed 80 characters */
68
+ label: zod_1.z.string().max(80, 'Cannot exceed 80 characters').optional(),
69
+ /** Must match column name */
70
+ display: zod_1.z.string().optional(),
71
+ // Controls
72
+ extensible: zod_1.z.boolean().optional().default(false),
73
+ live_feed: zod_1.z.boolean().optional().default(false),
74
+ /** sys_number to create auto prefixing. Specify as Object literal */
75
+ auto_number: zod_1.z
76
+ .object({
77
+ prefix: zod_1.z.string().default('pre').optional(),
78
+ number: zod_1.z.number().default(1000).optional(),
79
+ number_of_digits: zod_1.z.number().default(7).optional(),
80
+ })
81
+ .optional(),
82
+ // Application Access
83
+ accessible_from: zod_1.z
84
+ .union([zod_1.z.literal('package_private'), zod_1.z.literal('public')])
85
+ .optional()
86
+ .default('public'),
87
+ caller_access: zod_1.z.enum(exports.callerAccess).optional(),
88
+ /** Array of read, update, create, delete actions (['read', 'update',...])*/
89
+ actions: zod_1.z
90
+ .array(zod_1.z.union([zod_1.z.literal('read'), zod_1.z.literal('update'), zod_1.z.literal('delete'), zod_1.z.literal('create')]))
91
+ .optional(),
92
+ allow_web_service_access: zod_1.z.boolean().optional().default(false),
93
+ allow_new_fields: zod_1.z.boolean().optional().default(false),
94
+ allow_ui_actions: zod_1.z.boolean().optional().default(false),
95
+ allow_client_scripts: zod_1.z.boolean().optional().default(false),
96
+ // From sys_dictionary
97
+ audit: zod_1.z.boolean().optional().default(false),
98
+ read_only: zod_1.z.boolean().optional().default(false),
99
+ text_index: zod_1.z.boolean().optional().default(false),
100
+ /** Object literal of key value pairs corresponding to attributes */
101
+ attributes: zod_1.z.record(zod_1.z.union([zod_1.z.string(), zod_1.z.number(), zod_1.z.boolean()])).optional(),
102
+ /** Array of objects [{ { name: <columnName>, element: ...,}...}] */
103
+ index: zod_1.z
104
+ .array(zod_1.z.object({
105
+ name: zod_1.z.string(),
106
+ unique: zod_1.z.boolean(),
107
+ element: zod_1.z.string(),
108
+ }))
109
+ .optional(),
110
+ });
111
+ const componentTables = ['sys_dictionary', 'sys_choice', 'sys_documentation'];
112
+ exports.ColumnSchema = zod_1.z.object({
113
+ entityKind: zod_1.z.string().optional(),
114
+ column_type: zod_1.z.string().optional(),
115
+ audit: zod_1.z.boolean().optional().default(false),
116
+ label: zod_1.z.string().optional(),
117
+ maxLength: zod_1.z.number().optional().default(40),
118
+ mandatory: zod_1.z.boolean().optional().default(false),
119
+ read_only: zod_1.z.boolean().optional().default(false),
120
+ default: zod_1.z.any().optional(),
121
+ attributes: zod_1.z.record(zod_1.z.string(), zod_1.z.union([zod_1.z.string(), zod_1.z.boolean(), zod_1.z.number()])).optional(),
122
+ referenceTable: zod_1.z.string().optional(),
123
+ dropdown: zod_1.z.enum(db_1.choiceDropdown).default('none').optional(),
124
+ choices: zod_1.z.record(zod_1.z.any()).or(zod_1.z.array(zod_1.z.any())).optional(),
125
+ choice_elements: zod_1.z.record(zod_1.z.any()).or(zod_1.z.array(zod_1.z.any())).optional(),
126
+ display: zod_1.z.boolean().default(false).optional(),
127
+ function_definition: zod_1.z.string().optional(),
128
+ dynamic_value_definitions: zod_1.z
129
+ .object({
130
+ type: zod_1.z.union([
131
+ zod_1.z.literal('dynamic_default'),
132
+ zod_1.z.literal('choices_from_other_table'),
133
+ zod_1.z.literal('calculated_value'),
134
+ zod_1.z.literal('dependent_field'),
135
+ ]),
136
+ })
137
+ .and(zod_1.z.any())
138
+ .optional(),
139
+ });
140
+ const BooleanFromString = zod_1.z
141
+ .string()
142
+ .transform((str) => str === 'true')
143
+ .or(zod_1.z.boolean())
144
+ .optional();
145
+ const IntFromString = zod_1.z
146
+ .string()
147
+ .transform((str) => (0, lodash_1.parseInt)(str))
148
+ .or(zod_1.z.number())
149
+ .optional();
150
+ // These fields transform from sys_db_object only, not bootstrap. (Except name, which is needed to match)
151
+ const DBObjectIncomingAttributes = zod_1.z.object({
152
+ name: RecordPlugin_1.TextStringSchema.or(zod_1.z.string()).optional(),
153
+ read_access: RecordPlugin_1.TextBooleanSchema.or(BooleanFromString).optional().default(true),
154
+ create_access: RecordPlugin_1.TextBooleanSchema.or(BooleanFromString).optional().default(true),
155
+ update_access: RecordPlugin_1.TextBooleanSchema.or(BooleanFromString).optional().default(true),
156
+ delete_access: RecordPlugin_1.TextBooleanSchema.or(BooleanFromString).optional().default(false),
157
+ ws_access: RecordPlugin_1.TextBooleanSchema.or(BooleanFromString).optional().default(true),
158
+ caller_access: RecordPlugin_1.TextNumberSchema.or(IntFromString)
159
+ .transform((val) => {
160
+ if (val) {
161
+ return exports.callerAccess[val];
162
+ }
163
+ return;
164
+ })
165
+ .optional(),
166
+ alter_access: RecordPlugin_1.TextBooleanSchema.or(BooleanFromString).optional().default(false),
167
+ client_scripts_access: RecordPlugin_1.TextBooleanSchema.or(BooleanFromString).optional().default(false),
168
+ actions_access: RecordPlugin_1.TextBooleanSchema.or(BooleanFromString).optional().default(false),
169
+ //configuration_access: TextBooleanSchema.or(BooleanFromString).optional().default(false),
170
+ is_extendable: RecordPlugin_1.TextBooleanSchema.or(BooleanFromString).optional().default(false),
171
+ // live_feed_enabled: TextBooleanSchema.or(BooleanFromString).optional().default(false),
172
+ access: RecordPlugin_1.TextStringSchema.or(zod_1.z.string()).optional(),
173
+ });
174
+ // Attributes in the element='collection' tag of bootstrap xml
175
+ exports.TableSchemaBootstrap = zod_1.z.object({
176
+ name: zod_1.z.string(),
177
+ extends: zod_1.z.string().optional(),
178
+ label: zod_1.z.string().max(80, 'Cannot exceed 80 characters').optional(),
179
+ // Controls
180
+ extensible: zod_1.z.boolean().optional().default(false),
181
+ live_feed: zod_1.z.boolean().optional().default(false),
182
+ auto_number: zod_1.z
183
+ .object({
184
+ prefix: zod_1.z.string().default('pre').optional(),
185
+ number: zod_1.z.number().default(1000).optional(),
186
+ number_of_digits: zod_1.z.number().default(7).optional(),
187
+ })
188
+ .optional(),
189
+ number_ref: zod_1.z.any().optional(),
190
+ // Application Access
191
+ accessible_from: zod_1.z
192
+ .union([zod_1.z.literal('public'), zod_1.z.literal('package_private')])
193
+ .optional()
194
+ .default('public'),
195
+ caller_access: zod_1.z.enum(exports.callerAccess).default('none').optional(),
196
+ actions: zod_1.z
197
+ .array(zod_1.z.union([zod_1.z.literal('read'), zod_1.z.literal('update'), zod_1.z.literal('delete'), zod_1.z.literal('create')]))
198
+ .default(['read'])
199
+ .optional(),
200
+ allow_web_service_access: zod_1.z.boolean().optional().default(true),
201
+ allow_new_fields: zod_1.z.boolean().optional().default(false),
202
+ allow_ui_actions: zod_1.z.boolean().optional().default(false),
203
+ allow_client_scripts: zod_1.z.boolean().optional().default(false),
204
+ // From sys_dictionary
205
+ audit: zod_1.z.boolean().optional().default(false),
206
+ read_only: zod_1.z.boolean().optional().default(false),
207
+ text_index: zod_1.z.boolean().optional().default(false),
208
+ attributes: zod_1.z
209
+ .record(zod_1.z.union([zod_1.z.string(), zod_1.z.number(), zod_1.z.boolean()]))
210
+ .default({})
211
+ .optional(),
212
+ });
213
+ const TableSchemaBootstrapIncoming = exports.TableSchemaBootstrap.omit({ actions: true }).extend({
214
+ caller_access: zod_1.z
215
+ .union([zod_1.z.literal(0), zod_1.z.literal(1), zod_1.z.literal(2)])
216
+ .transform((val) => {
217
+ if (val) {
218
+ return exports.callerAccess[val];
219
+ }
220
+ return;
221
+ })
222
+ .optional(),
223
+ accessible_from: zod_1.z.union([zod_1.z.literal('public'), zod_1.z.literal('package_private')]).optional(),
224
+ extends: zod_1.z
225
+ .string()
226
+ .or(zod_1.z.object({ name: zod_1.z.string() }).transform((obj) => obj.name))
227
+ .optional(),
228
+ live_feed: zod_1.z.boolean().optional().default(false),
229
+ index: zod_1.z.any().optional(),
230
+ columns: zod_1.z.any().optional(),
231
+ });
232
+ // Everything in side <database> in boostrap.xml
233
+ const BootstrapDatabaseElement = zod_1.z.object({
234
+ element: zod_1.z.record(zod_1.z.any()),
235
+ });
236
+ const DBObjectIncoming = zod_1.z.object({
237
+ '@_table': zod_1.z.literal('sys_db_object'),
238
+ sys_db_object: zod_1.z.record(zod_1.z.any()),
239
+ });
240
+ exports.Documentation = zod_1.z.object({
241
+ sys_documentation: zod_1.z.object({
242
+ element: RecordPlugin_1.TextStringSchema.optional(),
243
+ label: RecordPlugin_1.TextStringSchema.optional(),
244
+ language: RecordPlugin_1.TextStringSchema.optional(),
245
+ hint: RecordPlugin_1.TextStringSchema.optional(),
246
+ help: RecordPlugin_1.TextStringSchema.optional(),
247
+ name: RecordPlugin_1.TextStringSchema.optional(),
248
+ plural: RecordPlugin_1.TextStringSchema.optional(),
249
+ url: RecordPlugin_1.TextStringSchema.optional(),
250
+ url_target: RecordPlugin_1.TextStringSchema.optional(),
251
+ }),
252
+ });
253
+ // Attributes from element=table in bootstrap.xml
254
+ exports.TableSchemaBootstrapAttributes = zod_1.z
255
+ .object({
256
+ '@_name': zod_1.z.string(),
257
+ '@_extends': zod_1.z.string().optional(),
258
+ '@_label': zod_1.z.string().optional(),
259
+ '@_max_length': zod_1.z.coerce.number().optional(),
260
+ // From sys_dictionary
261
+ '@_audit': BooleanFromString,
262
+ '@_read_only': BooleanFromString,
263
+ '@_text_index': BooleanFromString,
264
+ '@_client_scripts_access': BooleanFromString,
265
+ '@_ws_access': BooleanFromString,
266
+ '@_alter_access': BooleanFromString,
267
+ '@_create_access': BooleanFromString,
268
+ '@_delete_access': BooleanFromString,
269
+ '@_update_access': BooleanFromString,
270
+ '@_query_access': BooleanFromString,
271
+ '@_actions_access': BooleanFromString,
272
+ '@_read_access': BooleanFromString,
273
+ '@_is_extendable': BooleanFromString,
274
+ '@_caller_access': IntFromString,
275
+ '@_attributes': zod_1.z
276
+ .string()
277
+ .transform((values) => {
278
+ const ret = {};
279
+ if (values === '') {
280
+ return undefined;
281
+ }
282
+ const entries = values.split(',');
283
+ entries.forEach((attr) => {
284
+ const s = attr.split('=');
285
+ if (s.length === 2 && s[0] && s[1]) {
286
+ try {
287
+ ret[s[0]] = JSON.parse(s[1]);
288
+ }
289
+ catch (err) {
290
+ ret[s[0]] = s[1];
291
+ }
292
+ }
293
+ });
294
+ return ret;
295
+ })
296
+ .optional(),
297
+ })
298
+ .catchall(zod_1.z.any());
299
+ const IndexSchemaBootstrapAttributes = zod_1.z.object({
300
+ '@_name': zod_1.z.string(),
301
+ '@_unique': BooleanFromString,
302
+ element: zod_1.z.object({
303
+ '@_name': zod_1.z.string(),
304
+ }),
305
+ });
306
+ exports.ColumnSchemaBootstrapAttributes = exports.TableSchemaBootstrapAttributes.omit({ '@_extends': true })
307
+ .extend({
308
+ '@_choice': zod_1.z.coerce.number().optional(),
309
+ '@_active': BooleanFromString,
310
+ '@_mandatory': BooleanFromString,
311
+ '@_display': BooleanFromString,
312
+ '@_type': zod_1.z.string().optional(),
313
+ '@_use_dependent_field': BooleanFromString,
314
+ '@_use_dynamic_default': BooleanFromString,
315
+ '@_reference': zod_1.z.string().optional(),
316
+ '@_virtual': BooleanFromString,
317
+ '@_default': zod_1.z.string().optional(),
318
+ '@_calculation': zod_1.z.string().optional(),
319
+ '@_choice_field': zod_1.z.string().optional(),
320
+ '@_function_definition': zod_1.z.string().optional(),
321
+ choice: zod_1.z.object({ element: zod_1.z.array(zod_1.z.any()).or(zod_1.z.record(zod_1.z.any())).optional() }).optional(),
322
+ })
323
+ .catchall(zod_1.z.any());
324
+ const ChoiceSchema = zod_1.z.object({
325
+ label: zod_1.z.string().optional(),
326
+ value: zod_1.z.string().optional(),
327
+ sequence: zod_1.z.coerce.number().optional(),
328
+ dependent_value: zod_1.z.coerce.number().optional(),
329
+ hint: zod_1.z.string().optional(),
330
+ inactive: BooleanFromString.default(false).optional(),
331
+ inactive_on_update: BooleanFromString.default(false).optional(),
332
+ language: zod_1.z.string().optional(),
333
+ });
334
+ const ChoiceSchemaIncoming = ChoiceSchema.omit({ value: true });
335
+ function isSNScope(scopeName) {
336
+ return scopeName.startsWith('sn') || scopeName.startsWith('now');
337
+ }
338
+ exports.default = (0, sdk_build_core_1.Plugin)({
339
+ name: 'Table',
340
+ ownedTables: {
341
+ sys_db_object: { diagnosticLevel: sdk_project_1.Diagnostic.Level.Warn },
342
+ },
343
+ extractors: {
344
+ entity: {
345
+ // TODO: Cast to `any` is temporary workaround for the circular nature of Table entities
346
+ CallExpression: (node, context) => {
347
+ const result = (0, sdk_build_core_1.extractCallExpression)(db_1.Table, 'table', node, context, (table) => table.name);
348
+ if (!result.handled || !(0 in result.data)) {
349
+ return result;
350
+ }
351
+ const data = result.data[0];
352
+ const diagnostics = result.diagnostics;
353
+ const scopeName = context.app.config.scope;
354
+ const scopeRegex = new RegExp(`^${scopeName}_`);
355
+ const nameRegex = new RegExp(`^[a-z_][a-z0-9_]`);
356
+ const tableName = data.getProperty('name');
357
+ const scopeMatches = tableName.getValue().match(scopeRegex);
358
+ if (!scopeMatches) {
359
+ const nameNode = tableName.getNode().asKindOrThrow(ts_morph_1.SyntaxKind.StringLiteral);
360
+ if (nameNode.getParent().getKindName() !== 'AsExpression') {
361
+ diagnostics.push(new sdk_build_core_1.FluentDiagnostic(tableName.getNode(), `'name' property must start with scope prefix '${scopeName}'`));
362
+ }
363
+ }
364
+ const schema = data.getProperty('schema');
365
+ const schemaNode = schema.getNode().asKindOrThrow(ts_morph_1.SyntaxKind.ObjectLiteralExpression);
366
+ for (const columnName in schema.getValue()) {
367
+ const columnNode = schemaNode.getPropertyOrThrow(columnName);
368
+ if (!scopeMatches && !isSNScope(scopeName) && !columnName.match(scopeRegex)) {
369
+ diagnostics.push(new sdk_build_core_1.FluentDiagnostic(columnNode, `Column name must be prefixed with scope '${scopeName}' if table name does not contain prefix`));
370
+ }
371
+ if (!columnName.match(nameRegex)) {
372
+ diagnostics.push(new sdk_build_core_1.FluentDiagnostic(columnNode, `Column name must only contain lowercase letters, numbers, and underscores`));
373
+ }
374
+ }
375
+ const declaration = node.getParentIfKind(ts_morph_1.SyntaxKind.VariableDeclaration);
376
+ if (!declaration ||
377
+ !declaration.isExported() ||
378
+ !declaration.isNamedExport() ||
379
+ declaration.getName() !== tableName.getValue()) {
380
+ diagnostics.push(new sdk_build_core_1.FluentDiagnostic(node, `Table definition should be exported as a named export with the name '${tableName.getValue()}'`, { level: sdk_project_1.Diagnostic.Level.Warn }));
381
+ }
382
+ return { handled: true, data: [data], diagnostics };
383
+ },
384
+ },
385
+ raw: {
386
+ FunctionDeclaration(node, context) {
387
+ const info = (0, scriptUtils_1.scriptInfo)(node, context, db_1.Table.name);
388
+ if (!info) {
389
+ return { handled: false };
390
+ }
391
+ return { handled: true, diagnostics: [], data: [info] };
392
+ },
393
+ FunctionExpression(node, context) {
394
+ const info = (0, scriptUtils_1.scriptInfo)(node, context, db_1.Table.name);
395
+ if (!info) {
396
+ return { handled: false };
397
+ }
398
+ return { handled: true, diagnostics: [], data: [info] };
399
+ },
400
+ },
401
+ xml(xml, context) {
402
+ const bootstrapData = {};
403
+ let dbObjectData = {};
404
+ const bootstrapDatabaseXML = BootstrapDatabaseElement.safeParse(xml.data['database']);
405
+ if (bootstrapDatabaseXML.success) {
406
+ const data = exports.TableSchemaBootstrapAttributes.parse(bootstrapDatabaseXML.data.element);
407
+ Object.entries(data).forEach(([key, value]) => {
408
+ if (key.startsWith('@_')) {
409
+ bootstrapData[key.substring(2)] = value;
410
+ }
411
+ else if (key === 'element') {
412
+ //
413
+ }
414
+ else {
415
+ bootstrapData[key] = value;
416
+ }
417
+ });
418
+ context.handledXmls[xml.filePath] = 'handled';
419
+ }
420
+ const db_object_inc = DBObjectIncoming.safeParse(xml.data['record_update']);
421
+ if (db_object_inc.success) {
422
+ dbObjectData = DBObjectIncomingAttributes.parse(db_object_inc.data.sys_db_object);
423
+ context.handledXmls[xml.filePath] = 'handled';
424
+ return new sdk_build_core_1.XmlData(dbObjectData, xml.filePath, 'sys_db_object', db_object_inc.data.sys_db_object['@_action']);
425
+ }
426
+ else {
427
+ const record_update = xml.data['record_update'];
428
+ if (record_update) {
429
+ const table = Object.keys(record_update)[0];
430
+ if (!table || !componentTables.includes(table)) {
431
+ return;
432
+ }
433
+ if (table === 'sys_documentation') {
434
+ const data = exports.Documentation.parse(record_update[table]);
435
+ return new sdk_build_core_1.XmlData({
436
+ table: table,
437
+ id: record_update[table][table]['sys_id']['#text'],
438
+ data: data.sys_documentation,
439
+ }, xml.filePath, 'record', record_update[table][table]['@_action']);
440
+ }
441
+ context.handledXmls[xml.filePath] = 'ignored';
442
+ return;
443
+ }
444
+ }
445
+ // Columns and Indexes
446
+ const columns = [];
447
+ const idxElements = [];
448
+ if (bootstrapDatabaseXML.success && bootstrapDatabaseXML.data.element['element']) {
449
+ const element = bootstrapDatabaseXML.data.element['element'];
450
+ const elementsArray = (0, lodash_1.isArray)(element) ? element : [element];
451
+ columns.push(...zod_1.z.array(exports.ColumnSchemaBootstrapAttributes).parse(elementsArray));
452
+ columns.forEach((element) => {
453
+ if (element.choice && !(0, lodash_1.isEmpty)(element.choice)) {
454
+ element['choice_elements'] = {};
455
+ const choices = (0, lodash_1.isArray)(element.choice.element)
456
+ ? element.choice.element
457
+ : [element.choice.element];
458
+ choices.forEach((choice) => {
459
+ const obj = removeAttributeTag(choice);
460
+ const choiceData = ChoiceSchemaIncoming.parse(obj);
461
+ if (!choiceData.label) {
462
+ choiceData.label = obj.value;
463
+ }
464
+ element['choice_elements'][obj.value] = choiceData;
465
+ });
466
+ }
467
+ element = removeAttributeTag(element);
468
+ });
469
+ bootstrapData['columns'] = columns.reduce((map, obj) => ((map[obj['name']] = obj), map), {});
470
+ let elements = bootstrapDatabaseXML.data.element['index'];
471
+ elements = (0, lodash_1.isArray)(elements) ? elements : [elements];
472
+ elements.forEach((element) => {
473
+ const idxData = IndexSchemaBootstrapAttributes.safeParse(element);
474
+ if (idxData.success) {
475
+ idxElements.push({
476
+ name: idxData.data['@_name'],
477
+ element: idxData.data.element['@_name'],
478
+ unique: idxData.data['@_unique'] ?? false,
479
+ });
480
+ }
481
+ });
482
+ bootstrapData['index'] = idxElements;
483
+ }
484
+ return new sdk_build_core_1.XmlData(bootstrapData, xml.filePath, 'bootstrap');
485
+ },
486
+ },
487
+ composers: {
488
+ entity: {
489
+ table(entity, context) {
490
+ const node = entity.getNode();
491
+ const data = entity.getValue();
492
+ const table = exports.TableSchemaFull.parse(data);
493
+ const composeData = compose(table);
494
+ composeData['columns'] = composeColumns(table.schema, context, table.display);
495
+ const entities = [];
496
+ if (table.auto_number) {
497
+ const data = table.auto_number;
498
+ const numberRecord = SysNumber(table.name, data.number_of_digits, data.number, data.prefix);
499
+ const composedNumber = RecordPlugin_1.RecordPlugin.composers.entity.record(new sdk_build_core_1.EntityData('record', context.registerExplicitId(numberRecord.table, numberRecord.$id), sdk_build_core_1.ObjectData.fromObjectValue(numberRecord, node), node), context);
500
+ entities.push(composedNumber);
501
+ composeData['number_ref'] = composedNumber.guid;
502
+ }
503
+ composeData['index'] = table.index;
504
+ entities.push({
505
+ kind: 'bootstrap',
506
+ node,
507
+ guid: composeData.name,
508
+ data: { data: { bootstrapData: composeData, dbObjectData: composeData } },
509
+ });
510
+ return entities;
511
+ },
512
+ },
513
+ xml: {
514
+ bootstrap(xml) {
515
+ return {
516
+ kind: xml.kind,
517
+ guid: xml.data['name'],
518
+ data: { data: { bootstrapData: xml.data } },
519
+ };
520
+ },
521
+ sys_db_object(xml) {
522
+ return {
523
+ kind: 'bootstrap',
524
+ guid: xml.data['name'],
525
+ data: { data: { dbObjectData: xml.data } },
526
+ action: xml.action,
527
+ };
528
+ },
529
+ },
530
+ },
531
+ generators: {
532
+ bootstrap(document, context) {
533
+ const parsedBoostrapData = TableSchemaBootstrapIncoming.safeParse(document.data.data.bootstrapData);
534
+ if (!parsedBoostrapData.success) {
535
+ return undefined;
536
+ }
537
+ return (0, sdk_build_core_1.linkDocument)(document, generateCallExpressionExportForDocument(context, {
538
+ sourceFile: (0, sdk_build_core_1.getOrCreateEntitySourceFile)(context, parsedBoostrapData.data.name),
539
+ moduleSpecifier: '@servicenow/sdk/core',
540
+ exportName: parsedBoostrapData.data.name,
541
+ }, db_1.Table, {}).getInitializerIfKindOrThrow(ts_morph_1.SyntaxKind.CallExpression));
542
+ },
543
+ record(document, context) {
544
+ if (document.data?.['table'] !== 'sys_documentation' &&
545
+ document.data?.['table'] !== 'ua_table_licensing_config') {
546
+ return;
547
+ }
548
+ return (0, sdk_build_core_1.linkDocument)(document, (0, sdk_build_core_1.generateCallExpression)(context, (0, sdk_build_core_1.getOrCreateEntitySourceFile)(context, `${document.data?.['data'].name}`), '@servicenow/sdk/core', db_1.Record, { $id: document.guid }));
549
+ },
550
+ },
551
+ serializers: {
552
+ bootstrap(document) {
553
+ const composedData = document.data.data;
554
+ const { columns, index, attributes, ...bootstrapData } = composedData.bootstrapData;
555
+ if (bootstrapData.live_feed) {
556
+ // live_feed needs to be a table sys_dictionary attribute so it can be synced to sys_db_object by a startup process
557
+ attributes['live_feed'] = true;
558
+ }
559
+ const builder = new sdk_build_core_1.XMLJsonBuilder('1.0');
560
+ const databaseObj = builder.createRoot('database', undefined, undefined);
561
+ const composedAttributes = composeAttributes(attributes);
562
+ const collectionObj = databaseObj.addJsonObj('element', undefined, { ...bootstrapData, attributes: composedAttributes });
563
+ for (const column of Object.values(columns)) {
564
+ const { choice_elements, attributes, ...parsedColumn } = column;
565
+ const columnAttributes = composeAttributes(attributes);
566
+ const elementObj = collectionObj.addJsonObj('element', undefined, {
567
+ ...parsedColumn,
568
+ attributes: columnAttributes,
569
+ });
570
+ buildChoices(column, elementObj);
571
+ }
572
+ buildIndexes(index, collectionObj);
573
+ const bootstrapXmlJson = new fast_xml_parser_1.XMLBuilder({
574
+ ignoreAttributes: false,
575
+ format: true,
576
+ suppressBooleanAttributes: false,
577
+ suppressEmptyNode: true,
578
+ }).build(builder.buildJsonObj());
579
+ return {
580
+ name: `${bootstrapData.name}.xml`,
581
+ directory: 'dictionary',
582
+ content: bootstrapXmlJson,
583
+ usedIds: [],
584
+ };
585
+ },
586
+ },
587
+ transformers: {
588
+ bootstrap: {
589
+ CallExpression(document) {
590
+ const expressionName = (0, sdk_build_core_1.getCallExpressionName)(document.node);
591
+ if (expressionName !== db_1.Table.name) {
592
+ return false;
593
+ }
594
+ const [args] = document.node.getArguments();
595
+ if (!ts_morph_1.Node.isObjectLiteralExpression(args)) {
596
+ return false;
597
+ }
598
+ if (document.action === 'DELETE') {
599
+ (0, sdk_build_core_1.removeNode)(document.node);
600
+ return true;
601
+ }
602
+ if (!document.changedData) {
603
+ return true;
604
+ }
605
+ const composedData = document.changedData.data;
606
+ const xmlData = document.xmlData.data;
607
+ let bootstrap_data = {};
608
+ let db_data = {};
609
+ if (!(0, lodash_1.isEmpty)(composedData.bootstrapData)) {
610
+ // sys_db_object or node without bootstrap.xml. Mark as handled and ignore
611
+ bootstrap_data = TableSchemaBootstrapIncoming.partial().parse(composedData.bootstrapData);
612
+ }
613
+ if (!(0, lodash_1.isEmpty)(composedData.dbObjectData)) {
614
+ db_data = DBObjectIncomingAttributes.partial().parse(composedData.dbObjectData);
615
+ }
616
+ const { auto_number, number_ref, extends: ext, index, columns, ...bootstrap_rest } = mapNames(bootstrap_data);
617
+ const { create_access, delete_access, update_access, read_access, caller_access, ...db_rest } = mapNames(db_data);
618
+ const rest = { ...bootstrap_rest, ...db_rest };
619
+ if (ext) {
620
+ rest['extends'] = ext;
621
+ }
622
+ if (caller_access) {
623
+ rest['caller_access'] = exports.callerAccess[caller_access];
624
+ }
625
+ if (!(0, lodash_1.isEmpty)(db_data)) {
626
+ const actions = getActionsArray({ create_access, delete_access, update_access, read_access });
627
+ if (actions.length > 0) {
628
+ (0, sdk_build_core_1.writeCustomProperty)(args, 'actions', '[]', (0, sdk_build_core_1.stringify)(actions));
629
+ }
630
+ else {
631
+ const actionsProp = (0, sdk_build_core_1.getOrCreatePropertyAssignment)(args, 'actions', '[]');
632
+ actionsProp.remove();
633
+ }
634
+ }
635
+ if (!rest.attributes) {
636
+ delete rest.attributes;
637
+ }
638
+ if (xmlData.bootstrapData && xmlData.bootstrapData.index) {
639
+ const indexProp = (0, sdk_build_core_1.getOrCreatePropertyAssignment)(args, 'index', '[]');
640
+ indexProp.setInitializer((0, sdk_build_core_1.stringify)(xmlData.bootstrapData.index));
641
+ if (xmlData.bootstrapData.index.length === 0) {
642
+ indexProp.remove();
643
+ }
644
+ }
645
+ (0, sdk_build_core_1.transformFunctionArguments)(document.node, db_1.Table, rest);
646
+ // Handle columns
647
+ const incomingColumns = xmlData.bootstrapData ? xmlData.bootstrapData.columns : undefined;
648
+ updateDisplayValue(document.node, columns, incomingColumns);
649
+ transformColumns(incomingColumns, args);
650
+ return true;
651
+ },
652
+ },
653
+ },
654
+ postProcessors: {
655
+ entities(entities, context) {
656
+ entities
657
+ .filter((entity) => entity.getKind() === 'table')
658
+ .forEach((table) => {
659
+ const tableName = table.getProperty('name').getValue();
660
+ const originalSourceFilePath = path.normalize(table.getNode().getSourceFile().getFilePath());
661
+ context.compiler.addTableInterfaceToGlobalDeclaration(originalSourceFilePath, tableName);
662
+ });
663
+ },
664
+ },
665
+ });
666
+ function generateCallExpressionExportForDocument(context, info, fn, ...args) {
667
+ const { sourceFile, moduleSpecifier } = info;
668
+ return (0, sdk_build_core_1.generateCallExpressionExport)(context, sourceFile, moduleSpecifier, info.exportName, fn, ...args);
669
+ }
670
+ function composeAttributes(attributes) {
671
+ if (!attributes) {
672
+ return '';
673
+ }
674
+ return Object.entries(attributes)
675
+ .map(([key, value]) => `${key}=${value}`)
676
+ .join(',');
677
+ }
678
+ function updateDisplayValue(node, columns, incomingColumns) {
679
+ const display = Object.values(columns ?? {}).filter((col) => col.display);
680
+ if (display) {
681
+ const displayName = Object.values(incomingColumns ?? {}).find((c) => c.display);
682
+ if (displayName) {
683
+ (0, sdk_build_core_1.transformFunctionArguments)(node, db_1.Table, { display: displayName.name });
684
+ }
685
+ }
686
+ }
687
+ function composeColumns(columns, context, display) {
688
+ const composedColumns = {};
689
+ for (const [columnName, columnData] of Object.entries(columns)) {
690
+ const column = exports.ColumnSchema.parse(columnData);
691
+ const requiresDropdown = column.dynamic_value_definitions || column.choices;
692
+ const element = {
693
+ name: columnName,
694
+ type: column.entityKind === 'generic' ? column.column_type : column.entityKind,
695
+ attributes: column.attributes ?? undefined,
696
+ reference: column.referenceTable,
697
+ audit: column.audit,
698
+ label: column.label ?? columnName,
699
+ max_length: column.maxLength,
700
+ mandatory: column.mandatory,
701
+ read_only: column.read_only,
702
+ choice: db_1.choiceDropdown.indexOf(column.dropdown ?? requiresDropdown ? 'dropdown_with_none' : 'none'),
703
+ display: display ? display === columnName : false,
704
+ // dynamic values
705
+ virtual: column.dynamic_value_definitions?.type === 'calculated_value' ? true : undefined,
706
+ calculation: column.dynamic_value_definitions?.type === 'calculated_value'
707
+ ? getScriptInfo(column.dynamic_value_definitions['calculated_value'], context)
708
+ : undefined,
709
+ choice_table: column.dynamic_value_definitions?.type === 'choices_from_other_table'
710
+ ? column.dynamic_value_definitions.table
711
+ : undefined,
712
+ choice_field: column.dynamic_value_definitions?.type === 'choices_from_other_table'
713
+ ? column.dynamic_value_definitions.field
714
+ : undefined,
715
+ use_dependent_field: column.dynamic_value_definitions?.type === 'dependent_field' || undefined,
716
+ dependent: column.dynamic_value_definitions?.type === 'dependent_field'
717
+ ? column.dynamic_value_definitions['column_name']
718
+ : undefined,
719
+ use_dynamic_default: column.dynamic_value_definitions?.type === 'dynamic_default' || undefined,
720
+ default_value: column.dynamic_value_definitions?.type === 'dynamic_default'
721
+ ? getDynamicDefault(column.dynamic_value_definitions?.dynamic_default)
722
+ : undefined,
723
+ default: column.default,
724
+ function_definition: column.function_definition,
725
+ function_field: column.function_definition ? true : false,
726
+ };
727
+ if (column.choices) {
728
+ Object.keys(column.choices).forEach((key) => {
729
+ if ((0, lodash_1.isObject)(column.choices[key])) {
730
+ column.choices[key] = { value: key, ...column.choices[key] };
731
+ }
732
+ else {
733
+ column.choices[key] = { value: key, label: column.choices[key] };
734
+ }
735
+ });
736
+ element['choice_elements'] = zod_1.z.record(ChoiceSchema).parse(column.choices);
737
+ }
738
+ composedColumns[columnName] = element;
739
+ }
740
+ return composedColumns;
741
+ }
742
+ function compose(bootstrapData) {
743
+ if (bootstrapData.live_feed) {
744
+ bootstrapData.attributes = {
745
+ // live_feed needs to be a table sys_dictionary attribute so it can be synced to sys_db_object by a startup process
746
+ ...bootstrapData.attributes,
747
+ live_feed: true,
748
+ };
749
+ }
750
+ const composedData = {
751
+ // Generic data
752
+ name: bootstrapData.name,
753
+ type: 'collection',
754
+ extends: bootstrapData.extends,
755
+ label: bootstrapData.label ?? bootstrapData.name,
756
+ // Controls
757
+ is_extendable: bootstrapData.extensible,
758
+ text_index: bootstrapData.text_index,
759
+ read_only: bootstrapData.read_only,
760
+ audit: bootstrapData.audit,
761
+ access: bootstrapData.accessible_from,
762
+ caller_access: exports.callerAccess.indexOf(bootstrapData.caller_access ?? 'none'),
763
+ read_access: bootstrapData.actions?.includes('read'),
764
+ update_access: bootstrapData.actions?.includes('update'),
765
+ create_access: bootstrapData.actions?.includes('create'),
766
+ delete_access: bootstrapData.actions?.includes('delete'),
767
+ ws_access: bootstrapData.allow_web_service_access,
768
+ alter_access: bootstrapData.allow_new_fields,
769
+ actions_access: bootstrapData.allow_ui_actions,
770
+ client_scripts_access: bootstrapData.allow_client_scripts,
771
+ attributes: bootstrapData.attributes,
772
+ };
773
+ return composedData;
774
+ }
775
+ // API properties that are different in the bootstrap/sys_db_object file
776
+ const property_name_mapping = {
777
+ client_scripts_access: 'allow_client_scripts',
778
+ alter_access: 'allow_new_fields',
779
+ actions_access: 'allow_ui_actions',
780
+ ws_access: 'allow_web_service_access',
781
+ is_extendable: 'extensible',
782
+ access: 'accessible_from',
783
+ live_feed_enabled: 'live_feed',
784
+ };
785
+ function mapNames(schema) {
786
+ Object.keys(schema).forEach((key) => {
787
+ if (property_name_mapping[key]) {
788
+ schema[property_name_mapping[key]] = schema[key];
789
+ delete schema[key];
790
+ }
791
+ });
792
+ return schema;
793
+ }
794
+ let schemaPosition = 4;
795
+ function transformColumns(incoming_schema, args) {
796
+ const schemaProperty = (0, sdk_build_core_1.getOrCreatePropertyAssignment)(args, 'schema', '{}');
797
+ const schemaLiteral = schemaProperty.getChildrenOfKind(ts_morph_1.ts.SyntaxKind.ObjectLiteralExpression)[0];
798
+ if (!schemaLiteral) {
799
+ return;
800
+ }
801
+ const keys = Object.keys(incoming_schema ?? {});
802
+ if (keys.length === 0) {
803
+ return;
804
+ }
805
+ //TODO:: need to come up with a way to format script more accurately
806
+ schemaPosition = schemaLiteral.getSourceFile().getLineAndColumnAtPos(schemaLiteral.getStart()).column;
807
+ const assignments = [];
808
+ keys.forEach((key) => {
809
+ const data = incoming_schema[key];
810
+ const callExpFromType = getCallExpressionFromType(data.type);
811
+ const transformedColumn = transformColumnData(data, callExpFromType);
812
+ const callExp = generateColumnExpression(callExpFromType, {
813
+ ...transformedColumn,
814
+ choices: data.choice_elements,
815
+ });
816
+ assignments.push(ts_morph_1.ts.factory.createPropertyAssignment((0, sdk_build_core_1.createPropertyIdentifier)(data.name), callExp));
817
+ });
818
+ schemaLiteral.transform((traversal) => {
819
+ if (ts_morph_1.ts.isObjectLiteralExpression(traversal.currentNode)) {
820
+ return traversal.factory.updateObjectLiteralExpression(traversal.currentNode, assignments);
821
+ }
822
+ return traversal.currentNode;
823
+ });
824
+ }
825
+ function getActionsArray(data) {
826
+ const actions = [];
827
+ if (data.read_access) {
828
+ actions.push('read');
829
+ }
830
+ if (data.update_access) {
831
+ actions.push('update');
832
+ }
833
+ if (data.delete_access) {
834
+ actions.push('delete');
835
+ }
836
+ if (data.create_access) {
837
+ actions.push('create');
838
+ }
839
+ return actions;
840
+ }
841
+ function getDynamicDefault(val) {
842
+ return val.startsWith('javascript:') ? val : `javascript:${exports.dynamic_value_mapping[val]}`;
843
+ }
844
+ function buildIndexes(indexes = [], collection) {
845
+ indexes.forEach((index) => {
846
+ const indexElement = collection.addJsonObj('index', undefined, { name: index.name, unique: index.unique });
847
+ indexElement.addJsonObj('element', undefined, { name: index.element });
848
+ });
849
+ }
850
+ function buildChoices(column, element) {
851
+ if (!column.choice_elements) {
852
+ return;
853
+ }
854
+ const choices = element.addJsonObj('choice', undefined, undefined);
855
+ if (Array.isArray(column.choices) && column.choices.length > 0) {
856
+ // Formatted - choices: [1, 2, 3, 4]
857
+ for (const choice in column.choices) {
858
+ choices.addJsonObj('element', undefined, {
859
+ value: column.choices[choice],
860
+ label: column.choices[choice],
861
+ });
862
+ }
863
+ }
864
+ else {
865
+ // Formatted - choices: { 1: { label: 'label' }, 2: { lable: label 2}, ...}
866
+ Object.entries(column.choice_elements).forEach((value) => {
867
+ if ((0, lodash_1.isObject)(value[1])) {
868
+ choices.addJsonObj('element', undefined, {
869
+ value: value[0],
870
+ ...value[1],
871
+ });
872
+ }
873
+ else {
874
+ choices.addJsonObj('element', undefined, {
875
+ value: value[1],
876
+ label: value[0],
877
+ });
878
+ }
879
+ });
880
+ }
881
+ }
882
+ function transformColumnData(col, callExpFromType) {
883
+ const { type: internal_type, choice, name, virtual, display, choice_table, choice_field, use_dependent_field, dependent, calculation, use_dynamic_default, default_value, choice_elements, table, default: def, max_length, reference, function_field, ...column } = col;
884
+ if (max_length) {
885
+ column.maxLength = max_length;
886
+ }
887
+ if (internal_type && (callExpFromType.entityKind === 'generic' || callExpFromType.name === 'GenericColumn')) {
888
+ column.column_type = internal_type;
889
+ }
890
+ if (choice !== undefined) {
891
+ column.dropdown = db_1.choiceDropdown[choice];
892
+ }
893
+ if (reference) {
894
+ column.referenceTable = reference;
895
+ }
896
+ // Handle dynamic values
897
+ if (calculation) {
898
+ column.dynamic_value_definitions = {
899
+ type: 'calculated_value',
900
+ calculated_value: calculation,
901
+ };
902
+ }
903
+ else if (choice_table || choice_field) {
904
+ column.dynamic_value_definitions = {
905
+ type: 'choices_from_other_table',
906
+ table: choice_table,
907
+ field: choice_field,
908
+ };
909
+ }
910
+ else if (dependent) {
911
+ column.dynamic_value_definitions = {
912
+ type: 'dependent_field',
913
+ column_name: dependent,
914
+ };
915
+ }
916
+ else if (def) {
917
+ column.default = def;
918
+ }
919
+ else if (default_value) {
920
+ column.dynamic_value_definitions = {
921
+ type: 'dynamic_default',
922
+ dynamic_default: def,
923
+ };
924
+ }
925
+ if (column.label && column.label === name) {
926
+ delete column.label;
927
+ }
928
+ if ((0, lodash_1.isEmpty)(column.attributes)) {
929
+ delete column.attributes;
930
+ }
931
+ else if (isDefaultEdgeEncryptionAttribute(column.attributes)) {
932
+ delete column.attributes;
933
+ }
934
+ return column;
935
+ }
936
+ // The instance will sometimes add edge_encryption_enabled=true, this is a default so don't write it if it is the only one
937
+ function isDefaultEdgeEncryptionAttribute(attributes) {
938
+ return (attributes &&
939
+ Object.entries(attributes).length === 1 &&
940
+ attributes.edge_encryption_enabled !== undefined &&
941
+ attributes.edge_encryption_enabled);
942
+ }
943
+ function getScriptInfo(scriptInfo, context) {
944
+ if ((0, lodash_1.isString)(scriptInfo)) {
945
+ return scriptInfo;
946
+ }
947
+ const { filePath, functionName, isDefault } = scriptInfo;
948
+ const script = (0, scriptUtils_1.buildScriptImport)(filePath, functionName, isDefault, context, (funcName) => `;${funcName}(current)`);
949
+ return script.replaceAll('\n', '');
950
+ }
951
+ function removeAttributeTag(obj) {
952
+ Object.entries(obj).forEach(([key, value]) => {
953
+ if (key.startsWith('@_')) {
954
+ obj[key.substring(2)] = value;
955
+ delete obj[key];
956
+ }
957
+ });
958
+ return obj;
959
+ }
960
+ function SysNumber(category, maximum_digits, number, prefix) {
961
+ return (0, db_1.Record)({
962
+ table: 'sys_number',
963
+ $id: `${category}_${prefix}`,
964
+ data: {
965
+ category,
966
+ maximum_digits: maximum_digits ?? 1000,
967
+ number: number ?? 7,
968
+ prefix: prefix ?? 'PRE',
969
+ },
970
+ });
971
+ }
972
+ // TODO should this reference sys_filter_option_dynamic instead?
973
+ exports.dynamic_value_mapping = {
974
+ 'Current Name': `current.name`,
975
+ 'Next ECC Sequence Number': `GlideCounter.next('ecc:sequence');`,
976
+ 'Get Module View': `var viewDefault='';if(current.device_type=='mobile') viewDefault='Mobile';else if(!current.application.nil() && current.application.device_type=='mobile' && current.device_type.nil()) viewDefault='Mobile';viewDefault`,
977
+ 'Get Label Display Value': `gs.getDisplayValueFor(current.table, current.table_key, '')`,
978
+ 'Get CMDB Item Category': `gs.include("CMDBItem");var item = new CMDBItem(current);item.setCategory();`,
979
+ 'Parent Record Matcher Table': `if (typeof parent != "undefined") parent.matcher_table`,
980
+ 'Next Cache Flush Number': `GlideCounter.next('sys_cache_flush');`,
981
+ 'Get Next Number': `global.getNextObjNumber()`,
982
+ 'Next Workflow Log Order Number': `GlideCounter.next('wf_log:order');`,
983
+ Subject: 'email.subject',
984
+ 'Get Mobile Module View': `var viewDefault='';if(typeof parent != 'undefined')if(parent.device_type=='mobile') viewDefault='Mobile';viewDefault`,
985
+ 'Parent Record Model Table': `if (typeof parent != "undefined") parent.model_table`,
986
+ 'Get Label Table Display Value': `gs.getDisplayValueFor(current.table, current.table_key, 'sys_class_name')`,
987
+ 'Parent Record Source Table': `if (typeof parent != "undefined") parent.source_table`,
988
+ 'Get Next Padded Number': `global.getNextObjNumberPadded();`,
989
+ 'My First Name': `gs.getUser().firstName`,
990
+ 'My Last Name': `gs.getUser().lastName`,
991
+ 'My Job Title': `gs.getUser().title`,
992
+ };
993
+ function generateColumnExpression(expression, args, argsSetIfDefined) {
994
+ const setArgs = { ...args };
995
+ if (argsSetIfDefined) {
996
+ Object.keys(argsSetIfDefined).forEach((key) => {
997
+ if (argsSetIfDefined[key] !== undefined) {
998
+ setArgs[key] = argsSetIfDefined[key];
999
+ }
1000
+ });
1001
+ }
1002
+ return ts_morph_1.ts.factory.createCallExpression(ts_morph_1.ts.factory.createIdentifier(expression.name), undefined, [
1003
+ createObjectExpression(setArgs),
1004
+ ]);
1005
+ }
1006
+ function createObjectExpression(firstArg) {
1007
+ return ts_morph_1.ts.factory.createObjectLiteralExpression(Object.entries(firstArg)
1008
+ .filter(([_key, value]) => value !== undefined)
1009
+ .map(([key, value]) => {
1010
+ if (key === 'referenceTable') {
1011
+ return ts_morph_1.ts.factory.createPropertyAssignment(ts_morph_1.ts.factory.createIdentifier('referenceTable'), ts_morph_1.ts.factory.createStringLiteral(value));
1012
+ }
1013
+ else if (key === 'calculated_value') {
1014
+ const calVal = `${os.EOL}${(0, ScriptTemplatePlugin_1.formatScript)(value, schemaPosition)}`;
1015
+ return ts_morph_1.ts.factory.createPropertyAssignment(ts_morph_1.ts.factory.createIdentifier(key), ts_morph_1.ts.factory.createTaggedTemplateExpression(ts_morph_1.ts.factory.createIdentifier('script'), undefined, ts_morph_1.ts.factory.createNoSubstitutionTemplateLiteral(calVal, calVal)));
1016
+ }
1017
+ return ts_morph_1.ts.factory.createPropertyAssignment((0, sdk_build_core_1.createPropertyIdentifier)(key), factoryCreateValue(value, ts_morph_1.ts.factory));
1018
+ }));
1019
+ }
1020
+ function factoryCreateValue(value, factory) {
1021
+ if (typeof value === 'string') {
1022
+ return factory.createStringLiteral(value);
1023
+ }
1024
+ if (typeof value === 'number') {
1025
+ if (value >= 0) {
1026
+ return factory.createNumericLiteral(value);
1027
+ }
1028
+ else {
1029
+ return factory.createPrefixUnaryExpression(ts_morph_1.ts.SyntaxKind.MinusToken, factory.createNumericLiteral(Math.abs(value)));
1030
+ }
1031
+ }
1032
+ if (typeof value === 'boolean') {
1033
+ return value ? factory.createTrue() : factory.createFalse();
1034
+ }
1035
+ if (typeof value === 'object') {
1036
+ if (value === null) {
1037
+ return factory.createNull();
1038
+ }
1039
+ if ((0, lodash_1.isArray)(value)) {
1040
+ const newvals = [];
1041
+ Object.values(value).forEach((v) => {
1042
+ newvals.push(factoryCreateValue(v, factory));
1043
+ });
1044
+ return factory.createArrayLiteralExpression(newvals);
1045
+ }
1046
+ else if (ts_morph_1.Structure.isImportSpecifier(value)) {
1047
+ return factory.createIdentifier(value['name']);
1048
+ }
1049
+ else {
1050
+ return createObjectExpression(value);
1051
+ }
1052
+ }
1053
+ return factory.createNull();
1054
+ // throw new Error(`Unsupported value type: ${typeof value}`)
1055
+ }
1056
+ function getCallExpressionFromType(internal_type) {
1057
+ switch (internal_type) {
1058
+ case 'boolean':
1059
+ return db_1.BooleanColumn;
1060
+ case 'choice':
1061
+ return db_1.ChoiceColumn;
1062
+ case 'conditions':
1063
+ return db_1.ConditionsColumn;
1064
+ case 'date':
1065
+ return db_1.OtherDateColumn;
1066
+ case 'calendar_date_time':
1067
+ return db_1.CalendarDateTimeColumn;
1068
+ case 'datetime':
1069
+ return db_1.BasicDateTimeColumn;
1070
+ case 'due_date':
1071
+ return db_1.DueDateColumn;
1072
+ case 'glide_date':
1073
+ return db_1.DateColumn;
1074
+ case 'glide_date_time':
1075
+ return db_1.DateTimeColumn;
1076
+ case 'integer_date':
1077
+ return db_1.IntegerDateColumn;
1078
+ case 'schedule_date_time':
1079
+ return db_1.ScheduleDateTimeColumn;
1080
+ case 'decimal':
1081
+ return db_1.DecimalColumn;
1082
+ case 'document_id':
1083
+ return db_1.DocumentIdColumn;
1084
+ case 'domain_id':
1085
+ return db_1.DomainIdColumn;
1086
+ case 'domain_path':
1087
+ return db_1.DomainPathColumn;
1088
+ case 'field_name':
1089
+ return db_1.FieldNameColumn;
1090
+ case 'integer':
1091
+ return db_1.IntegerColumn;
1092
+ case 'radio':
1093
+ return db_1.RadioColumn;
1094
+ case 'reference':
1095
+ return db_1.ReferenceColumn;
1096
+ case 'script':
1097
+ return db_1.ScriptColumn;
1098
+ case 'sys_class_name':
1099
+ return db_1.SystemClassNameColumn;
1100
+ case 'table_name':
1101
+ return db_1.TableNameColumn;
1102
+ case 'translated_field':
1103
+ return db_1.TranslatedFieldColumn;
1104
+ case 'translated_text':
1105
+ return db_1.TranslatedTextColumn;
1106
+ case 'user_roles':
1107
+ return db_1.UserRolesColumn;
1108
+ case 'version':
1109
+ return db_1.VersionColumn;
1110
+ case 'string':
1111
+ return db_1.StringColumn;
1112
+ case 'int':
1113
+ case 'string_types':
1114
+ case 'approval_rules':
1115
+ case 'audio':
1116
+ case 'auto_increment':
1117
+ case 'auto_number':
1118
+ case 'bootstrap_color':
1119
+ case 'breakdown_element':
1120
+ case 'catalog_preview':
1121
+ case 'char':
1122
+ case 'collection':
1123
+ case 'color':
1124
+ case 'color_display':
1125
+ case 'composite_field':
1126
+ case 'composite_name':
1127
+ case 'compressed':
1128
+ case 'condition_string':
1129
+ case 'counter':
1130
+ case 'css':
1131
+ case 'currency':
1132
+ case 'currency2':
1133
+ case 'data_array':
1134
+ case 'data_object':
1135
+ case 'data_structure':
1136
+ case 'days_of_week':
1137
+ case 'day_of_week':
1138
+ case 'documentation_field':
1139
+ case 'dynamic_json':
1140
+ case 'email':
1141
+ case 'email_script':
1142
+ case 'expression':
1143
+ case 'external_names':
1144
+ case 'field_list':
1145
+ case 'file_attachment':
1146
+ case 'float':
1147
+ case 'formula':
1148
+ case 'geo_point':
1149
+ case 'glide_action_list':
1150
+ case 'glide_duration':
1151
+ case 'glide_list':
1152
+ case 'glide_precise_time':
1153
+ case 'glide_time':
1154
+ case 'glide_utc_time':
1155
+ case 'glide_var':
1156
+ case 'glyphicon':
1157
+ case 'graphql_schema':
1158
+ case 'GUID':
1159
+ case 'html':
1160
+ case 'html_script':
1161
+ case 'html_template':
1162
+ case 'icon':
1163
+ case 'image':
1164
+ case 'index_name':
1165
+ case 'insert_timestamp':
1166
+ case 'integer_time':
1167
+ case 'internal_type':
1168
+ case 'ip_addr':
1169
+ case 'ip_address':
1170
+ case 'journal':
1171
+ case 'journal_input':
1172
+ case 'journal_list':
1173
+ case 'json':
1174
+ case 'json_translations':
1175
+ case 'language':
1176
+ case 'long':
1177
+ case 'longint':
1178
+ case 'mask_code':
1179
+ case 'metric_absolute':
1180
+ case 'metric_counter':
1181
+ case 'metric_derive':
1182
+ case 'metric_gauge':
1183
+ case 'mid_config':
1184
+ case 'month_of_year':
1185
+ case 'multi_small':
1186
+ case 'multi_two_lines':
1187
+ case 'name_values':
1188
+ case 'nds_icon':
1189
+ case 'nl_task_int1':
1190
+ case 'order_index':
1191
+ case 'password':
1192
+ case 'password2':
1193
+ case 'percent_complete':
1194
+ case 'phone_number':
1195
+ case 'phone_number_e164':
1196
+ case 'ph_number':
1197
+ case 'price':
1198
+ case 'properties':
1199
+ case 'records':
1200
+ case 'reference_name':
1201
+ case 'related_tags':
1202
+ case 'reminder_field_name':
1203
+ case 'repeat_count':
1204
+ case 'repeat_type':
1205
+ case 'replication_payload':
1206
+ case 'schedule_interval_count':
1207
+ case 'script_client':
1208
+ case 'script_plain':
1209
+ case 'script_server':
1210
+ case 'short_field_name':
1211
+ case 'short_table_name':
1212
+ case 'simple_name_values':
1213
+ case 'slushbucket':
1214
+ case 'snapshot_template_value':
1215
+ case 'source_id':
1216
+ case 'source_name':
1217
+ case 'source_table':
1218
+ case 'string_boolean':
1219
+ case 'string_full_utf8':
1220
+ case 'structure':
1221
+ case 'sysevent_name':
1222
+ case 'sysrule_field_name':
1223
+ case 'sys_class_path':
1224
+ case 'template_value':
1225
+ case 'time':
1226
+ case 'timer':
1227
+ case 'translated':
1228
+ case 'translated_html':
1229
+ case 'tree_code':
1230
+ case 'tree_path':
1231
+ case 'url':
1232
+ case 'user_image':
1233
+ case 'user_input':
1234
+ case 'variables':
1235
+ case 'variable_conditions':
1236
+ case 'variable_template_value':
1237
+ case 'video':
1238
+ case 'week_of_month':
1239
+ case 'wide_text':
1240
+ case 'wiki_text':
1241
+ case 'wms_job':
1242
+ case 'workflow':
1243
+ case 'workflow_conditions':
1244
+ case 'xml':
1245
+ default:
1246
+ return db_1.GenericColumn;
1247
+ }
1248
+ }
1249
+ //# sourceMappingURL=TablePlugin.js.map