@opencrvs/toolkit 2.1.2 → 2.2.0-rc.045257f

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 (144) hide show
  1. package/build.sh +2 -12
  2. package/create-countryconfig/package.json +1 -1
  3. package/dist/application-config/index.js +41 -9
  4. package/dist/authentication/index.d.ts +1 -0
  5. package/dist/authentication/index.js +30 -6
  6. package/dist/cli.js +944 -2044
  7. package/dist/commons/api/router.d.ts +1546 -243
  8. package/dist/commons/application-config/index.d.ts +2 -2
  9. package/dist/commons/conditionals/conditionals.d.ts +3 -3
  10. package/dist/commons/conditionals/index.d.ts +1 -0
  11. package/dist/commons/conditionals/validate.d.ts +5 -0
  12. package/dist/commons/events/ActionConfig.d.ts +146 -20
  13. package/dist/commons/events/ActionDocument.d.ts +89 -0
  14. package/dist/commons/events/ActionInput.d.ts +56 -4
  15. package/dist/commons/events/ActionType.d.ts +11 -1
  16. package/dist/commons/events/AdvancedSearchConfig.d.ts +12 -0
  17. package/dist/commons/events/AuditLog.d.ts +4 -0
  18. package/dist/commons/events/CompositeFieldValue.d.ts +5 -1
  19. package/dist/commons/events/CountryConfigQueryInput.d.ts +192 -18
  20. package/dist/commons/events/Draft.d.ts +2 -0
  21. package/dist/commons/events/EventConfig.d.ts +27 -6
  22. package/dist/commons/events/EventDocument.d.ts +88 -0
  23. package/dist/commons/events/EventIndex.d.ts +43 -6
  24. package/dist/commons/events/EventMetadata.d.ts +23 -1
  25. package/dist/commons/events/EventStatus.d.ts +1 -0
  26. package/dist/commons/events/FieldConfig.d.ts +11 -1
  27. package/dist/commons/events/FieldTypeMapping.d.ts +6 -6
  28. package/dist/commons/events/Flag.d.ts +1 -7
  29. package/dist/commons/events/PlainDate.d.ts +1 -0
  30. package/dist/commons/events/WorkqueueConfig.d.ts +224 -33
  31. package/dist/commons/events/eventConfigValidation.d.ts +26 -1
  32. package/dist/commons/events/index.d.ts +3 -0
  33. package/dist/commons/events/scopes.d.ts +2 -0
  34. package/dist/commons/events/state/flags.d.ts +1 -1
  35. package/dist/commons/events/state/index.d.ts +10 -2
  36. package/dist/commons/events/state/utils.d.ts +11 -1
  37. package/dist/commons/events/test.utils.d.ts +30 -1
  38. package/dist/commons/events/toNotificationForm.d.ts +17 -0
  39. package/dist/commons/events/utils.d.ts +62 -8
  40. package/dist/conditionals/index.js +16 -4
  41. package/dist/environment/derived-variables.d.ts +16 -4
  42. package/dist/environment/derived-variables.d.ts.map +1 -1
  43. package/dist/environment/derived-variables.js +18 -4
  44. package/dist/environment/dockerhub.d.ts +15 -0
  45. package/dist/environment/dockerhub.d.ts.map +1 -0
  46. package/dist/environment/dockerhub.js +104 -0
  47. package/dist/environment/questions.js +1 -1
  48. package/dist/environment/setup-environment.d.ts.map +1 -1
  49. package/dist/environment/setup-environment.js +67 -18
  50. package/dist/environment/templates.d.ts.map +1 -1
  51. package/dist/events/index.js +496 -129
  52. package/dist/migrations/index.d.ts +9 -0
  53. package/dist/migrations/index.d.ts.map +1 -0
  54. package/dist/migrations/index.js +847 -0
  55. package/dist/migrations/move-declaration-to-declare-action.d.ts +38 -0
  56. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -0
  57. package/dist/migrations/move-declaration-to-declare-action.js +377 -0
  58. package/dist/migrations/{v2.1 → persistent}/add-translations.d.ts +7 -1
  59. package/dist/migrations/persistent/add-translations.d.ts.map +1 -0
  60. package/dist/migrations/{v2.1 → persistent}/add-translations.js +14 -12
  61. package/dist/migrations/persistent/check-upgrade-path.d.ts +36 -0
  62. package/dist/migrations/persistent/check-upgrade-path.d.ts.map +1 -0
  63. package/dist/migrations/persistent/check-upgrade-path.js +105 -0
  64. package/dist/migrations/persistent/update-toolkit-dependency.d.ts +7 -0
  65. package/dist/migrations/persistent/update-toolkit-dependency.d.ts.map +1 -0
  66. package/dist/migrations/persistent/update-toolkit-dependency.js +77 -0
  67. package/dist/migrations/read-declaration-through-helper.d.ts +39 -0
  68. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -0
  69. package/dist/migrations/read-declaration-through-helper.js +257 -0
  70. package/dist/migrations/replace-incomplete-flag.d.ts +26 -0
  71. package/dist/migrations/replace-incomplete-flag.d.ts.map +1 -0
  72. package/dist/migrations/replace-incomplete-flag.js +126 -0
  73. package/dist/notification/index.js +390 -106
  74. package/dist/scopes/index.d.ts +83 -90
  75. package/dist/scopes/index.js +26 -6
  76. package/dist/templates/charts-values/dependencies/values.yaml +1 -1
  77. package/dist/templates/charts-values/opencrvs-services/values.yaml +3 -5
  78. package/dist/templates/charts-values/traefik/values.yaml +4 -3
  79. package/opencrvs-toolkit-2.2.0-rc.045257f.tgz +0 -0
  80. package/package.json +2 -2
  81. package/tsconfig.build.tsbuildinfo +1 -1
  82. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts +0 -3
  83. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts.map +0 -1
  84. package/dist/migrations/v2.1/add-explicit-correction-flags.js +0 -234
  85. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +0 -3
  86. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +0 -1
  87. package/dist/migrations/v2.1/add-recovery-link-notifications.js +0 -511
  88. package/dist/migrations/v2.1/add-translations.d.ts.map +0 -1
  89. package/dist/migrations/v2.1/enable-telemetry.d.ts +0 -3
  90. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +0 -1
  91. package/dist/migrations/v2.1/enable-telemetry.js +0 -455
  92. package/dist/migrations/v2.1/index.d.ts +0 -6
  93. package/dist/migrations/v2.1/index.d.ts.map +0 -1
  94. package/dist/migrations/v2.1/index.js +0 -2170
  95. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +0 -14
  96. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +0 -1
  97. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +0 -348
  98. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +0 -2
  99. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +0 -1
  100. package/dist/migrations/v2.1/remove-metabase-package-installs.js +0 -161
  101. package/dist/migrations/v2.1/remove-sentry.d.ts +0 -3
  102. package/dist/migrations/v2.1/remove-sentry.d.ts.map +0 -1
  103. package/dist/migrations/v2.1/remove-sentry.js +0 -354
  104. package/dist/migrations/v2.1/rename-trigger-paths.d.ts +0 -3
  105. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +0 -1
  106. package/dist/migrations/v2.1/rename-trigger-paths.js +0 -216
  107. package/dist/migrations/v2.1/template-files.d.ts +0 -8
  108. package/dist/migrations/v2.1/template-files.d.ts.map +0 -1
  109. package/dist/migrations/v2.1/template-files.js +0 -49
  110. package/dist/migrations/v2.1/upgrade-tilt.d.ts +0 -8
  111. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +0 -1
  112. package/dist/migrations/v2.1/upgrade-tilt.js +0 -139
  113. package/dist/templates/countryconfig-template/.tiltignore +0 -1
  114. package/dist/templates/countryconfig-template/Dockerfile.assets +0 -7
  115. package/dist/templates/countryconfig-template/Tiltfile +0 -112
  116. package/dist/templates/countryconfig-template/assets/README.md +0 -1
  117. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +0 -61
  118. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +0 -455
  119. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +0 -168
  120. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +0 -67
  121. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +0 -168
  122. package/dist/templates/countryconfig-template/assets/metabase/README.md +0 -34
  123. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +0 -36
  124. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +0 -46
  125. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +0 -27737
  126. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +0 -21
  127. package/dist/templates/countryconfig-template/assets/metabase/package.json +0 -13
  128. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +0 -108
  129. package/dist/templates/countryconfig-template/assets/metabase/run.sh +0 -120
  130. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +0 -40
  131. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +0 -135
  132. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +0 -108
  133. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +0 -50
  134. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +0 -35
  135. package/dist/templates/countryconfig-template/tilt/common.tilt +0 -145
  136. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +0 -15
  137. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +0 -56
  138. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +0 -21
  139. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +0 -38
  140. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +0 -17
  141. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +0 -16
  142. package/dist/templates/countryconfig-template/tilt/lib.tilt +0 -95
  143. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +0 -136
  144. package/opencrvs-toolkit-2.1.2.tgz +0 -0
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Codemod: Move the top-level `declaration` given to `defineConfig` onto the
3
+ * event's DECLARE action.
4
+ *
5
+ * Usage:
6
+ * ts-node -r tsconfig-paths/register src/migrations/move-declaration-to-declare-action.ts
7
+ *
8
+ * Why:
9
+ * As of v2.2 the declaration form lives on the DECLARE action. `defineConfig`
10
+ * still accepts a top-level `declaration`, but warns that it is deprecated
11
+ * and will stop accepting it in a future release.
12
+ *
13
+ * What it does:
14
+ * - Scans all TypeScript files under `src/`
15
+ * - Finds every call to the toolkit's `defineConfig` given an object literal
16
+ * with a top-level `declaration`
17
+ * - Moves that `declaration` property, as written, into the object literal
18
+ * of the DECLARE action in `actions`, after its `label` (or its `type` when
19
+ * it has no `label`)
20
+ * - Moves the comments on the lines above it and after it with it
21
+ * - Logs, without changing, configs it cannot rewrite safely: a config not
22
+ * given as an object literal, `actions` that is not an array literal, an
23
+ * action not written inline whose type does not rule out DECLARE, no
24
+ * DECLARE action or more than one, and a DECLARE action that already has
25
+ * a `declaration` (which `defineConfig` rejects)
26
+ * - Saves the modified files in-place
27
+ */
28
+ import { SourceFile } from 'ts-morph';
29
+ /**
30
+ * Moves the top-level `declaration` of every toolkit `defineConfig` call in the
31
+ * file onto its DECLARE action.
32
+ *
33
+ * @returns the number of event configs rewritten.
34
+ */
35
+ export declare function moveDeclarationToDeclareAction(sourceFile: SourceFile): number;
36
+ declare function main(): Promise<void>;
37
+ export { main };
38
+ //# sourceMappingURL=move-declaration-to-declare-action.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"move-declaration-to-declare-action.d.ts","sourceRoot":"","sources":["../../src/migrations/move-declaration-to-declare-action.ts"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAOL,UAAU,EAGX,MAAM,UAAU,CAAA;AAmWjB;;;;;GAKG;AACH,wBAAgB,8BAA8B,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAqD7E;AAED,iBAAe,IAAI,kBA6ClB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -0,0 +1,377 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
+ return new (P || (P = Promise))(function (resolve, reject) {
15
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
19
+ });
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.moveDeclarationToDeclareAction = moveDeclarationToDeclareAction;
26
+ exports.main = main;
27
+ /**
28
+ * Codemod: Move the top-level `declaration` given to `defineConfig` onto the
29
+ * event's DECLARE action.
30
+ *
31
+ * Usage:
32
+ * ts-node -r tsconfig-paths/register src/migrations/move-declaration-to-declare-action.ts
33
+ *
34
+ * Why:
35
+ * As of v2.2 the declaration form lives on the DECLARE action. `defineConfig`
36
+ * still accepts a top-level `declaration`, but warns that it is deprecated
37
+ * and will stop accepting it in a future release.
38
+ *
39
+ * What it does:
40
+ * - Scans all TypeScript files under `src/`
41
+ * - Finds every call to the toolkit's `defineConfig` given an object literal
42
+ * with a top-level `declaration`
43
+ * - Moves that `declaration` property, as written, into the object literal
44
+ * of the DECLARE action in `actions`, after its `label` (or its `type` when
45
+ * it has no `label`)
46
+ * - Moves the comments on the lines above it and after it with it
47
+ * - Logs, without changing, configs it cannot rewrite safely: a config not
48
+ * given as an object literal, `actions` that is not an array literal, an
49
+ * action not written inline whose type does not rule out DECLARE, no
50
+ * DECLARE action or more than one, and a DECLARE action that already has
51
+ * a `declaration` (which `defineConfig` rejects)
52
+ * - Saves the modified files in-place
53
+ */
54
+ const ts_morph_1 = require("ts-morph");
55
+ const path_1 = __importDefault(require("path"));
56
+ const DEFINE_CONFIG_NAME = 'defineConfig';
57
+ const DECLARATION_PROPERTY_NAME = 'declaration';
58
+ const ACTIONS_PROPERTY_NAME = 'actions';
59
+ const DECLARE_ACTION_TYPE = 'DECLARE';
60
+ function location(node) {
61
+ const relPath = path_1.default.relative(process.cwd(), node.getSourceFile().getFilePath());
62
+ return `${relPath}:${node.getStartLineNumber()}`;
63
+ }
64
+ /**
65
+ * Returns true if the call is to the `defineConfig` published by the toolkit,
66
+ * as opposed to a function of the same name declared in the country config.
67
+ */
68
+ function isToolkitDefineConfigCall(call) {
69
+ var _a;
70
+ const symbol = call.getExpression().getSymbol();
71
+ const resolved = (_a = symbol === null || symbol === void 0 ? void 0 : symbol.getAliasedSymbol()) !== null && _a !== void 0 ? _a : symbol;
72
+ if ((resolved === null || resolved === void 0 ? void 0 : resolved.getName()) !== DEFINE_CONFIG_NAME) {
73
+ return false;
74
+ }
75
+ return resolved
76
+ .getDeclarations()
77
+ .some((declaration) => declaration.getSourceFile().isDeclarationFile());
78
+ }
79
+ /** Finds a property given by name, whether written `key: value` or shorthand. */
80
+ function findProperty(literal, name) {
81
+ const property = literal.getProperty(name);
82
+ return ts_morph_1.Node.isPropertyAssignment(property) ||
83
+ ts_morph_1.Node.isShorthandPropertyAssignment(property)
84
+ ? property
85
+ : undefined;
86
+ }
87
+ /**
88
+ * Returns false only if the action type's `type` is known to be some other
89
+ * action: a string literal, or a union of them, other than DECLARE.
90
+ */
91
+ function mayHaveDeclareType(actionType, node) {
92
+ const typeProperty = actionType.getProperty('type');
93
+ if (!typeProperty) {
94
+ return true;
95
+ }
96
+ const type = typeProperty.getTypeAtLocation(node);
97
+ const values = type.isUnion() ? type.getUnionTypes() : [type];
98
+ return !values.every((value) => value.isStringLiteral() && value.getLiteralValue() !== DECLARE_ACTION_TYPE);
99
+ }
100
+ /**
101
+ * Returns true if the node may be the DECLARE action. An action not written
102
+ * inline (a variable, a call, a spread) may be, unless its type shows it is
103
+ * some other action.
104
+ */
105
+ function mayBeDeclareAction(node) {
106
+ if (ts_morph_1.Node.isObjectLiteralExpression(node)) {
107
+ return isDeclareAction(node);
108
+ }
109
+ if (ts_morph_1.Node.isSpreadElement(node)) {
110
+ const arrayType = node.getExpression().getType();
111
+ const elementTypes = arrayType.isTuple()
112
+ ? arrayType.getTupleElements()
113
+ : [arrayType.getArrayElementType()];
114
+ return elementTypes.some((elementType) => !elementType || mayHaveDeclareType(elementType, node));
115
+ }
116
+ return mayHaveDeclareType(node.getType(), node);
117
+ }
118
+ function isDeclareAction(literal) {
119
+ const type = findProperty(literal, 'type');
120
+ return (ts_morph_1.Node.isPropertyAssignment(type) &&
121
+ type.getInitializerOrThrow().getType().getLiteralValue() ===
122
+ DECLARE_ACTION_TYPE);
123
+ }
124
+ /**
125
+ * Finds the DECLARE action in `actions`, or logs why the config cannot be
126
+ * rewritten and returns undefined.
127
+ */
128
+ function findDeclareAction(config) {
129
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
130
+ const actionsValue = ts_morph_1.Node.isPropertyAssignment(actions)
131
+ ? actions.getInitializer()
132
+ : undefined;
133
+ if (!ts_morph_1.Node.isArrayLiteralExpression(actionsValue)) {
134
+ console.warn(` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`);
135
+ return undefined;
136
+ }
137
+ const candidates = actionsValue.getElements().filter(mayBeDeclareAction);
138
+ if (candidates.length !== 1 ||
139
+ !ts_morph_1.Node.isObjectLiteralExpression(candidates[0])) {
140
+ console.warn(` [${location(config)}] Skipped: could not find exactly one ${DECLARE_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME}\`. Move \`${DECLARATION_PROPERTY_NAME}\` onto it by hand.`);
141
+ return undefined;
142
+ }
143
+ const declareAction = candidates[0];
144
+ if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
145
+ console.warn(` [${location(config)}] Skipped: \`${DECLARATION_PROPERTY_NAME}\` is set both at the top level and on the ${DECLARE_ACTION_TYPE} action. Keep only the one on the action.`);
146
+ return undefined;
147
+ }
148
+ return declareAction;
149
+ }
150
+ /** The whitespace the line the node starts on is indented by. */
151
+ function indentationOf(node) {
152
+ var _a;
153
+ var _b;
154
+ const text = node.getSourceFile().getFullText();
155
+ const lineStart = text.lastIndexOf('\n', node.getStart() - 1) + 1;
156
+ return (_b = (_a = /^[ \t]*/.exec(text.slice(lineStart))) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : '';
157
+ }
158
+ /** The text from the position to the end of its line, without the line break. */
159
+ function restOfLine(text, position) {
160
+ const lineEnd = text.indexOf('\n', position);
161
+ return text.slice(position, lineEnd === -1 ? text.length : lineEnd);
162
+ }
163
+ function isOnlyComments(text) {
164
+ return /^\s*(?:\/\/.*|\/\*.*?\*\/\s*)*$/.test(text);
165
+ }
166
+ function layoutOf(property) {
167
+ var _a;
168
+ var _b;
169
+ const text = property.getSourceFile().getFullText();
170
+ const next = property.getNextSibling();
171
+ const hasComma = (next === null || next === void 0 ? void 0 : next.getKind()) === ts_morph_1.SyntaxKind.CommaToken;
172
+ const end = next && hasComma ? next.getEnd() : property.getEnd();
173
+ const trailing = restOfLine(text, end);
174
+ // A comment on the line the previous property ends on is that property's
175
+ const lineBreak = text
176
+ .slice(property.getFullStart(), property.getStart())
177
+ .indexOf('\n');
178
+ if (lineBreak === -1 || !isOnlyComments(trailing)) {
179
+ return {
180
+ ownsLines: false,
181
+ start: property.getStart(true),
182
+ end,
183
+ hasComma,
184
+ trailingComment: ''
185
+ };
186
+ }
187
+ const firstLine = property.getFullStart() + lineBreak + 1;
188
+ return {
189
+ ownsLines: true,
190
+ start: firstLine + ((_b = (_a = /^\s*/.exec(text.slice(firstLine))) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0),
191
+ end,
192
+ hasComma,
193
+ trailingComment: trailing.trimEnd()
194
+ };
195
+ }
196
+ function insertAt(position, text) {
197
+ return { start: position, end: position, text };
198
+ }
199
+ /**
200
+ * Returns the edits inserting the property into the DECLARE action after its
201
+ * `label`, or after its `type` when it has no `label`, in the action's own
202
+ * layout: on lines of its own at the anchor's indentation, together with its
203
+ * comments, or inline when the action is on one line.
204
+ */
205
+ function insertIntoDeclareAction(declareAction, property) {
206
+ var _a;
207
+ // `type` is always there: it is how the DECLARE action was found
208
+ const anchor = (_a = declareAction.getProperty('label')) !== null && _a !== void 0 ? _a : declareAction.getPropertyOrThrow('type');
209
+ const text = property.getSourceFile().getFullText();
210
+ const anchorLayout = layoutOf(anchor);
211
+ const layout = layoutOf(property);
212
+ const indent = indentationOf(anchor);
213
+ // Copied as text so the value keeps its formatting and its comments, with
214
+ // continuation lines re-indented from the property's indentation to the
215
+ // anchor's
216
+ const oldIndent = indentationOf(property);
217
+ const reindent = (lines) => lines
218
+ .split('\n')
219
+ .map((line, index) => index > 0 && line.startsWith(oldIndent)
220
+ ? indent + line.slice(oldIndent.length)
221
+ : line)
222
+ .join('\n');
223
+ if (anchorLayout.ownsLines) {
224
+ const moved = reindent(text.slice(layout.start, property.getEnd()));
225
+ const position = anchorLayout.end + restOfLine(text, anchorLayout.end).length;
226
+ const insertion = `\n${indent}${moved}${anchorLayout.hasComma ? ',' : ''}${layout.trailingComment}`;
227
+ if (anchorLayout.hasComma) {
228
+ return [insertAt(position, insertion)];
229
+ }
230
+ // The anchor was the last property: it needs a comma now
231
+ return position === anchor.getEnd()
232
+ ? [insertAt(position, `,${insertion}`)]
233
+ : [insertAt(anchor.getEnd(), ','), insertAt(position, insertion)];
234
+ }
235
+ const droppedComments = text.slice(layout.start, property.getStart(true)).trim() !== '' ||
236
+ layout.trailingComment !== '';
237
+ if (droppedComments) {
238
+ console.warn(` [${location(property)}] The comments next to \`${DECLARATION_PROPERTY_NAME}\` were not moved with it. Move them onto the ${DECLARE_ACTION_TYPE} action by hand.`);
239
+ }
240
+ const isMultiLine = declareAction.getText().includes('\n');
241
+ const separator = isMultiLine ? `,\n${indent}` : ', ';
242
+ return [
243
+ insertAt(anchor.getEnd(), `${separator}${reindent(property.getText(true))}`)
244
+ ];
245
+ }
246
+ /**
247
+ * Returns the edits removing the property together with the comma separating
248
+ * it from its neighbours and, when it is on lines of its own, those lines.
249
+ */
250
+ function removeFromConfig(property) {
251
+ var _a;
252
+ const text = property.getSourceFile().getFullText();
253
+ const layout = layoutOf(property);
254
+ // The comma before the property, past any comments, which ts-morph lists
255
+ // as siblings
256
+ const previousComma = (_a = property
257
+ .getPreviousSiblings()
258
+ .find((sibling) => !isOnlyComments(sibling.getText()))) === null || _a === void 0 ? void 0 : _a.asKind(ts_morph_1.SyntaxKind.CommaToken);
259
+ if (layout.ownsLines) {
260
+ const lines = {
261
+ start: text.lastIndexOf('\n', layout.start - 1),
262
+ end: layout.end + restOfLine(text, layout.end).length,
263
+ text: ''
264
+ };
265
+ // The last property: drop the comma before it too
266
+ return !layout.hasComma && previousComma
267
+ ? [
268
+ lines,
269
+ {
270
+ start: previousComma.getStart(),
271
+ end: previousComma.getEnd(),
272
+ text: ''
273
+ }
274
+ ]
275
+ : [lines];
276
+ }
277
+ if (layout.hasComma) {
278
+ return [{ start: property.getFullStart(), end: layout.end, text: '' }];
279
+ }
280
+ // The last property: drop the comma before it instead
281
+ return [
282
+ {
283
+ start: (previousComma !== null && previousComma !== void 0 ? previousComma : property).getStart(),
284
+ end: property.getEnd(),
285
+ text: ''
286
+ }
287
+ ];
288
+ }
289
+ /**
290
+ * Returns the config given to a toolkit `defineConfig` call when it is an
291
+ * object literal. Logs a config given any other way that may have a top-level
292
+ * `declaration`, as it cannot be rewritten.
293
+ */
294
+ function findConfigLiteral(call) {
295
+ const config = call.getArguments()[0];
296
+ if (!config || ts_morph_1.Node.isObjectLiteralExpression(config)) {
297
+ return config;
298
+ }
299
+ if (config.getType().getProperty(DECLARATION_PROPERTY_NAME)) {
300
+ console.warn(` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME}\` is not given an object literal. If its config has a top-level \`${DECLARATION_PROPERTY_NAME}\`, move it onto the ${DECLARE_ACTION_TYPE} action by hand.`);
301
+ }
302
+ return undefined;
303
+ }
304
+ /**
305
+ * Moves the top-level `declaration` of every toolkit `defineConfig` call in the
306
+ * file onto its DECLARE action.
307
+ *
308
+ * @returns the number of event configs rewritten.
309
+ */
310
+ function moveDeclarationToDeclareAction(sourceFile) {
311
+ const configs = sourceFile
312
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.CallExpression)
313
+ .filter(isToolkitDefineConfigCall)
314
+ .map(findConfigLiteral)
315
+ .filter(ts_morph_1.Node.isObjectLiteralExpression);
316
+ // Collected as text edits and applied together, as editing a node through
317
+ // ts-morph invalidates nodes still waiting to be edited
318
+ const edits = [];
319
+ let changes = 0;
320
+ for (const config of configs) {
321
+ const declaration = findProperty(config, DECLARATION_PROPERTY_NAME);
322
+ if (!declaration) {
323
+ continue;
324
+ }
325
+ const declareAction = findDeclareAction(config);
326
+ if (!declareAction) {
327
+ continue;
328
+ }
329
+ console.log(` [${location(declaration)}] Moved \`${declaration.getText()}\` onto the ${DECLARE_ACTION_TYPE} action`);
330
+ edits.push(...insertIntoDeclareAction(declareAction, declaration), ...removeFromConfig(declaration));
331
+ changes++;
332
+ }
333
+ if (changes === 0) {
334
+ return 0;
335
+ }
336
+ // Applied from the end of the file, so each edit leaves the positions of
337
+ // the ones still to apply untouched
338
+ const text = edits
339
+ .sort((a, b) => b.start - a.start)
340
+ .reduce((result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end), sourceFile.getFullText());
341
+ sourceFile.replaceWithText(text);
342
+ return changes;
343
+ }
344
+ function main() {
345
+ return __awaiter(this, void 0, void 0, function* () {
346
+ const srcDir = path_1.default.join(process.cwd(), 'src');
347
+ console.log(`Scanning for top-level event declarations in: ${srcDir}\n`);
348
+ const project = new ts_morph_1.Project({
349
+ tsConfigFilePath: path_1.default.resolve(srcDir, '../tsconfig.json'),
350
+ skipAddingFilesFromTsConfig: false
351
+ });
352
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
353
+ const fp = sf.getFilePath();
354
+ return fp.includes('/src/') && !fp.includes('/node_modules/');
355
+ });
356
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.\n`);
357
+ let totalChanges = 0;
358
+ const modifiedFiles = [];
359
+ for (const sourceFile of sourceFiles) {
360
+ const changes = moveDeclarationToDeclareAction(sourceFile);
361
+ if (changes > 0) {
362
+ totalChanges += changes;
363
+ modifiedFiles.push(sourceFile);
364
+ }
365
+ }
366
+ if (modifiedFiles.length === 0) {
367
+ console.log('No top-level event declarations found. Nothing to do.');
368
+ return;
369
+ }
370
+ console.log(`\nSaving ${modifiedFiles.length} modified file(s)...`);
371
+ for (const sourceFile of modifiedFiles) {
372
+ yield sourceFile.save();
373
+ console.log(` Saved: ${path_1.default.relative(process.cwd(), sourceFile.getFilePath())}`);
374
+ }
375
+ console.log(`\nDone. Moved ${totalChanges} declaration(s) across ${modifiedFiles.length} file(s).`);
376
+ });
377
+ }
@@ -4,6 +4,12 @@ import { CsvFile } from '../../csv';
4
4
  * local file's columns.
5
5
  */
6
6
  export declare function rowsToAdd(local: CsvFile, template: CsvFile): string[];
7
- declare function main(): Promise<void>;
7
+ /**
8
+ * @param targetVersion the major.minor the country config is upgraded to, e.g. `2.2`.
9
+ */
10
+ declare function main(targetVersion: string): Promise<void>;
11
+ /**
12
+ * @knipignore
13
+ */
8
14
  export { main };
9
15
  //# sourceMappingURL=add-translations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"add-translations.d.ts","sourceRoot":"","sources":["../../../src/migrations/persistent/add-translations.ts"],"names":[],"mappings":"AAkCA,OAAO,EACL,OAAO,EAMR,MAAM,WAAW,CAAA;AAYlB;;;GAGG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,GAAG,MAAM,EAAE,CAgBrE;AAqED;;GAEG;AACH,iBAAe,IAAI,CAAC,aAAa,EAAE,MAAM,iBA2BxC;AAED;;GAEG;AACH,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -29,8 +29,9 @@ exports.main = main;
29
29
  * config.
30
30
  *
31
31
  * Unlike every other codemod, this one carries no list of what it changes, and
32
- * should not need editing again. Its input is `client.csv` and `login.csv` from
33
- * the country config template of the version being upgraded to, fetched from
32
+ * should not need editing again: every version's upgrade runs it, passing the
33
+ * version it upgrades to. Its input is `client.csv` and `login.csv` from
34
+ * the country config template of that version, fetched from
34
35
  * GitHub; whatever rows those files have gained, this adds. A pull request that
35
36
  * introduces a translation key therefore only has to add it to the template —
36
37
  * `packages/countryconfig-template/src/translations/` — which the
@@ -48,8 +49,6 @@ const path_1 = __importDefault(require("path"));
48
49
  const csv_1 = require("../../csv");
49
50
  const template_1 = require("../../translations/template");
50
51
  const APPLICATIONS = ['client', 'login'];
51
- /** The version this folder upgrades a country config to. */
52
- const TARGET_VERSION = '2.1';
53
52
  const skipped = [];
54
53
  function warnSkipped(message) {
55
54
  skipped.push(message);
@@ -73,7 +72,7 @@ function rowsToAdd(local, template) {
73
72
  }));
74
73
  });
75
74
  }
76
- function updateApplication(cwd, refs, application) {
75
+ function updateApplication(cwd, targetVersion, refs, application) {
77
76
  return __awaiter(this, void 0, void 0, function* () {
78
77
  const relativePath = `src/translations/${application}.csv`;
79
78
  const local = (0, csv_1.readCsvFile)(path_1.default.join(cwd, relativePath));
@@ -83,7 +82,7 @@ function updateApplication(cwd, refs, application) {
83
82
  }
84
83
  const fetched = yield (0, template_1.fetchTemplate)(refs, application);
85
84
  if (!fetched) {
86
- warnSkipped(`No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`);
85
+ warnSkipped(`No ${application}.csv found in the ${targetVersion} country config template on GitHub; ${application}.csv not updated`);
87
86
  return;
88
87
  }
89
88
  const template = readTemplate(fetched.contents);
@@ -113,26 +112,29 @@ function readTemplate(contents) {
113
112
  };
114
113
  }
115
114
  /** Refs to read the template from. Undefined when GitHub cannot be asked. */
116
- function listRefs() {
115
+ function listRefs(targetVersion) {
117
116
  return __awaiter(this, void 0, void 0, function* () {
118
117
  try {
119
- return yield (0, template_1.candidateRefs)(TARGET_VERSION);
118
+ return yield (0, template_1.candidateRefs)(targetVersion);
120
119
  }
121
120
  catch (error) {
122
- warnSkipped(`Could not list the ${TARGET_VERSION} refs on GitHub (${error.message}); translations not added`);
121
+ warnSkipped(`Could not list the ${targetVersion} refs on GitHub (${error.message}); translations not added`);
123
122
  return undefined;
124
123
  }
125
124
  });
126
125
  }
127
- function main() {
126
+ /**
127
+ * @param targetVersion the major.minor the country config is upgraded to, e.g. `2.2`.
128
+ */
129
+ function main(targetVersion) {
128
130
  return __awaiter(this, void 0, void 0, function* () {
129
131
  const cwd = process.cwd();
130
132
  console.log('Adding the translation keys core gained this version...\n');
131
- const refs = yield listRefs();
133
+ const refs = yield listRefs(targetVersion);
132
134
  if (refs) {
133
135
  for (const application of APPLICATIONS) {
134
136
  try {
135
- yield updateApplication(cwd, refs, application);
137
+ yield updateApplication(cwd, targetVersion, refs, application);
136
138
  }
137
139
  catch (error) {
138
140
  warnSkipped(`Could not read ${application}.csv from the country config template on GitHub (${error.message}); ${application}.csv not updated`);
@@ -0,0 +1,36 @@
1
+ export declare const TOOLKIT_PACKAGE_NAME = "@opencrvs/toolkit";
2
+ interface MajorMinor {
3
+ major: number;
4
+ minor: number;
5
+ }
6
+ export type UpgradePathCheck = {
7
+ status: 'ok';
8
+ } | {
9
+ status: 'unknown';
10
+ message: string;
11
+ } | {
12
+ status: 'blocked';
13
+ message: string;
14
+ };
15
+ /**
16
+ * Reads the major.minor out of a version or a version range, e.g. `2.1` out of
17
+ * `2.1.0`, `^2.1.3` or `2.2.0-rc.1`. Returns undefined when there is none, as
18
+ * in `workspace:*` or `latest`.
19
+ */
20
+ export declare function findMajorMinor(version: string): MajorMinor | undefined;
21
+ /**
22
+ * Returns the `@opencrvs/toolkit` version the country config in the directory
23
+ * depends on, as written in its `package.json`, or undefined when it has none.
24
+ */
25
+ export declare function findCountryConfigToolkitVersion(cwd: string): string | undefined;
26
+ /**
27
+ * Checks that the country config is on the minor version before the toolkit's,
28
+ * or already on the toolkit's: the steps are idempotent, so running them again
29
+ * after a patch release is safe.
30
+ *
31
+ * @param countryConfigToolkitVersion the toolkit version the country config depends on.
32
+ * @param toolkitVersion the version of the toolkit running the upgrade.
33
+ */
34
+ export declare function checkUpgradePath(countryConfigToolkitVersion: string | undefined, toolkitVersion: string): UpgradePathCheck;
35
+ export {};
36
+ //# sourceMappingURL=check-upgrade-path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check-upgrade-path.d.ts","sourceRoot":"","sources":["../../../src/migrations/persistent/check-upgrade-path.ts"],"names":[],"mappings":"AAqBA,eAAO,MAAM,oBAAoB,sBAAsB,CAAA;AAEvD,UAAU,UAAU;IAClB,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;CACd;AAED,MAAM,MAAM,gBAAgB,GACxB;IAAE,MAAM,EAAE,IAAI,CAAA;CAAE,GAChB;IAAE,MAAM,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACtC;IAAE,MAAM,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAA;AAE1C;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAMtE;AAMD;;;GAGG;AACH,wBAAgB,+BAA+B,CAC7C,GAAG,EAAE,MAAM,GACV,MAAM,GAAG,SAAS,CAapB;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAC9B,2BAA2B,EAAE,MAAM,GAAG,SAAS,EAC/C,cAAc,EAAE,MAAM,GACrB,gBAAgB,CAoDlB"}
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __importDefault = (this && this.__importDefault) || function (mod) {
13
+ return (mod && mod.__esModule) ? mod : { "default": mod };
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.TOOLKIT_PACKAGE_NAME = void 0;
17
+ exports.findMajorMinor = findMajorMinor;
18
+ exports.findCountryConfigToolkitVersion = findCountryConfigToolkitVersion;
19
+ exports.checkUpgradePath = checkUpgradePath;
20
+ /**
21
+ * Checks that a country config is upgraded one minor version at a time, as the
22
+ * documentation recommends. The toolkit only carries the steps from the
23
+ * previous minor to its own, so upgrading from further back would silently skip
24
+ * the steps of the versions in between.
25
+ */
26
+ const fs_1 = __importDefault(require("fs"));
27
+ const path_1 = __importDefault(require("path"));
28
+ exports.TOOLKIT_PACKAGE_NAME = '@opencrvs/toolkit';
29
+ /**
30
+ * Reads the major.minor out of a version or a version range, e.g. `2.1` out of
31
+ * `2.1.0`, `^2.1.3` or `2.2.0-rc.1`. Returns undefined when there is none, as
32
+ * in `workspace:*` or `latest`.
33
+ */
34
+ function findMajorMinor(version) {
35
+ const match = /(\d+)\.(\d+)/.exec(version);
36
+ return match
37
+ ? { major: Number(match[1]), minor: Number(match[2]) }
38
+ : undefined;
39
+ }
40
+ function format({ major, minor }) {
41
+ return `${major}.${minor}`;
42
+ }
43
+ /**
44
+ * Returns the `@opencrvs/toolkit` version the country config in the directory
45
+ * depends on, as written in its `package.json`, or undefined when it has none.
46
+ */
47
+ function findCountryConfigToolkitVersion(cwd) {
48
+ var _a, _b;
49
+ var _c;
50
+ try {
51
+ const packageJson = JSON.parse(fs_1.default.readFileSync(path_1.default.join(cwd, 'package.json'), 'utf-8'));
52
+ return ((_c = (_a = packageJson.dependencies) === null || _a === void 0 ? void 0 : _a[exports.TOOLKIT_PACKAGE_NAME]) !== null && _c !== void 0 ? _c : (_b = packageJson.devDependencies) === null || _b === void 0 ? void 0 : _b[exports.TOOLKIT_PACKAGE_NAME]);
53
+ }
54
+ catch (_d) {
55
+ return undefined;
56
+ }
57
+ }
58
+ /**
59
+ * Checks that the country config is on the minor version before the toolkit's,
60
+ * or already on the toolkit's: the steps are idempotent, so running them again
61
+ * after a patch release is safe.
62
+ *
63
+ * @param countryConfigToolkitVersion the toolkit version the country config depends on.
64
+ * @param toolkitVersion the version of the toolkit running the upgrade.
65
+ */
66
+ function checkUpgradePath(countryConfigToolkitVersion, toolkitVersion) {
67
+ const target = findMajorMinor(toolkitVersion);
68
+ const current = countryConfigToolkitVersion
69
+ ? findMajorMinor(countryConfigToolkitVersion)
70
+ : undefined;
71
+ if (!target || !current) {
72
+ return {
73
+ status: 'unknown',
74
+ message: `Could not tell which version the country config is on from its ${exports.TOOLKIT_PACKAGE_NAME} dependency (${countryConfigToolkitVersion !== null && countryConfigToolkitVersion !== void 0 ? countryConfigToolkitVersion : 'not found'}). Make sure it is on the version before ${toolkitVersion}: upgrade one minor version at a time.`
75
+ };
76
+ }
77
+ const isSameVersion = current.major === target.major && current.minor === target.minor;
78
+ const isPreviousMinor = current.major === target.major && current.minor === target.minor - 1;
79
+ // Which minor a major ends on is not known here, so any minor of the
80
+ // previous major is let through to the next major's x.0
81
+ const isPreviousMajor = target.minor === 0 && current.major === target.major - 1;
82
+ if (isSameVersion || isPreviousMinor || isPreviousMajor) {
83
+ return { status: 'ok' };
84
+ }
85
+ const isNewer = current.major > target.major ||
86
+ (current.major === target.major && current.minor > target.minor);
87
+ if (isNewer) {
88
+ return {
89
+ status: 'blocked',
90
+ message: `The country config is already on ${format(current)}, newer than toolkit ${toolkitVersion}. Run the upgrade with the toolkit of the version you are upgrading to.`
91
+ };
92
+ }
93
+ const upgradesFrom = target.minor > 0
94
+ ? format({ major: target.major, minor: target.minor - 1 })
95
+ : `the last ${target.major - 1}.x`;
96
+ // Which minor a major ends on is not known here, so the next version is
97
+ // named only within a major
98
+ const nextStep = current.major === target.major
99
+ ? `: run \`npx ${exports.TOOLKIT_PACKAGE_NAME}@${format({ major: current.major, minor: current.minor + 1 })} upgrade\` first`
100
+ : '';
101
+ return {
102
+ status: 'blocked',
103
+ message: `The country config is on ${format(current)}, but toolkit ${toolkitVersion} only upgrades from ${upgradesFrom}. Upgrade one minor version at a time${nextStep}.`
104
+ };
105
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Returns the `package.json` text with its toolkit dependency set to the
3
+ * version, or undefined when there is nothing to update.
4
+ */
5
+ export declare function updateToolkitDependency(packageJson: string, toolkitVersion: string): string | undefined;
6
+ export declare function main(toolkitVersion: string): Promise<void>;
7
+ //# sourceMappingURL=update-toolkit-dependency.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-toolkit-dependency.d.ts","sourceRoot":"","sources":["../../../src/migrations/persistent/update-toolkit-dependency.ts"],"names":[],"mappings":"AAoCA;;;GAGG;AACH,wBAAgB,uBAAuB,CACrC,WAAW,EAAE,MAAM,EACnB,cAAc,EAAE,MAAM,GACrB,MAAM,GAAG,SAAS,CAepB;AAED,wBAAsB,IAAI,CAAC,cAAc,EAAE,MAAM,iBAwBhD"}