effect-atom-svelte-devtools 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,7 @@ import path from "node:path";
11
11
  import { tsPlugin } from "@sveltejs/acorn-typescript";
12
12
  import { Parser } from "acorn";
13
13
  import MagicString from "magic-string";
14
+ import { parse as parseComponent } from "svelte/compiler";
14
15
  /** The id the transformed code imports `label` from; the plugin resolves it to ./label.ts. */
15
16
  export const labelModule = "virtual:effect-atom-svelte-devtools/label";
16
17
  const labelBinding = "__effectAtomSvelteLabel";
@@ -24,6 +25,19 @@ export const componentName = (file) => path
24
25
  .map((part) => part[0]?.toUpperCase() + part.slice(1))
25
26
  .join("") || "Component";
26
27
  const parser = Parser.extend(tsPlugin());
28
+ // The parser gives every node a type, a start and an end; a type is what tells one from data.
29
+ const isNode = (value) => typeof value === "object" &&
30
+ value !== null &&
31
+ "type" in value &&
32
+ typeof value.type === "string";
33
+ /** The node a field holds, if it holds one. */
34
+ const child = (value) => isNode(value) ? value : undefined;
35
+ /** The nodes a list field holds. */
36
+ const children = (value) => Array.isArray(value) ? value.filter(isNode) : [];
37
+ /** An identifier's name: `todosAtom`. */
38
+ const identifierName = (node) => node?.type === "Identifier" && typeof node.name === "string"
39
+ ? node.name
40
+ : undefined;
27
41
  // Type annotations around the call, as in `Atom.make(0) as Atom.Writable<number>`, are looked
28
42
  // through: only the call is wrapped.
29
43
  const wrappers = new Set([
@@ -33,41 +47,59 @@ const wrappers = new Set([
33
47
  "TSTypeAssertion",
34
48
  "ParenthesizedExpression",
35
49
  ]);
36
- const unwrap = (node) => wrappers.has(node.type) ? unwrap(node.expression) : node;
37
- /** The identifier a callee chain starts from: `Atom` in `Atom.make(...).pipe(...)`. */
38
- const chainStart = (node) => {
50
+ const unwrap = (node) => {
51
+ const inner = wrappers.has(node.type) ? child(node.expression) : undefined;
52
+ return inner === undefined ? node : unwrap(inner);
53
+ };
54
+ /** The node a field holds, with its type annotations looked through. */
55
+ const unwrapped = (value) => {
56
+ const node = child(value);
57
+ return node === undefined ? undefined : unwrap(node);
58
+ };
59
+ /** The next node down a callee chain: a member's object, a call's callee, an annotation's expression. */
60
+ const chainNext = (node) => {
39
61
  if (node.type === "MemberExpression") {
40
- return chainStart(node.object);
62
+ return child(node.object);
41
63
  }
42
64
  if (node.type === "CallExpression") {
43
- return chainStart(node.callee);
65
+ return child(node.callee);
44
66
  }
45
- return wrappers.has(node.type) ? chainStart(node.expression) : node;
67
+ return wrappers.has(node.type) ? child(node.expression) : undefined;
68
+ };
69
+ /** The identifier a callee chain starts from: `Atom` in `Atom.make(...).pipe(...)`. */
70
+ const chainStart = (node) => {
71
+ const next = chainNext(node);
72
+ return next === undefined ? node : chainStart(next);
46
73
  };
47
74
  /**
48
75
  * A call to wrap, or `undefined`. Svelte's runes (`$state(...)`, `$derived.by(...)`) must stay as
49
76
  * they are, and hooks (`useAtomValue(...)`) never return an atom, so both are left be.
50
77
  */
51
78
  const call = (init) => {
52
- if (init === null || init === undefined) {
79
+ const node = unwrapped(init);
80
+ if (node?.type !== "CallExpression") {
53
81
  return undefined;
54
82
  }
55
- const node = unwrap(init);
56
- if (node.type !== "CallExpression") {
57
- return undefined;
58
- }
59
- const start = chainStart(node.callee);
60
- if (start.type === "Identifier" &&
61
- /^(?:\$|use[A-Z])/u.test(String(start.name))) {
83
+ const start = identifierName(chainStart(node));
84
+ if (start !== undefined && /^(?:\$|use[A-Z])/u.test(start)) {
62
85
  return undefined;
63
86
  }
64
87
  return node;
65
88
  };
66
89
  /** Whether the call is `Atom.family(...)` (or a bare `family(...)`), whose members are labelled. */
67
90
  const isFamily = (node) => {
68
- const callee = node.callee;
69
- const property = callee.type === "MemberExpression" ? callee.property : callee;
70
- return property.type === "Identifier" && property.name === "family";
91
+ const callee = child(node.callee);
92
+ const property = callee?.type === "MemberExpression" ? child(callee.property) : callee;
93
+ return identifierName(property) === "family";
94
+ };
95
+ /** The method a member expression takes from `Atom`: `make` in `Atom.make`. */
96
+ const atomMethod = (node) => {
97
+ if (node?.type !== "MemberExpression") {
98
+ return undefined;
99
+ }
100
+ return identifierName(child(node.object)) === "Atom"
101
+ ? identifierName(child(node.property))
102
+ : undefined;
71
103
  };
72
104
  // The arguments `Atom.make` takes as a plain value, rather than a function or an effect.
73
105
  const plainValues = new Set([
@@ -77,49 +109,69 @@ const plainValues = new Set([
77
109
  "ArrayExpression",
78
110
  "UnaryExpression",
79
111
  ]);
112
+ // What a state atom can be piped through and stay one: what is written to it is still what it
113
+ // reads. `Atom.map` and the like write through to their source, so their value can't be written
114
+ // back.
115
+ const stateKeeping = new Set([
116
+ "keepAlive",
117
+ "autoDispose",
118
+ "setIdleTTL",
119
+ "setLazy",
120
+ "withEquality",
121
+ "withLabel",
122
+ "serializable",
123
+ "withServerValue",
124
+ "withServerValueInitial",
125
+ ]);
126
+ /** Whether `Atom.keepAlive`, `Atom.setIdleTTL(...)` or the like: one of `stateKeeping`. */
127
+ const keepsState = (argument) => {
128
+ const node = unwrap(argument);
129
+ const callee = node.type === "CallExpression" ? unwrapped(node.callee) : node;
130
+ return (callee?.computed !== true && stateKeeping.has(atomMethod(callee) ?? ""));
131
+ };
80
132
  /**
81
133
  * Whether the call makes a state atom, such as `Atom.make(0)` or `Atom.make([]).pipe(...)`: one
82
134
  * that holds what is written to it, which a hot reload can carry over.
83
135
  */
84
136
  const isState = (node) => {
85
- const callee = node.callee;
86
- if (callee.type !== "MemberExpression") {
137
+ const callee = child(node.callee);
138
+ if (callee?.type !== "MemberExpression") {
87
139
  return false;
88
140
  }
89
- const object = callee.object;
90
- const property = callee.property;
91
- if (property.type === "Identifier" && property.name === "pipe") {
92
- return object.type === "CallExpression" && isState(object);
141
+ const args = children(node.arguments);
142
+ if (identifierName(child(callee.property)) === "pipe") {
143
+ const object = child(callee.object);
144
+ return (object?.type === "CallExpression" &&
145
+ isState(object) &&
146
+ args.every(keepsState));
93
147
  }
94
- const [argument] = node.arguments;
95
- return (object.type === "Identifier" &&
96
- object.name === "Atom" &&
97
- property.type === "Identifier" &&
98
- property.name === "make" &&
148
+ const [argument] = args;
149
+ return (atomMethod(callee) === "make" &&
99
150
  argument !== undefined &&
100
151
  plainValues.has(unwrap(argument).type));
101
152
  };
102
153
  /** A property's name, when it is written out: `todosAtom` in `{ todosAtom: ... }`. */
103
154
  const propertyName = (property) => {
104
- const key = property.key;
105
- if (property.computed) {
155
+ if (property.computed === true) {
106
156
  return undefined;
107
157
  }
108
- if (key.type === "Identifier") {
109
- return String(key.name);
158
+ const key = child(property.key);
159
+ if (key?.type === "Identifier") {
160
+ return identifierName(key);
110
161
  }
111
- return key.type === "Literal" && typeof key.value === "string"
162
+ return key?.type === "Literal" && typeof key.value === "string"
112
163
  ? key.value
113
164
  : undefined;
114
165
  };
115
166
  /** Every node below `node`, depth first. */
116
167
  const descendants = (node, found = []) => {
117
- for (const value of Object.values(node)) {
118
- const children = Array.isArray(value) ? value : [value];
119
- for (const child of children) {
120
- if (typeof child === "object" && child !== null && "type" in child) {
121
- found.push(child);
122
- descendants(child, found);
168
+ const values = Object.values(node);
169
+ for (const value of values) {
170
+ const below = Array.isArray(value) ? value : [value];
171
+ for (const item of below) {
172
+ if (isNode(item)) {
173
+ found.push(item);
174
+ descendants(item, found);
123
175
  }
124
176
  }
125
177
  }
@@ -148,18 +200,19 @@ const sites = (program, base, defaultName, once) => {
148
200
  });
149
201
  };
150
202
  const members = (object, prefix) => {
151
- for (const property of object.properties) {
152
- const key = property.type === "Property" ? propertyName(property) : undefined;
153
- if (key === undefined) {
203
+ for (const property of children(object.properties)) {
204
+ const key = child(property.key);
205
+ const name = property.type === "Property" ? propertyName(property) : undefined;
206
+ const value = unwrapped(property.value);
207
+ if (key === undefined || name === undefined || value === undefined) {
154
208
  continue;
155
209
  }
156
- const value = unwrap(property.value);
157
210
  const node = call(value);
158
211
  if (node) {
159
- add(node, `${prefix}.${key}`, property.key.start);
212
+ add(node, `${prefix}.${name}`, key.start);
160
213
  }
161
214
  else if (value.type === "ObjectExpression") {
162
- members(value, `${prefix}.${key}`);
215
+ members(value, `${prefix}.${name}`);
163
216
  }
164
217
  }
165
218
  };
@@ -167,25 +220,26 @@ const sites = (program, base, defaultName, once) => {
167
220
  if (declaration.type !== "VariableDeclaration") {
168
221
  return;
169
222
  }
170
- for (const declarator of declaration.declarations) {
223
+ for (const declarator of children(declaration.declarations)) {
171
224
  handled.add(declarator);
172
- const id = declarator.id;
173
- if (id.type !== "Identifier" || !declarator.init) {
225
+ const id = child(declarator.id);
226
+ const name = identifierName(id);
227
+ const init = unwrapped(declarator.init);
228
+ if (id === undefined || name === undefined || init === undefined) {
174
229
  continue;
175
230
  }
176
- const init = unwrap(declarator.init);
177
231
  const node = call(init);
178
232
  if (node) {
179
- add(node, String(id.name), id.start);
233
+ add(node, name, id.start);
180
234
  }
181
235
  else if (init.type === "ObjectExpression") {
182
- members(init, String(id.name));
236
+ members(init, name);
183
237
  }
184
238
  }
185
239
  };
186
- for (const statement of program.body) {
240
+ for (const statement of children(program.body)) {
187
241
  if (statement.type === "ExportNamedDeclaration") {
188
- const { declaration } = statement;
242
+ const declaration = child(statement.declaration);
189
243
  if (declaration) {
190
244
  declare(declaration);
191
245
  }
@@ -204,14 +258,14 @@ const sites = (program, base, defaultName, once) => {
204
258
  if (node.type !== "VariableDeclarator" || handled.has(node)) {
205
259
  continue;
206
260
  }
207
- const id = node.id;
208
- const init = node.init ? call(node.init) : undefined;
209
- const start = init ? chainStart(init.callee) : undefined;
210
- if (id.type === "Identifier" &&
211
- init &&
212
- start?.type === "Identifier" &&
213
- start.name === "Atom") {
214
- add(init, String(id.name), id.start, false);
261
+ const id = child(node.id);
262
+ const name = identifierName(id);
263
+ const init = call(node.init);
264
+ if (id !== undefined &&
265
+ name !== undefined &&
266
+ init !== undefined &&
267
+ identifierName(chainStart(init)) === "Atom") {
268
+ add(init, name, id.start, false);
215
269
  }
216
270
  }
217
271
  return found;
@@ -225,14 +279,14 @@ const factoryName = /^(?!use[A-Z]|is[A-Z])[\w$]+Atom$/u;
225
279
  * as `mapDraftAtom({"doc":1})`, so a cache that makes a new atom for a key it has seen shows it.
226
280
  */
227
281
  const factoryCalls = (program, base) => descendants(program).flatMap((node) => {
228
- const callee = node.type === "CallExpression" ? node.callee : undefined;
229
- return callee?.type === "Identifier" &&
230
- factoryName.test(String(callee.name))
282
+ const callee = node.type === "CallExpression" ? child(node.callee) : undefined;
283
+ const name = identifierName(callee);
284
+ return callee !== undefined && name !== undefined && factoryName.test(name)
231
285
  ? [
232
286
  {
233
287
  calleeEnd: base + callee.end,
234
288
  calleeStart: base + callee.start,
235
- name: String(callee.name),
289
+ name,
236
290
  },
237
291
  ]
238
292
  : [];
@@ -243,19 +297,65 @@ const parse = (code) => parser.parse(code, {
243
297
  });
244
298
  // Svelte's own pattern for finding scripts to preprocess (svelte/src/compiler/preprocess).
245
299
  const scriptPattern = /<!--[^]*?-->|<script(?<attributes>(?:\s+[^=>'"/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"/\s]+)*\s*)(?:\/>|>(?<code>[\S\s]*?)<\/script>)/gu;
300
+ /** Text blanked out, keeping its offsets (an astral character is two UTF-16 units) and lines. */
301
+ const blank = (text) => text.replaceAll(/[^\n]/gu, (character) => " ".repeat(character.length));
302
+ /** The component with each script and style's content blanked out, so only its markup is left. */
303
+ const markupOf = (source, matches) => {
304
+ let markup = source;
305
+ for (const match of matches) {
306
+ const { code } = match.groups ?? {};
307
+ if (code !== undefined) {
308
+ const from = match.index + match[0].length - "</script>".length - code.length;
309
+ markup =
310
+ markup.slice(0, from) + blank(code) + markup.slice(from + code.length);
311
+ }
312
+ }
313
+ return markup.replaceAll(/(?<open><style(?:\s[^>]*)?>)(?<css>[^]*?)<\/style>/gu, (_, open, css) => `${open}${blank(css)}</style>`);
314
+ };
315
+ /**
316
+ * Where the component's own scripts (its instance and module scripts) start, as Svelte's parser
317
+ * sees them: a script nested in the markup (in an element, a block or <svelte:head>) is page HTML.
318
+ * Takes the blanked markup, so a script or style that needs a preprocessor doesn't matter.
319
+ * `undefined` if the markup doesn't parse either.
320
+ */
321
+ const topLevel = (markup) => {
322
+ try {
323
+ const ast = parseComponent(markup, { modern: true });
324
+ // Svelte drops a byte order mark before parsing, so its offsets are one short of the source's.
325
+ const shift = markup.startsWith("\uFEFF") ? 1 : 0;
326
+ return new Set([ast.instance?.start, ast.module?.start]
327
+ .filter((start) => start !== undefined)
328
+ .map((start) => start + shift));
329
+ }
330
+ catch {
331
+ return undefined;
332
+ }
333
+ };
246
334
  /** The scripts of a component: where each one's code starts, the code, and if it is the module script. */
247
335
  const scripts = (source) => {
248
336
  const found = [];
249
- for (const match of source.matchAll(scriptPattern)) {
250
- const [whole] = match;
337
+ const matches = [...source.matchAll(scriptPattern)];
338
+ const markup = markupOf(source, matches);
339
+ const top = topLevel(markup);
340
+ // The fallback when the markup doesn't parse. HTML comments are matched too, and scripts and
341
+ // styles are blanked, so neither kind of comment that mentions <svelte:head> starts a head.
342
+ const heads = [
343
+ ...markup.matchAll(/<!--[^]*?-->|<svelte:head\b[^]*?<\/svelte:head>/gu),
344
+ ]
345
+ .filter((m) => m[0].startsWith("<svelte:head"))
346
+ .map((m) => [m.index, m.index + m[0].length]);
347
+ for (const match of matches) {
251
348
  const { attributes, code } = match.groups ?? {};
252
- if (attributes === undefined || code === undefined) {
349
+ const nested = top
350
+ ? !top.has(match.index)
351
+ : heads.some(([from, to]) => match.index > from && match.index < to);
352
+ if (attributes === undefined || code === undefined || nested) {
253
353
  continue;
254
354
  }
255
355
  found.push({
256
356
  code,
257
357
  module: /\bmodule\b/u.test(attributes),
258
- start: match.index + whole.indexOf(">") + 1,
358
+ start: match.index + "<script".length + attributes.length + 1,
259
359
  });
260
360
  }
261
361
  return found;
@@ -303,12 +403,17 @@ const address = (file, root) => {
303
403
  /** Wraps each labelled declaration's call in `label(...)`, and each factory's callee in `call(...)`. */
304
404
  const wrap = (output, code, found, calls, where) => {
305
405
  for (const site of found) {
306
- const options = {
307
- ...(site.family ? { family: true } : {}),
406
+ const options = {};
407
+ if (site.family) {
408
+ options.family = true;
409
+ }
410
+ if (site.keep) {
308
411
  // The declaration's source, hashed: an edit to it means the old value no longer applies.
309
- ...(site.keep ? { keep: hash(code.slice(site.start, site.end)) } : {}),
310
- ...(site.local ? { local: true } : {}),
311
- };
412
+ options.keep = hash(code.slice(site.start, site.end));
413
+ }
414
+ if (site.local) {
415
+ options.local = true;
416
+ }
312
417
  const args = [
313
418
  JSON.stringify(site.name),
314
419
  JSON.stringify(where(site.at)),
package/dist/vite.js CHANGED
@@ -72,8 +72,10 @@ export const atomLabels = (options = {}) => {
72
72
  catch {
73
73
  // The app can't resolve the library, so there is none of its code to skip.
74
74
  }
75
+ // The plugin that compiles components, among the plugins as Vite runs them: "vite-plugin-svelte"
76
+ // up to version 6, "vite-plugin-svelte:compile" from 7, which runs after every "pre" plugin.
75
77
  const names = config.plugins.map((plugin) => plugin.name);
76
- const svelte = names.findIndex((name) => name.startsWith("vite-plugin-svelte"));
78
+ const svelte = names.findIndex((name) => name === "vite-plugin-svelte" || name === "vite-plugin-svelte:compile");
77
79
  if (svelte !== -1 &&
78
80
  svelte < names.indexOf("effect-atom-svelte-devtools:labels")) {
79
81
  config.logger.warn("effect-atom-svelte-devtools: atomLabels() comes after the Svelte plugin, so atoms declared in components aren't labelled. Put it before sveltekit() or svelte().");
@@ -89,7 +91,7 @@ export const atomLabels = (options = {}) => {
89
91
  if (id.includes("?") ||
90
92
  !filter(id) ||
91
93
  packages.some((directory) => id.startsWith(directory))) {
92
- return undefined;
94
+ return;
93
95
  }
94
96
  return labelAtoms(code, id, root, { keep: serving });
95
97
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-atom-svelte-devtools",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Developer tools for effect-atom-svelte: atom names from your source, and a live view of the registry",
5
5
  "keywords": [
6
6
  "devtools",
@@ -56,19 +56,20 @@
56
56
  "magic-string": "^0.30.21"
57
57
  },
58
58
  "devDependencies": {
59
- "@sveltejs/package": "^3.0.0",
60
- "@sveltejs/vite-plugin-svelte": "^7.2.0",
59
+ "@sveltejs/package": "^3.0.1",
60
+ "@sveltejs/vite-plugin-svelte": "^7.3.1",
61
61
  "@types/node": "^24",
62
- "effect": "4.0.1",
62
+ "effect": "4.0.5",
63
63
  "effect-atom-svelte": "workspace:*",
64
64
  "svelte": "^5.57.2",
65
- "svelte-check": "^4.6.0",
66
- "vite": "^8.3.0",
67
- "vitest": "^5.0.3"
65
+ "svelte-check": "^4.7.6",
66
+ "typescript": "^6.0.3",
67
+ "vite": "^8.3.4",
68
+ "vitest": "^5.0.5"
68
69
  },
69
70
  "peerDependencies": {
70
71
  "effect": "~4.0.0",
71
- "effect-atom-svelte": "^0.2.0",
72
+ "effect-atom-svelte": "^0.4.0",
72
73
  "svelte": "^5.57.2",
73
74
  "vite": ">=5.0.0"
74
75
  },