@inlang/sdk 0.34.3 → 0.34.5

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 (38) hide show
  1. package/LICENSE +201 -0
  2. package/dist/adapter/solidAdapter.test.js +1 -1
  3. package/dist/api.d.ts +13 -0
  4. package/dist/api.d.ts.map +1 -1
  5. package/dist/createMessagesQuery.d.ts +14 -2
  6. package/dist/createMessagesQuery.d.ts.map +1 -1
  7. package/dist/createMessagesQuery.js +338 -6
  8. package/dist/createMessagesQuery.test.js +133 -88
  9. package/dist/createNodeishFsWithWatcher.d.ts +1 -0
  10. package/dist/createNodeishFsWithWatcher.d.ts.map +1 -1
  11. package/dist/createNodeishFsWithWatcher.js +2 -2
  12. package/dist/createNodeishFsWithWatcher.test.js +8 -0
  13. package/dist/loadProject.d.ts.map +1 -1
  14. package/dist/loadProject.js +21 -487
  15. package/dist/persistence/filelock/acquireFileLock.d.ts +3 -0
  16. package/dist/persistence/filelock/acquireFileLock.d.ts.map +1 -0
  17. package/dist/persistence/filelock/acquireFileLock.js +109 -0
  18. package/dist/persistence/filelock/releaseLock.d.ts +3 -0
  19. package/dist/persistence/filelock/releaseLock.d.ts.map +1 -0
  20. package/dist/persistence/filelock/releaseLock.js +23 -0
  21. package/dist/v2/index.d.ts +2 -0
  22. package/dist/v2/index.d.ts.map +1 -0
  23. package/dist/v2/index.js +1 -0
  24. package/dist/v2/types.d.ts +411 -0
  25. package/dist/v2/types.d.ts.map +1 -0
  26. package/dist/v2/types.js +69 -0
  27. package/package.json +8 -7
  28. package/src/adapter/solidAdapter.test.ts +1 -1
  29. package/src/api.ts +15 -0
  30. package/src/createMessagesQuery.test.ts +147 -109
  31. package/src/createMessagesQuery.ts +477 -8
  32. package/src/createNodeishFsWithWatcher.test.ts +13 -0
  33. package/src/createNodeishFsWithWatcher.ts +2 -2
  34. package/src/loadProject.ts +20 -666
  35. package/src/persistence/filelock/acquireFileLock.ts +124 -0
  36. package/src/persistence/filelock/releaseLock.ts +28 -0
  37. package/src/v2/index.ts +1 -0
  38. package/src/v2/types.ts +142 -0
@@ -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
+ };