@inlang/sdk 0.34.3 → 0.34.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2024] [Opral US Inc.]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -177,7 +177,7 @@ describe("messages", () => {
177
177
  project.setSettings({ ...project.settings(), languageTags: ["en"] });
178
178
  // TODO: how can we await `setConfig` correctly
179
179
  await new Promise((resolve) => setTimeout(resolve, 510));
180
- expect(effectOnMessagesCounter).toBe(1); // 2 times because effect creation + set
180
+ expect(effectOnMessagesCounter).toBe(7); // 7 = initial effect, setSetting, loadMessage (2x - one per message), setResolvedPlugins, loadMessages (2x - one per message)
181
181
  expect(Object.values(project.query.messages.getAll()).length).toBe(2);
182
182
  });
183
183
  it("should react to message udpate", async () => {
@@ -1,7 +1,19 @@
1
- import type { Message } from "@inlang/message";
2
1
  import type { InlangProject } from "./api.js";
2
+ import type { resolveModules } from "./resolve-modules/resolveModules.js";
3
+ import type { NodeishFilesystem } from "@lix-js/fs";
4
+ import type { ProjectSettings } from "@inlang/project-settings";
5
+ type createMessagesQueryParameters = {
6
+ projectPath: string;
7
+ nodeishFs: NodeishFilesystem;
8
+ settings: () => ProjectSettings | undefined;
9
+ resolvedModules: () => Awaited<ReturnType<typeof resolveModules>> | undefined;
10
+ onInitialMessageLoadResult: (e?: Error) => void;
11
+ onLoadMessageResult: (e?: Error) => void;
12
+ onSaveMessageResult: (e?: Error) => void;
13
+ };
3
14
  /**
4
15
  * Creates a reactive query API for messages.
5
16
  */
6
- export declare function createMessagesQuery(messages: () => Array<Message>): InlangProject["query"]["messages"];
17
+ export declare function createMessagesQuery({ projectPath, nodeishFs, settings, resolvedModules, onInitialMessageLoadResult, onLoadMessageResult, onSaveMessageResult, }: createMessagesQueryParameters): InlangProject["query"]["messages"];
18
+ export {};
7
19
  //# sourceMappingURL=createMessagesQuery.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"createMessagesQuery.d.ts","sourceRoot":"","sources":["../src/createMessagesQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AAI9C,OAAO,KAAK,EAAE,aAAa,EAAmB,MAAM,UAAU,CAAA;AAE9D;;GAEG;AACH,wBAAgB,mBAAmB,CAClC,QAAQ,EAAE,MAAM,KAAK,CAAC,OAAO,CAAC,GAC5B,aAAa,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,CAiFpC"}
1
+ {"version":3,"file":"createMessagesQuery.d.ts","sourceRoot":"","sources":["../src/createMessagesQuery.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAmB,MAAM,UAAU,CAAA;AAE9D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAA;AAEzE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAKnD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAwB/D,KAAK,6BAA6B,GAAG;IACpC,WAAW,EAAE,MAAM,CAAA;IACnB,SAAS,EAAE,iBAAiB,CAAA;IAC5B,QAAQ,EAAE,MAAM,eAAe,GAAG,SAAS,CAAA;IAC3C,eAAe,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC,GAAG,SAAS,CAAA;IAC7E,0BAA0B,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,KAAK,IAAI,CAAA;IAC/C,mBAAmB,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,KAAK,IAAI,CAAA;IACxC,mBAAmB,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,KAAK,IAAI,CAAA;CACxC,CAAA;AACD;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,EACnC,WAAW,EACX,SAAS,EACT,QAAQ,EACR,eAAe,EACf,0BAA0B,EAC1B,mBAAmB,EACnB,mBAAmB,GACnB,EAAE,6BAA6B,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,CA6LpE"}
@@ -1,29 +1,112 @@
1
1
  import { ReactiveMap } from "./reactivity/map.js";
2
2
  import { createEffect } from "./reactivity/solid.js";
3
3
  import { createSubscribable } from "./loadProject.js";
4
+ import { createNodeishFsWithWatcher } from "./createNodeishFsWithWatcher.js";
5
+ import { onCleanup } from "solid-js";
6
+ import { stringifyMessage } from "./storage/helper.js";
7
+ import { acquireFileLock } from "./persistence/filelock/acquireFileLock.js";
8
+ import _debug from "debug";
9
+ import { releaseLock } from "./persistence/filelock/releaseLock.js";
10
+ import { PluginLoadMessagesError, PluginSaveMessagesError } from "./errors.js";
11
+ import { humanIdHash } from "./storage/human-id/human-readable-id.js";
12
+ const debug = _debug("sdk:createMessagesQuery");
4
13
  /**
5
14
  * Creates a reactive query API for messages.
6
15
  */
7
- export function createMessagesQuery(messages) {
16
+ export function createMessagesQuery({ projectPath, nodeishFs, settings, resolvedModules, onInitialMessageLoadResult, onLoadMessageResult, onSaveMessageResult, }) {
8
17
  // @ts-expect-error
9
18
  const index = new ReactiveMap();
19
+ // filepath for the lock folder
20
+ const messageLockDirPath = projectPath + "/messagelock";
10
21
  // Map default alias to message
11
22
  // Assumes that aliases are only created and deleted, not updated
12
23
  // TODO #2346 - handle updates to aliases
13
24
  // TODO #2346 - refine to hold messageId[], if default alias is not unique
14
25
  // @ts-expect-error
15
26
  const defaultAliasIndex = new ReactiveMap();
27
+ const messageStates = {
28
+ messageDirtyFlags: {},
29
+ messageLoadHash: {},
30
+ isSaving: false,
31
+ currentSaveMessagesViaPlugin: undefined,
32
+ sheduledSaveMessages: undefined,
33
+ isLoading: false,
34
+ sheduledLoadMessagesViaPlugin: undefined,
35
+ };
36
+ // triggered whenever settings or resolved modules change
16
37
  createEffect(() => {
38
+ // we clear the index independent from the change for
17
39
  index.clear();
18
- for (const message of structuredClone(messages())) {
19
- index.set(message.id, message);
20
- if ("default" in message.alias) {
21
- defaultAliasIndex.set(message.alias.default, message);
22
- }
40
+ defaultAliasIndex.clear();
41
+ // Load messages -> use settings to subscribe to signals from the settings
42
+ const _settings = settings();
43
+ if (!_settings)
44
+ return;
45
+ // wait for first effect excution until modules are resolved
46
+ const resolvedPluginApi = resolvedModules()?.resolvedPluginApi;
47
+ if (!resolvedPluginApi)
48
+ return;
49
+ const abortController = new AbortController();
50
+ // called between executions of effects as well as on disposal
51
+ onCleanup(() => {
52
+ // stop listening on fs events
53
+ abortController.abort();
54
+ });
55
+ const fsWithWatcher = createNodeishFsWithWatcher({
56
+ nodeishFs: nodeishFs,
57
+ // this message is called whenever a file changes that was read earlier by this filesystem
58
+ // - the plugin loads messages -> reads the file messages.json -> start watching on messages.json -> updateMessages
59
+ updateMessages: () => {
60
+ // reload
61
+ loadMessagesViaPlugin(fsWithWatcher, messageLockDirPath, messageStates, index, _settings, // NOTE we bang here - we don't expect the settings to become null during the livetime of a project
62
+ resolvedPluginApi)
63
+ .catch((e) => {
64
+ onLoadMessageResult(e);
65
+ })
66
+ .then(() => {
67
+ onLoadMessageResult();
68
+ });
69
+ },
70
+ abortController,
71
+ });
72
+ if (!resolvedPluginApi.loadMessages) {
73
+ onInitialMessageLoadResult(new Error("no loadMessages in resolved Modules found"));
74
+ return;
23
75
  }
76
+ loadMessagesViaPlugin(fsWithWatcher, messageLockDirPath, messageStates, index, _settings, // NOTE we bang here - we don't expect the settings to become null during the livetime of a project
77
+ resolvedPluginApi)
78
+ .catch((e) => {
79
+ // propagate initial load error to calling laodProject function
80
+ onInitialMessageLoadResult(new PluginLoadMessagesError({ cause: e }));
81
+ })
82
+ .then(() => {
83
+ onInitialMessageLoadResult();
84
+ });
24
85
  });
25
86
  const get = (args) => index.get(args.where.id);
26
87
  const getByDefaultAlias = (alias) => defaultAliasIndex.get(alias);
88
+ const scheduleSave = function () {
89
+ // NOTE: we ignore save calls on a project without settings for now
90
+ const _settings = settings();
91
+ if (!_settings)
92
+ return;
93
+ // wait for first effect excution until modules are resolved
94
+ const resolvedPluginApi = resolvedModules()?.resolvedPluginApi;
95
+ if (!resolvedPluginApi)
96
+ return;
97
+ saveMessagesViaPlugin(nodeishFs, messageLockDirPath, messageStates, index, _settings, // NOTE we bang here - we don't expect the settings to become null during the livetime of a project
98
+ resolvedPluginApi)
99
+ .catch((e) => {
100
+ debug.log("error during saveMessagesViaPlugin");
101
+ debug.log(e);
102
+ })
103
+ .catch((e) => {
104
+ onSaveMessageResult(e);
105
+ })
106
+ .then(() => {
107
+ onSaveMessageResult();
108
+ });
109
+ };
27
110
  return {
28
111
  create: ({ data }) => {
29
112
  if (index.has(data.id))
@@ -32,6 +115,8 @@ export function createMessagesQuery(messages) {
32
115
  if ("default" in data.alias) {
33
116
  defaultAliasIndex.set(data.alias.default, data);
34
117
  }
118
+ messageStates.messageDirtyFlags[data.id] = true;
119
+ scheduleSave();
35
120
  return true;
36
121
  },
37
122
  get: Object.assign(get, {
@@ -51,6 +136,8 @@ export function createMessagesQuery(messages) {
51
136
  if (message === undefined)
52
137
  return false;
53
138
  index.set(where.id, { ...message, ...data });
139
+ messageStates.messageDirtyFlags[where.id] = true;
140
+ scheduleSave();
54
141
  return true;
55
142
  },
56
143
  upsert: ({ where, data }) => {
@@ -64,6 +151,8 @@ export function createMessagesQuery(messages) {
64
151
  else {
65
152
  index.set(where.id, { ...message, ...data });
66
153
  }
154
+ messageStates.messageDirtyFlags[where.id] = true;
155
+ scheduleSave();
67
156
  return true;
68
157
  },
69
158
  delete: ({ where }) => {
@@ -74,7 +163,250 @@ export function createMessagesQuery(messages) {
74
163
  defaultAliasIndex.delete(message.alias.default);
75
164
  }
76
165
  index.delete(where.id);
166
+ messageStates.messageDirtyFlags[where.id] = true;
167
+ scheduleSave();
77
168
  return true;
78
169
  },
79
170
  };
80
171
  }
172
+ // --- serialization of loading / saving messages.
173
+ // 1. A plugin saveMessage call can not be called simultaniously to avoid side effects - its an async function not controlled by us
174
+ // 2. loading and saving must not run in "parallel".
175
+ // - json plugin exports into separate file per language.
176
+ // - saving a message in two different languages would lead to a write in de.json first
177
+ // - This will leads to a load of the messages and since en.json has not been saved yet the english variant in the message would get overritten with the old state again
178
+ /**
179
+ * Messsage that loads messages from a plugin - this method synchronizes with the saveMessage funciton.
180
+ * If a save is in progress loading will wait until saving is done. If another load kicks in during this load it will queue the
181
+ * load and execute it at the end of this load. subsequential loads will not be queued but the same promise will be reused
182
+ *
183
+ * - NOTE: this means that the parameters used to load like settingsValue and loadPlugin might not take into account. this has to be refactored
184
+ * with the loadProject restructuring
185
+ * @param fs
186
+ * @param messagesQuery
187
+ * @param settingsValue
188
+ * @param loadPlugin
189
+ * @returns void - updates the files and messages in of the project in place
190
+ */
191
+ async function loadMessagesViaPlugin(fs, lockDirPath, messageState, messages, settingsValue, resolvedPluginApi) {
192
+ const experimentalAliases = !!settingsValue.experimental?.aliases;
193
+ // loading is an asynchronous process - check if another load is in progress - queue this call if so
194
+ if (messageState.isLoading) {
195
+ if (!messageState.sheduledLoadMessagesViaPlugin) {
196
+ messageState.sheduledLoadMessagesViaPlugin = createAwaitable();
197
+ }
198
+ // another load will take place right after the current one - its goingt to be idempotent form the current requested one - don't reschedule
199
+ return messageState.sheduledLoadMessagesViaPlugin.promise;
200
+ }
201
+ // set loading flag
202
+ messageState.isLoading = true;
203
+ let lockTime = undefined;
204
+ try {
205
+ lockTime = await acquireFileLock(fs, lockDirPath, "loadMessage");
206
+ const loadedMessages = await makeTrulyAsync(resolvedPluginApi.loadMessages({
207
+ settings: settingsValue,
208
+ nodeishFs: fs,
209
+ }));
210
+ for (const loadedMessage of loadedMessages) {
211
+ const loadedMessageClone = structuredClone(loadedMessage);
212
+ const currentMessages = [...messages.values()]
213
+ // TODO #1585 here we match using the id to support legacy load message plugins - after we introduced import / export methods we will use importedMessage.alias
214
+ .filter((message) => (experimentalAliases ? message.alias["default"] : message.id) === loadedMessage.id);
215
+ if (currentMessages.length > 1) {
216
+ // NOTE: if we happen to find two messages witht the sam alias we throw for now
217
+ // - this could be the case if one edits the aliase manualy
218
+ throw new Error("more than one message with the same id or alias found ");
219
+ }
220
+ else if (currentMessages.length === 1) {
221
+ // update message in place - leave message id and alias untouched
222
+ loadedMessageClone.alias = {};
223
+ // TODO #1585 we have to map the id of the importedMessage to the alias and fill the id property with the id of the existing message - change when import mesage provides importedMessage.alias
224
+ if (experimentalAliases) {
225
+ loadedMessageClone.alias["default"] = loadedMessageClone.id;
226
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- length has checked beforhand
227
+ loadedMessageClone.id = currentMessages[0].id;
228
+ }
229
+ // NOTE stringifyMessage encodes messages independent from key order!
230
+ const importedEnecoded = stringifyMessage(loadedMessageClone);
231
+ // NOTE could use hash instead of the whole object JSON to save memory...
232
+ if (messageState.messageLoadHash[loadedMessageClone.id] === importedEnecoded) {
233
+ // debug("skipping upsert!")
234
+ continue;
235
+ }
236
+ // This logic is preventing cycles - could also be handled if update api had a parameter for who triggered update
237
+ // e.g. when FS was updated, we don't need to write back to FS
238
+ // update is synchronous, so update effect will be triggered immediately
239
+ // NOTE: this might trigger a save before we have the chance to delete - but since save is async and waits for the lock acquired by this method - its save to set the flags afterwards
240
+ messages.set(loadedMessageClone.id, loadedMessageClone);
241
+ // NOTE could use hash instead of the whole object JSON to save memory...
242
+ messageState.messageLoadHash[loadedMessageClone.id] = importedEnecoded;
243
+ }
244
+ else {
245
+ // message with the given alias does not exist so far
246
+ loadedMessageClone.alias = {};
247
+ // TODO #1585 we have to map the id of the importedMessage to the alias - change when import mesage provides importedMessage.alias
248
+ if (experimentalAliases) {
249
+ loadedMessageClone.alias["default"] = loadedMessageClone.id;
250
+ let currentOffset = 0;
251
+ let messsageId;
252
+ do {
253
+ messsageId = humanIdHash(loadedMessageClone.id, currentOffset);
254
+ if (messages.get(messsageId)) {
255
+ currentOffset += 1;
256
+ messsageId = undefined;
257
+ }
258
+ } while (messsageId === undefined);
259
+ // create a humanId based on a hash of the alias
260
+ loadedMessageClone.id = messsageId;
261
+ }
262
+ const importedEnecoded = stringifyMessage(loadedMessageClone);
263
+ // we don't have to check - done before hand if (messages.has(loadedMessageClone.id)) return false
264
+ messages.set(loadedMessageClone.id, loadedMessageClone);
265
+ messageState.messageLoadHash[loadedMessageClone.id] = importedEnecoded;
266
+ }
267
+ }
268
+ await releaseLock(fs, lockDirPath, "loadMessage", lockTime);
269
+ lockTime = undefined;
270
+ debug("loadMessagesViaPlugin: " + loadedMessages.length + " Messages processed ");
271
+ messageState.isLoading = false;
272
+ }
273
+ finally {
274
+ if (lockTime !== undefined) {
275
+ await releaseLock(fs, lockDirPath, "loadMessage", lockTime);
276
+ }
277
+ messageState.isLoading = false;
278
+ }
279
+ const executingScheduledMessages = messageState.sheduledLoadMessagesViaPlugin;
280
+ if (executingScheduledMessages) {
281
+ // a load has been requested during the load - executed it
282
+ // reset sheduling to except scheduling again
283
+ messageState.sheduledLoadMessagesViaPlugin = undefined;
284
+ // recall load unawaited to allow stack to pop
285
+ loadMessagesViaPlugin(fs, lockDirPath, messageState, messages, settingsValue, resolvedPluginApi)
286
+ .then(() => {
287
+ // resolve the scheduled load message promise
288
+ executingScheduledMessages.resolve();
289
+ })
290
+ .catch((e) => {
291
+ // reject the scheduled load message promise
292
+ executingScheduledMessages.reject(e);
293
+ });
294
+ }
295
+ }
296
+ async function saveMessagesViaPlugin(fs, lockDirPath, messageState, messages, settingsValue, resolvedPluginApi) {
297
+ // queue next save if we have a save ongoing
298
+ if (messageState.isSaving) {
299
+ if (!messageState.sheduledSaveMessages) {
300
+ messageState.sheduledSaveMessages = createAwaitable();
301
+ }
302
+ return messageState.sheduledSaveMessages.promise;
303
+ }
304
+ // set isSavingFlag
305
+ messageState.isSaving = true;
306
+ messageState.currentSaveMessagesViaPlugin = (async function () {
307
+ const saveMessageHashes = {};
308
+ // check if we have any dirty message - witho
309
+ if (Object.keys(messageState.messageDirtyFlags).length == 0) {
310
+ // nothing to save :-)
311
+ debug("save was skipped - no messages marked as dirty... build!");
312
+ messageState.isSaving = false;
313
+ return;
314
+ }
315
+ let messageDirtyFlagsBeforeSave;
316
+ let lockTime;
317
+ try {
318
+ lockTime = await acquireFileLock(fs, lockDirPath, "saveMessage");
319
+ // since it may takes some time to acquire the lock we check if the save is required still (loadMessage could have happend in between)
320
+ if (Object.keys(messageState.messageDirtyFlags).length == 0) {
321
+ debug("save was skipped - no messages marked as dirty... releasing lock again");
322
+ messageState.isSaving = false;
323
+ // release lock in finally block
324
+ return;
325
+ }
326
+ const currentMessages = [...messages.values()];
327
+ const messagesToExport = [];
328
+ for (const message of currentMessages) {
329
+ if (messageState.messageDirtyFlags[message.id]) {
330
+ const importedEnecoded = stringifyMessage(message);
331
+ // NOTE: could use hash instead of the whole object JSON to save memory...
332
+ saveMessageHashes[message.id] = importedEnecoded;
333
+ }
334
+ const fixedExportMessage = { ...message };
335
+ // TODO #1585 here we match using the id to support legacy load message plugins - after we introduced import / export methods we will use importedMessage.alias
336
+ if (settingsValue.experimental?.aliases) {
337
+ fixedExportMessage.id = fixedExportMessage.alias["default"] ?? fixedExportMessage.id;
338
+ }
339
+ messagesToExport.push(fixedExportMessage);
340
+ }
341
+ // wa are about to save the messages to the plugin - reset all flags now
342
+ messageDirtyFlagsBeforeSave = { ...messageState.messageDirtyFlags };
343
+ messageState.messageDirtyFlags = {};
344
+ // NOTE: this assumes that the plugin will handle message ordering
345
+ await resolvedPluginApi.saveMessages({
346
+ settings: settingsValue,
347
+ messages: messagesToExport,
348
+ nodeishFs: fs,
349
+ });
350
+ for (const [messageId, messageHash] of Object.entries(saveMessageHashes)) {
351
+ messageState.messageLoadHash[messageId] = messageHash;
352
+ }
353
+ if (lockTime !== undefined) {
354
+ await releaseLock(fs, lockDirPath, "saveMessage", lockTime);
355
+ lockTime = undefined;
356
+ }
357
+ // if there is a queued load, allow it to take the lock before we run additional saves.
358
+ if (messageState.sheduledLoadMessagesViaPlugin) {
359
+ debug("saveMessagesViaPlugin calling queued loadMessagesViaPlugin to share lock");
360
+ await loadMessagesViaPlugin(fs, lockDirPath, messageState, messages, settingsValue, resolvedPluginApi);
361
+ }
362
+ messageState.isSaving = false;
363
+ }
364
+ catch (err) {
365
+ // something went wrong - add dirty flags again
366
+ if (messageDirtyFlagsBeforeSave !== undefined) {
367
+ for (const dirtyMessageId of Object.keys(messageDirtyFlagsBeforeSave)) {
368
+ messageState.messageDirtyFlags[dirtyMessageId] = true;
369
+ }
370
+ }
371
+ if (lockTime !== undefined) {
372
+ await releaseLock(fs, lockDirPath, "saveMessage", lockTime);
373
+ lockTime = undefined;
374
+ }
375
+ messageState.isSaving = false;
376
+ // ok an error
377
+ throw new PluginSaveMessagesError({
378
+ cause: err,
379
+ });
380
+ }
381
+ finally {
382
+ if (lockTime !== undefined) {
383
+ await releaseLock(fs, lockDirPath, "saveMessage", lockTime);
384
+ lockTime = undefined;
385
+ }
386
+ messageState.isSaving = false;
387
+ }
388
+ })();
389
+ await messageState.currentSaveMessagesViaPlugin;
390
+ if (messageState.sheduledSaveMessages) {
391
+ const executingSheduledSaveMessages = messageState.sheduledSaveMessages;
392
+ messageState.sheduledSaveMessages = undefined;
393
+ saveMessagesViaPlugin(fs, lockDirPath, messageState, messages, settingsValue, resolvedPluginApi)
394
+ .then(() => {
395
+ executingSheduledSaveMessages.resolve();
396
+ })
397
+ .catch((e) => {
398
+ executingSheduledSaveMessages.reject(e);
399
+ });
400
+ }
401
+ }
402
+ const makeTrulyAsync = (fn) => (async () => fn)();
403
+ const createAwaitable = () => {
404
+ let resolve;
405
+ let reject;
406
+ const promise = new Promise((res, rej) => {
407
+ resolve = res;
408
+ reject = rej;
409
+ });
410
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- those properties get set by new Promise, TS can't know this
411
+ return { promise, resolve: resolve, reject: reject };
412
+ };