@tanstack/angular-query 5.0.0-rc.2 → 5.0.0-rc.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/angular-query",
3
- "version": "5.0.0-rc.2",
3
+ "version": "5.0.0-rc.3",
4
4
  "description": "Signals for managing, caching and syncing asynchronous and remote data in Angular",
5
5
  "author": "Arnoud de Vries",
6
6
  "license": "MIT",
@@ -49,6 +49,20 @@
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@angular/common": ">=20.1.0",
52
- "@angular/core": ">=20.1.0"
52
+ "@angular/core": ">=20.1.0",
53
+ "@angular-devkit/schematics": ">=20.1.0",
54
+ "@schematics/angular": ">=20.1.0",
55
+ "typescript": "^5.8.0 || ^6.0.0"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "@angular-devkit/schematics": {
59
+ "optional": true
60
+ },
61
+ "@schematics/angular": {
62
+ "optional": true
63
+ },
64
+ "typescript": {
65
+ "optional": true
66
+ }
53
67
  }
54
68
  }
@@ -5,6 +5,11 @@
5
5
  "description": "Configure TanStack Query in an Angular application.",
6
6
  "factory": "./ng-add/index#ngAdd",
7
7
  "schema": "./ng-add/schema.json"
8
+ },
9
+ "migrate-from-experimental": {
10
+ "description": "Migrate Angular Query experimental imports and unambiguous API calls to the stable package.",
11
+ "factory": "./migrate-from-experimental/index#migrate",
12
+ "schema": "./migrate-from-experimental/schema.json"
8
13
  }
9
14
  }
10
15
  }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MigrationImports = void 0;
7
+ const typescript_1 = __importDefault(require("typescript"));
8
+ /** Reuse visible value imports; add ordinary named imports only when needed. */
9
+ class MigrationImports {
10
+ checker;
11
+ usedNames = new Set();
12
+ additions = [];
13
+ existing = [];
14
+ constructor(source, checker, normalizeModule) {
15
+ this.checker = checker;
16
+ const collectNames = (node) => {
17
+ if (typescript_1.default.isIdentifier(node))
18
+ this.usedNames.add(node.text);
19
+ typescript_1.default.forEachChild(node, collectNames);
20
+ };
21
+ collectNames(source);
22
+ for (const statement of source.statements) {
23
+ if (!typescript_1.default.isImportDeclaration(statement) ||
24
+ !typescript_1.default.isStringLiteral(statement.moduleSpecifier) ||
25
+ statement.importClause?.isTypeOnly)
26
+ continue;
27
+ const bindings = statement.importClause?.namedBindings;
28
+ const module = normalizeModule(statement.moduleSpecifier.text);
29
+ if (bindings && typescript_1.default.isNamespaceImport(bindings)) {
30
+ this.existing.push({ local: bindings.name, module });
31
+ }
32
+ else if (bindings) {
33
+ for (const element of bindings.elements) {
34
+ if (!element.isTypeOnly)
35
+ this.existing.push({
36
+ name: (element.propertyName ?? element.name).text,
37
+ local: element.name,
38
+ module,
39
+ });
40
+ }
41
+ }
42
+ }
43
+ }
44
+ reference(name, module, location) {
45
+ for (const imported of this.existing) {
46
+ if (imported.module !== module ||
47
+ (imported.name && imported.name !== name))
48
+ continue;
49
+ const visible = this.checker.resolveName(imported.local.text, location, typescript_1.default.SymbolFlags.Value | typescript_1.default.SymbolFlags.Alias, false);
50
+ if (visible === this.checker.getSymbolAtLocation(imported.local)) {
51
+ return imported.name
52
+ ? imported.local.text
53
+ : `${imported.local.text}.${name}`;
54
+ }
55
+ }
56
+ const added = this.additions.find((entry) => entry.name === name && entry.module === module);
57
+ if (added)
58
+ return added.local;
59
+ // Check all scopes so the new import cannot be shadowed at another call site.
60
+ let local = name;
61
+ if (this.usedNames.has(local)) {
62
+ const base = name === 'inject' ? 'angularInject' : 'TanStackQueryClient';
63
+ local = base;
64
+ let suffix = 2;
65
+ while (this.usedNames.has(local))
66
+ local = `${base}${suffix++}`;
67
+ }
68
+ this.usedNames.add(local);
69
+ this.additions.push({ name, local, module });
70
+ return local;
71
+ }
72
+ render() {
73
+ return this.additions
74
+ .map(({ name, local, module }) => `import { ${name === local ? name : `${name} as ${local}`} } from '${module}';\n`)
75
+ .join('');
76
+ }
77
+ }
78
+ exports.MigrationImports = MigrationImports;
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.migrate = migrate;
4
+ const dependencies_1 = require("@schematics/angular/utility/dependencies");
5
+ const tasks_1 = require("@angular-devkit/schematics/tasks");
6
+ const source_1 = require("./source");
7
+ const workspace_1 = require("./workspace");
8
+ const PACKAGE_NAME = '@tanstack/angular-query';
9
+ const PACKAGE_VERSION = '5.0.0-rc.3';
10
+ const DEVTOOLS_PACKAGE_NAME = '@tanstack/angular-query-devtools';
11
+ const DEVTOOLS_PACKAGE_VERSION = '5.0.0-rc.3';
12
+ const MIGRATION_GUIDE = 'https://tanstack.com/query/latest/docs/framework/angular/guides/migrating-from-experimental';
13
+ const dependencyTypes = [
14
+ dependencies_1.NodeDependencyType.Default,
15
+ dependencies_1.NodeDependencyType.Dev,
16
+ dependencies_1.NodeDependencyType.Optional,
17
+ dependencies_1.NodeDependencyType.Peer,
18
+ ];
19
+ // TODO: Ideally remove migrate-from-experimental one year after Angular Query's
20
+ // first stable release, along with its collection entry, tests, and packaging references.
21
+ /** Migrates syntactically unambiguous uses; reports cases requiring human review. */
22
+ function migrate(options) {
23
+ return async (tree, context) => {
24
+ const workspace = await (0, workspace_1.migrationWorkspace)(tree);
25
+ const devtoolsManifests = new Set();
26
+ let changedFiles = 0;
27
+ let reviewItems = 0;
28
+ const report = (message) => {
29
+ reviewItems++;
30
+ context.logger.warn(message);
31
+ };
32
+ for (const path of workspace.files) {
33
+ const text = tree.readText(path);
34
+ if (!text.includes(source_1.OLD_PACKAGE) &&
35
+ !text.includes(PACKAGE_NAME) &&
36
+ !(options.migrateQueryCoreImports && text.includes(source_1.CORE_PACKAGE)))
37
+ continue;
38
+ const result = (0, source_1.migrateSource)(text, path, PACKAGE_NAME, DEVTOOLS_PACKAGE_NAME, report, options);
39
+ if (result.needsDevtools) {
40
+ const manifest = (0, workspace_1.sourceManifest)(path, workspace.manifests);
41
+ if (manifest)
42
+ devtoolsManifests.add(manifest);
43
+ else
44
+ report(`${path}: Add ${DEVTOOLS_PACKAGE_NAME} to the package manifest manually.`);
45
+ }
46
+ if (result.text !== text) {
47
+ tree.overwrite(path, result.text);
48
+ changedFiles++;
49
+ }
50
+ }
51
+ const remainingCoreReferences = new Map();
52
+ if (options.migrateQueryCoreImports)
53
+ for (const path of (0, workspace_1.packageReferenceFiles)(tree, source_1.CORE_PACKAGE)) {
54
+ for (const manifest of workspace.manifests)
55
+ if ((0, workspace_1.sourceManifest)(path, [manifest]))
56
+ remainingCoreReferences.set(manifest, path);
57
+ }
58
+ let packageChanges = 0;
59
+ for (const manifest of workspace.manifests)
60
+ packageChanges += migrateDependencies(tree, manifest, devtoolsManifests.has(manifest), report, options.migrateQueryCoreImports ?? false, remainingCoreReferences.get(manifest));
61
+ if (packageChanges && !options.skipInstall)
62
+ context.addTask(new tasks_1.NodePackageInstallTask());
63
+ context.logger.info(`Angular Query migration prepared: ${changedFiles} source file(s) changed, ${packageChanges} dependency change(s), ${reviewItems} item(s) requiring manual review.`);
64
+ if (packageChanges)
65
+ context.logger.info(options.skipInstall
66
+ ? 'Dependency installation was skipped. Run your package manager install command after applying the migration.'
67
+ : 'Dependency installation is scheduled after the migration is applied.');
68
+ context.logger.info('Address the warnings, then run your application build, tests, linting, and formatting checks. Review SSR hydration, error handling, persistence factories, and tests waiting for stability. Angular >=20.1 is required.');
69
+ context.logger.info(`Migration guide: ${MIGRATION_GUIDE}`);
70
+ return tree;
71
+ };
72
+ }
73
+ function migrateDependencies(tree, manifest, needsDevtools, report, migrateCore, remainingCoreReference) {
74
+ const pkg = tree.readJson(manifest);
75
+ let changes = 0;
76
+ for (const type of dependencyTypes) {
77
+ const dependencies = pkg[type];
78
+ if (!dependencies)
79
+ continue;
80
+ const experimental = dependencies[source_1.OLD_PACKAGE];
81
+ const core = migrateCore && dependencies[source_1.CORE_PACKAGE];
82
+ if (!experimental && !core)
83
+ continue;
84
+ if (experimental)
85
+ changes++;
86
+ if (core && !remainingCoreReference)
87
+ changes++;
88
+ if (!dependencies[PACKAGE_NAME]) {
89
+ (0, dependencies_1.addPackageJsonDependency)(tree, {
90
+ type,
91
+ name: PACKAGE_NAME,
92
+ version: `^${PACKAGE_VERSION}`,
93
+ overwrite: false,
94
+ }, manifest);
95
+ changes++;
96
+ }
97
+ }
98
+ if (dependencyTypes.some((type) => pkg[type]?.[source_1.OLD_PACKAGE]))
99
+ (0, dependencies_1.removePackageJsonDependency)(tree, source_1.OLD_PACKAGE, manifest);
100
+ const hasCoreDependency = dependencyTypes.some((type) => pkg[type]?.[source_1.CORE_PACKAGE]);
101
+ if (migrateCore && hasCoreDependency) {
102
+ if (remainingCoreReference)
103
+ report(`${manifest}: Keeping ${source_1.CORE_PACKAGE} because ${remainingCoreReference} still references it. Migrate remaining imports or references manually before removing the dependency.`);
104
+ else
105
+ (0, dependencies_1.removePackageJsonDependency)(tree, source_1.CORE_PACKAGE, manifest);
106
+ }
107
+ const current = tree.readJson(manifest);
108
+ if (needsDevtools &&
109
+ !dependencyTypes.some((type) => pkg[type]?.[DEVTOOLS_PACKAGE_NAME])) {
110
+ const type = current.peerDependencies?.[PACKAGE_NAME]
111
+ ? dependencies_1.NodeDependencyType.Peer
112
+ : dependencies_1.NodeDependencyType.Default;
113
+ (0, dependencies_1.addPackageJsonDependency)(tree, {
114
+ type,
115
+ name: DEVTOOLS_PACKAGE_NAME,
116
+ version: `^${DEVTOOLS_PACKAGE_VERSION}`,
117
+ overwrite: false,
118
+ }, manifest);
119
+ changes++;
120
+ }
121
+ const metadata = tree.readJson(manifest);
122
+ for (const name of [
123
+ source_1.OLD_PACKAGE,
124
+ ...(migrateCore && !remainingCoreReference ? [source_1.CORE_PACKAGE] : []),
125
+ ])
126
+ if (metadata.peerDependenciesMeta?.[name])
127
+ report(`${manifest}: Rename peerDependenciesMeta["${name}"] to "${PACKAGE_NAME}" and review the optional peer configuration.`);
128
+ return changes;
129
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,23 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema",
3
+ "title": "Migrate experimental Angular Query",
4
+ "type": "object",
5
+ "properties": {
6
+ "unsafeWrapClientReferences": {
7
+ "type": "boolean",
8
+ "default": false,
9
+ "description": "Unsafe: wrap client references in factories. References may be injection tokens or existing factories; review every conversion."
10
+ },
11
+ "migrateQueryCoreImports": {
12
+ "type": "boolean",
13
+ "default": false,
14
+ "description": "Replace @tanstack/query-core imports with @tanstack/angular-query and remove direct core dependencies when no references remain."
15
+ },
16
+ "skipInstall": {
17
+ "type": "boolean",
18
+ "default": false,
19
+ "description": "Skip installing changed package dependencies."
20
+ }
21
+ },
22
+ "additionalProperties": false
23
+ }
@@ -0,0 +1,417 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CORE_PACKAGE = exports.OLD_PACKAGE = void 0;
7
+ exports.migrateSource = migrateSource;
8
+ const typescript_1 = __importDefault(require("typescript"));
9
+ const imports_1 = require("./imports");
10
+ exports.OLD_PACKAGE = '@tanstack/angular-query-experimental';
11
+ exports.CORE_PACKAGE = '@tanstack/query-core';
12
+ // The experimental helpers used two different injector argument shapes.
13
+ const injectorArguments = {
14
+ injectQueries: { index: 1, kind: 'injector' },
15
+ injectQuery: { index: 1, kind: 'options' },
16
+ injectInfiniteQuery: { index: 1, kind: 'options' },
17
+ injectMutation: { index: 1, kind: 'options' },
18
+ injectMutationState: { index: 1, kind: 'options' },
19
+ injectIsFetching: { index: 1, kind: 'options' },
20
+ injectIsMutating: { index: 1, kind: 'options' },
21
+ injectIsRestoring: { index: 0, kind: 'options' },
22
+ injectDevtoolsPanel: { index: 1, kind: 'options' },
23
+ };
24
+ const removedInjectorOptions = new Set([
25
+ 'InjectQueryOptions',
26
+ 'InjectInfiniteQueryOptions',
27
+ 'InjectMutationOptions',
28
+ 'InjectMutationStateOptions',
29
+ 'InjectIsFetchingOptions',
30
+ 'InjectIsMutatingOptions',
31
+ 'InjectDevtoolsPanelOptions',
32
+ ]);
33
+ const removedApis = {
34
+ provideIsRestoring: 'Restoration is managed by withPersistQueryClient. Review custom restoration providers.',
35
+ queryFeature: 'Custom feature construction is no longer public. Use the supported with* features.',
36
+ QueryFeatures: 'Use the non-generic QueryFeature type.',
37
+ DevtoolsFeature: 'Use the non-generic QueryFeature type.',
38
+ PersistQueryClientFeature: 'Use the non-generic QueryFeature type.',
39
+ CreateBaseQueryOptions: 'Use CreateQueryOptions and review typed wrappers.',
40
+ };
41
+ /** Source edits preserve untouched formatting; symbols protect shadowed local names. */
42
+ function migrateSource(text, path, packageName, devtoolsPackageName, report, options = {}) {
43
+ const result = { needsDevtools: false };
44
+ const source = typescript_1.default.createSourceFile(path, text, typescript_1.default.ScriptTarget.Latest, true);
45
+ // Binding symbols distinguish imports from identically named local parameters.
46
+ const host = typescript_1.default.createCompilerHost({ noLib: true });
47
+ host.getSourceFile = (name) => (name === path ? source : undefined);
48
+ const checker = typescript_1.default
49
+ .createProgram([path], { noLib: true, noResolve: true }, host)
50
+ .getTypeChecker();
51
+ const bindings = new Map();
52
+ const namespaces = new Set();
53
+ const edits = [];
54
+ const replace = (node, value) => {
55
+ const start = node.getStart(source);
56
+ // A whole-import removal supersedes its earlier module-specifier edit.
57
+ for (let index = edits.length - 1; index >= 0; index--) {
58
+ if (edits[index].start >= start && edits[index].end <= node.end)
59
+ edits.splice(index, 1);
60
+ }
61
+ edits.push({ start, end: node.end, text: value });
62
+ };
63
+ const warn = (node, message) => report(`${path}:${source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1}: ${message}`);
64
+ const renames = {
65
+ provideAngularQuery: 'provideTanStackQuery',
66
+ provideQueryClient: 'provideTanStackQuery',
67
+ };
68
+ const imports = new imports_1.MigrationImports(source, checker, (module) => module === exports.OLD_PACKAGE ||
69
+ module === `${exports.OLD_PACKAGE}/inject-queries-experimental` ||
70
+ (options.migrateQueryCoreImports && module === exports.CORE_PACKAGE)
71
+ ? packageName
72
+ : module);
73
+ function migrateImports() {
74
+ for (const statement of source.statements) {
75
+ if ((!typescript_1.default.isImportDeclaration(statement) &&
76
+ !typescript_1.default.isExportDeclaration(statement)) ||
77
+ !statement.moduleSpecifier ||
78
+ !typescript_1.default.isStringLiteral(statement.moduleSpecifier))
79
+ continue;
80
+ const module = statement.moduleSpecifier.text;
81
+ const isCore = options.migrateQueryCoreImports && module === exports.CORE_PACKAGE;
82
+ const targets = {
83
+ [exports.OLD_PACKAGE]: packageName,
84
+ [`${exports.OLD_PACKAGE}/inject-queries-experimental`]: packageName,
85
+ [`${exports.OLD_PACKAGE}/devtools`]: devtoolsPackageName,
86
+ [`${exports.OLD_PACKAGE}/devtools/production`]: `${devtoolsPackageName}/production`,
87
+ [`${exports.OLD_PACKAGE}/devtools-panel`]: `${devtoolsPackageName}/devtools-panel`,
88
+ [`${exports.OLD_PACKAGE}/devtools-panel/production`]: `${devtoolsPackageName}/devtools-panel/production`,
89
+ };
90
+ if (isCore)
91
+ targets[exports.CORE_PACKAGE] = packageName;
92
+ const target = targets[module];
93
+ const isDevtools = target?.startsWith(devtoolsPackageName) ||
94
+ module === devtoolsPackageName ||
95
+ module.startsWith(`${devtoolsPackageName}/`);
96
+ if (isDevtools)
97
+ result.needsDevtools = true;
98
+ if (target)
99
+ replace(statement.moduleSpecifier, JSON.stringify(target));
100
+ else if (module.startsWith(`${exports.OLD_PACKAGE}/`))
101
+ warn(statement, 'Unrecognized experimental entrypoint. Update this package reference manually.');
102
+ if (module !== exports.OLD_PACKAGE &&
103
+ module !== packageName &&
104
+ module !== `${exports.OLD_PACKAGE}/inject-queries-experimental` &&
105
+ !isCore &&
106
+ !isDevtools)
107
+ continue;
108
+ if (typescript_1.default.isExportDeclaration(statement)) {
109
+ warn(statement, 'Review re-exported APIs and migrate their consumers manually.');
110
+ if (statement.exportClause &&
111
+ typescript_1.default.isNamedExports(statement.exportClause)) {
112
+ for (const element of statement.exportClause.elements)
113
+ warnRemovedApi(element, (element.propertyName ?? element.name).text);
114
+ }
115
+ continue;
116
+ }
117
+ const named = statement.importClause?.namedBindings;
118
+ if (!named)
119
+ continue;
120
+ if (typescript_1.default.isNamespaceImport(named)) {
121
+ const symbol = checker.getSymbolAtLocation(named.name);
122
+ if (symbol)
123
+ namespaces.add(symbol);
124
+ }
125
+ else {
126
+ const specifiers = [];
127
+ for (const element of named.elements) {
128
+ const name = (element.propertyName ?? element.name).text;
129
+ const symbol = checker.getSymbolAtLocation(element.name);
130
+ if (symbol)
131
+ bindings.set(symbol, name);
132
+ warnRemovedApi(element, name);
133
+ const removable = name === 'injectQueryClient' && canRemoveHelperImport(element);
134
+ if (!removable)
135
+ specifiers.push(!isDevtools && renames[name]
136
+ ? `${element.isTypeOnly ? 'type ' : ''}${renames[name]} as ${element.name.text}`
137
+ : element.getText(source));
138
+ if (name === 'injectQueryClient' && !removable)
139
+ warn(element, 'Review non-call references or arguments to removed injectQueryClient; its import requires manual removal.');
140
+ }
141
+ if (specifiers.join(', ') !==
142
+ named.elements.map((element) => element.getText(source)).join(', ')) {
143
+ if (specifiers.length === 0 && !statement.importClause.name)
144
+ replace(statement, '');
145
+ else
146
+ replace(named, `{ ${specifiers.join(', ')} }`);
147
+ }
148
+ }
149
+ }
150
+ }
151
+ function warnRemovedApi(node, name) {
152
+ if (removedInjectorOptions.has(name))
153
+ warn(node, `${name} was removed. Review typed wrappers and move injector handling to runInInjectionContext.`);
154
+ else if (removedApis[name])
155
+ warn(node, `${name} was removed. ${removedApis[name]}`);
156
+ }
157
+ function canRemoveHelperImport(element) {
158
+ const symbol = checker.getSymbolAtLocation(element.name);
159
+ if (!symbol)
160
+ return false;
161
+ function hasUnsupportedReference(node) {
162
+ if (typescript_1.default.isIdentifier(node) &&
163
+ checker.getSymbolAtLocation(node) === symbol &&
164
+ node !== element.name &&
165
+ node !== element.propertyName) {
166
+ return (!typescript_1.default.isCallExpression(node.parent) ||
167
+ node.parent.expression !== node ||
168
+ node.parent.arguments.length !== 0);
169
+ }
170
+ return typescript_1.default.forEachChild(node, hasUnsupportedReference) ?? false;
171
+ }
172
+ return !hasUnsupportedReference(source);
173
+ }
174
+ const apiName = (expression) => {
175
+ if (typescript_1.default.isIdentifier(expression)) {
176
+ const symbol = checker.getSymbolAtLocation(expression);
177
+ return symbol && bindings.get(symbol);
178
+ }
179
+ if (typescript_1.default.isPropertyAccessExpression(expression)) {
180
+ const symbol = checker.getSymbolAtLocation(expression.expression);
181
+ if (symbol && namespaces.has(symbol))
182
+ return expression.name.text;
183
+ }
184
+ if (typescript_1.default.isQualifiedName(expression)) {
185
+ const symbol = checker.getSymbolAtLocation(expression.left);
186
+ if (symbol && namespaces.has(symbol))
187
+ return expression.right.text;
188
+ }
189
+ return undefined;
190
+ };
191
+ function migrateCall(node) {
192
+ const name = apiName(node.expression);
193
+ if (name)
194
+ warnAboutInjectorArgument(node, name);
195
+ switch (name) {
196
+ case 'provideTanStackQuery':
197
+ case 'provideAngularQuery':
198
+ case 'provideQueryClient':
199
+ migrateProvider(node);
200
+ break;
201
+ case 'injectQueryClient':
202
+ migrateClientInjection(node);
203
+ break;
204
+ case 'injectIsFetching':
205
+ case 'injectIsMutating':
206
+ migrateActivityFilter(node);
207
+ break;
208
+ }
209
+ if (name &&
210
+ [
211
+ 'injectQuery',
212
+ 'injectInfiniteQuery',
213
+ 'injectMutation',
214
+ 'queryOptions',
215
+ 'infiniteQueryOptions',
216
+ 'mutationOptions',
217
+ ].includes(name))
218
+ warnAboutObserverOptions(node.arguments[0]);
219
+ if (name === 'withDevtools') {
220
+ warnAboutOption(node.arguments[1], 'deps', 'withDevtools no longer accepts deps. Call inject() inside the devtools options callback and remove deps.');
221
+ }
222
+ }
223
+ function warnAboutInjectorArgument(node, name) {
224
+ const argument = injectorArguments[name];
225
+ if (!argument)
226
+ return;
227
+ if (node.arguments.some(typescript_1.default.isSpreadElement)) {
228
+ warn(node, `Review spread arguments to ${name}; the stable helper no longer accepts an injector argument or injector options.`);
229
+ return;
230
+ }
231
+ if (node.arguments.length <= argument.index)
232
+ return;
233
+ const guidance = argument.kind === 'injector'
234
+ ? 'Pass the old injector argument to runInInjectionContext'
235
+ : 'Pass the old options.injector to runInInjectionContext (not the options object itself)';
236
+ warn(node, `${name} no longer accepts ${argument.kind === 'injector' ? 'an injector argument' : 'injector options'}. ${guidance}, call ${name} inside its callback, and remove the old argument. If it is undefined or contains no injector, remove it and ensure the call is in an injection context.`);
237
+ }
238
+ function migrateProvider(node) {
239
+ const first = node.arguments[0];
240
+ const expression = first && unwrap(first);
241
+ if (first &&
242
+ expression &&
243
+ typescript_1.default.isNewExpression(expression) &&
244
+ apiName(expression.expression) === 'QueryClient') {
245
+ edits.push({
246
+ start: first.getStart(source),
247
+ end: first.getStart(source),
248
+ text: '() => ',
249
+ });
250
+ }
251
+ else if (first &&
252
+ expression &&
253
+ !typescript_1.default.isArrowFunction(expression) &&
254
+ !typescript_1.default.isFunctionExpression(expression)) {
255
+ if (options.unsafeWrapClientReferences &&
256
+ (typescript_1.default.isIdentifier(expression) ||
257
+ typescript_1.default.isPropertyAccessExpression(expression) ||
258
+ typescript_1.default.isElementAccessExpression(expression))) {
259
+ edits.push({
260
+ start: first.getStart(source),
261
+ end: first.getStart(source),
262
+ text: '() => ',
263
+ });
264
+ warn(first, 'Unsafe conversion: wrapped this client reference in a factory. Verify it returns a QueryClient; existing factories must not be wrapped, and injection tokens need () => inject(token).');
265
+ }
266
+ else
267
+ warn(first, 'Client reference may be an instance, token, or factory; provide a client factory manually. Use --unsafe-wrap-client-references only after checking the argument is a QueryClient instance.');
268
+ }
269
+ if (typescript_1.default.isSpreadElement(node.parent))
270
+ edits.push({
271
+ start: node.parent.getStart(source),
272
+ end: node.getStart(source),
273
+ text: '',
274
+ });
275
+ warn(node, 'Verify this provider is in an environment injector; review default SSR hydration and PendingTasks behavior.');
276
+ }
277
+ function unwrap(node) {
278
+ return typescript_1.default.isParenthesizedExpression(node) ||
279
+ typescript_1.default.isAsExpression(node) ||
280
+ typescript_1.default.isSatisfiesExpression(node) ||
281
+ typescript_1.default.isNonNullExpression(node)
282
+ ? unwrap(node.expression)
283
+ : node;
284
+ }
285
+ function property(node, name) {
286
+ if (!node)
287
+ return undefined;
288
+ node = unwrap(node);
289
+ if (!typescript_1.default.isObjectLiteralExpression(node))
290
+ return undefined;
291
+ return node.properties.find((entry) => (typescript_1.default.isPropertyAssignment(entry) ||
292
+ typescript_1.default.isShorthandPropertyAssignment(entry)) &&
293
+ (typescript_1.default.isIdentifier(entry.name) || typescript_1.default.isStringLiteral(entry.name)) &&
294
+ entry.name.text === name);
295
+ }
296
+ function propertyValue(node, name) {
297
+ const entry = property(node, name);
298
+ return (entry && (typescript_1.default.isPropertyAssignment(entry) ? entry.initializer : entry.name));
299
+ }
300
+ function warnAboutOption(node, name, message) {
301
+ const entry = property(node, name);
302
+ if (entry)
303
+ warn(entry, message);
304
+ }
305
+ function warnAboutObserverOptions(node) {
306
+ if (!node)
307
+ return;
308
+ node = unwrap(node);
309
+ if (typescript_1.default.isArrowFunction(node) || typescript_1.default.isFunctionExpression(node)) {
310
+ if (typescript_1.default.isBlock(node.body)) {
311
+ const returns = (child) => {
312
+ if (typescript_1.default.isReturnStatement(child))
313
+ warnAboutObserverOptions(child.expression);
314
+ else if (!typescript_1.default.isFunctionLike(child))
315
+ typescript_1.default.forEachChild(child, returns);
316
+ };
317
+ typescript_1.default.forEachChild(node.body, returns);
318
+ }
319
+ else
320
+ warnAboutObserverOptions(node.body);
321
+ }
322
+ else if (typescript_1.default.isConditionalExpression(node)) {
323
+ warnAboutObserverOptions(node.whenTrue);
324
+ warnAboutObserverOptions(node.whenFalse);
325
+ }
326
+ else
327
+ warnAboutOption(node, 'throwOnError', 'Observer throwOnError was removed. Read the error signal or configure an ErrorHandler through cache callbacks. Imperative refetch throwOnError remains supported.');
328
+ }
329
+ function warnAboutIndirectReference(node, name) {
330
+ if (typescript_1.default.isCallExpression(node.parent) && node.parent.expression === node)
331
+ return;
332
+ if (name === 'injectQueryClient')
333
+ warn(node, 'injectQueryClient was removed. Replace this indirect reference with a function that calls inject(QueryClient), and review its consumers.');
334
+ else if (name === 'provideTanStackQuery' || renames[name])
335
+ warn(node, 'Review consumers of this provider reference: provideTanStackQuery expects a QueryClient factory and returns one EnvironmentProviders value.');
336
+ else if (injectorArguments[name])
337
+ warn(node, `Review consumers of this ${name} reference for removed injector arguments${name === 'injectIsFetching' || name === 'injectIsMutating' ? ' and callback-based filters' : ''}.`);
338
+ }
339
+ function migrateClientInjection(node) {
340
+ if (node.arguments.length !== 0) {
341
+ warn(node, 'Migrate injectQueryClient arguments manually using Angular inject or runInInjectionContext.');
342
+ return;
343
+ }
344
+ const inject = imports.reference('inject', '@angular/core', node);
345
+ const client = imports.reference('QueryClient', packageName, node);
346
+ replace(node, `${inject}(${client})`);
347
+ }
348
+ function migrateActivityFilter(node) {
349
+ const first = node.arguments[0];
350
+ if (!first)
351
+ return;
352
+ if (typescript_1.default.isObjectLiteralExpression(first)) {
353
+ edits.push({
354
+ start: first.getStart(source),
355
+ end: first.getStart(source),
356
+ text: '() => (',
357
+ }, { start: first.end, end: first.end, text: ')' });
358
+ }
359
+ else if (!typescript_1.default.isArrowFunction(first) && !typescript_1.default.isFunctionExpression(first))
360
+ warn(first, 'Review activity filter: the stable API expects a callback.');
361
+ }
362
+ function visit(node) {
363
+ if (typescript_1.default.isStringLiteral(node) &&
364
+ (node.text.startsWith(exports.OLD_PACKAGE) ||
365
+ (options.migrateQueryCoreImports &&
366
+ node.text.startsWith(exports.CORE_PACKAGE))) &&
367
+ !typescript_1.default.isImportDeclaration(node.parent) &&
368
+ !typescript_1.default.isExportDeclaration(node.parent)) {
369
+ warn(node, 'Review this package reference manually (for example, a dynamic import or require).');
370
+ }
371
+ if (typescript_1.default.isCallExpression(node))
372
+ migrateCall(node);
373
+ if (typescript_1.default.isPropertyAccessExpression(node) || typescript_1.default.isQualifiedName(node)) {
374
+ const name = apiName(node);
375
+ if (name) {
376
+ warnRemovedApi(node, name);
377
+ if (typescript_1.default.isPropertyAccessExpression(node)) {
378
+ if (renames[name])
379
+ replace(node.name, renames[name]);
380
+ warnAboutIndirectReference(node, name);
381
+ }
382
+ }
383
+ }
384
+ if (typescript_1.default.isIdentifier(node) &&
385
+ !typescript_1.default.isImportSpecifier(node.parent) &&
386
+ !typescript_1.default.isPropertyAccessExpression(node.parent) &&
387
+ !typescript_1.default.isQualifiedName(node.parent) &&
388
+ !typescript_1.default.isTypeReferenceNode(node.parent)) {
389
+ const name = apiName(node);
390
+ if (name)
391
+ warnAboutIndirectReference(node, name);
392
+ }
393
+ if (typescript_1.default.isTypeReferenceNode(node) &&
394
+ apiName(node.typeName) === 'QueryFeature' &&
395
+ node.typeArguments?.length)
396
+ warn(node, 'QueryFeature is no longer generic. Remove its type arguments and use features returned by the supported with* functions.');
397
+ if (typescript_1.default.isNewExpression(node) &&
398
+ apiName(node.expression) === 'QueryClient') {
399
+ const defaults = propertyValue(node.arguments?.[0], 'defaultOptions');
400
+ warnAboutObserverOptions(propertyValue(defaults, 'queries'));
401
+ warnAboutObserverOptions(propertyValue(defaults, 'mutations'));
402
+ }
403
+ typescript_1.default.forEachChild(node, visit);
404
+ }
405
+ migrateImports();
406
+ visit(source);
407
+ const newImports = imports.render();
408
+ if (newImports) {
409
+ // Insert after existing statements' leading comments (and a possible shebang).
410
+ const position = source.statements[0]?.getStart(source) ?? text.length;
411
+ edits.push({ start: position, end: position, text: newImports });
412
+ }
413
+ let output = text;
414
+ for (const edit of edits.sort((a, b) => b.start - a.start || b.end - a.end))
415
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
416
+ return { text: output, needsDevtools: result.needsDevtools };
417
+ }
@@ -0,0 +1,202 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.packageReferenceFiles = packageReferenceFiles;
7
+ exports.migrationWorkspace = migrationWorkspace;
8
+ exports.sourceManifest = sourceManifest;
9
+ const node_path_1 = require("node:path");
10
+ const workspace_1 = require("@schematics/angular/utility/workspace");
11
+ const schematics_1 = require("@angular-devkit/schematics");
12
+ const typescript_1 = __importDefault(require("typescript"));
13
+ // cspell:ignore subdirs
14
+ const ignoredDirectories = new Set([
15
+ 'node_modules',
16
+ 'dist',
17
+ 'build',
18
+ '.git',
19
+ '.angular',
20
+ '.nx',
21
+ '.cache',
22
+ 'coverage',
23
+ ]);
24
+ function isSource(path) {
25
+ return /\.[cm]?tsx?$/.test(path) && !/\.d\.[cm]?ts$/.test(path);
26
+ }
27
+ /** Visit files without descending into dependencies or generated output. */
28
+ function filesUnder(tree, root) {
29
+ const files = [];
30
+ const visit = (path) => {
31
+ const directory = tree.getDir(path);
32
+ for (const name of directory.subfiles) {
33
+ const file = node_path_1.posix.join(path, name);
34
+ files.push(file);
35
+ }
36
+ for (const name of directory.subdirs) {
37
+ if (!ignoredDirectories.has(name))
38
+ visit(node_path_1.posix.join(path, name));
39
+ }
40
+ };
41
+ visit(root);
42
+ return files;
43
+ }
44
+ function sourcesUnder(tree, root) {
45
+ return filesUnder(tree, root).filter(isSource);
46
+ }
47
+ /** Include declarations, JavaScript, and component files when checking dependency references. */
48
+ function packageReferenceFiles(tree, packageName) {
49
+ return filesUnder(tree, '/').filter((path) => {
50
+ const isComponent = /\.(vue|svelte|astro)$/.test(path);
51
+ if (!isComponent && !/\.[cm]?[jt]sx?$/.test(path))
52
+ return false;
53
+ const text = tree.readText(path);
54
+ if (!text.includes(packageName))
55
+ return false;
56
+ if (isComponent)
57
+ return true;
58
+ const containsReference = (node) => {
59
+ if (typescript_1.default.isStringLiteralLike(node) || typescript_1.default.isTemplateHead(node))
60
+ return (node.text === packageName || node.text.startsWith(`${packageName}/`));
61
+ return typescript_1.default.forEachChild(node, containsReference) ?? false;
62
+ };
63
+ return containsReference(typescript_1.default.createSourceFile(path, text, typescript_1.default.ScriptTarget.Latest, true));
64
+ });
65
+ }
66
+ /** TypeScript config patterns support *, ? and **; a bare directory includes its descendants. */
67
+ function configPattern(root, pattern) {
68
+ let path = node_path_1.posix.resolve(root, pattern);
69
+ if (!/[?*]/.test(path) && !node_path_1.posix.extname(path))
70
+ path += '/**/*';
71
+ const segments = path.split('/');
72
+ const expression = segments
73
+ .map((segment, index) => {
74
+ if (segment === '**')
75
+ return index === segments.length - 1 ? '.*' : '(?:[^/]+/)*';
76
+ const value = segment
77
+ .split('')
78
+ .map((character) => {
79
+ if (character === '*')
80
+ return '[^/]*';
81
+ if (character === '?')
82
+ return '[^/]';
83
+ return character.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
84
+ })
85
+ .join('');
86
+ return value + (index < segments.length - 1 ? '/' : '');
87
+ })
88
+ .join('');
89
+ return new RegExp(`^${expression}$`);
90
+ }
91
+ function configuredSources(tree, configPath) {
92
+ const readFile = (path) => tree.exists(path) ? tree.readText(path) : undefined;
93
+ const config = typescript_1.default.getParsedCommandLineOfConfigFile(configPath, { noLib: true }, {
94
+ useCaseSensitiveFileNames: true,
95
+ getCurrentDirectory: () => '/',
96
+ fileExists: (path) => tree.exists(path),
97
+ readFile,
98
+ readDirectory: (root, extensions, excludes, includes) => {
99
+ const patterns = includes;
100
+ const roots = new Set([root]);
101
+ for (const pattern of patterns) {
102
+ const prefix = node_path_1.posix.resolve(root, pattern).split(/[?*]/)[0];
103
+ roots.add(prefix.endsWith('/') ? prefix : node_path_1.posix.dirname(prefix));
104
+ }
105
+ const candidates = new Set([...roots].flatMap((path) => sourcesUnder(tree, path)));
106
+ return [...candidates].filter((path) => extensions.some((extension) => path.endsWith(extension)) &&
107
+ patterns.some((pattern) => configPattern(root, pattern).test(path)) &&
108
+ !(excludes ?? []).some((pattern) => configPattern(root, pattern).test(path)));
109
+ },
110
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
111
+ throw new schematics_1.SchematicsException(typescript_1.default.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));
112
+ },
113
+ });
114
+ if (!config)
115
+ return [];
116
+ const host = typescript_1.default.createCompilerHost(config.options);
117
+ host.getCurrentDirectory = () => '/';
118
+ host.fileExists = (path) => tree.exists(path);
119
+ host.readFile = readFile;
120
+ host.realpath = (path) => path;
121
+ host.directoryExists = (path) => {
122
+ const directory = tree.getDir(path);
123
+ return directory.subfiles.length > 0 || directory.subdirs.length > 0;
124
+ };
125
+ host.getSourceFile = (path) => {
126
+ if (path.split('/').some((part) => ignoredDirectories.has(part)))
127
+ return undefined;
128
+ const text = readFile(path);
129
+ return text === undefined
130
+ ? undefined
131
+ : typescript_1.default.createSourceFile(path, text, typescript_1.default.ScriptTarget.Latest, true);
132
+ };
133
+ return typescript_1.default
134
+ .createProgram(config.fileNames, config.options, host)
135
+ .getSourceFiles()
136
+ .map((source) => source.fileName)
137
+ .filter(isSource);
138
+ }
139
+ /** Use Angular/Nx projects and their declared configs, including inherited configs and local imports. */
140
+ async function migrationWorkspace(tree) {
141
+ const manifests = new Set();
142
+ if (tree.exists('/package.json'))
143
+ manifests.add('/package.json');
144
+ const projects = new Map();
145
+ const addProject = (root, sourceRoot, targets) => {
146
+ root = node_path_1.posix.resolve('/', root);
147
+ const project = projects.get(root) ?? {
148
+ sourceRoot,
149
+ configs: new Set(),
150
+ };
151
+ project.sourceRoot ??= sourceRoot;
152
+ projects.set(root, project);
153
+ const manifest = node_path_1.posix.join(root, 'package.json');
154
+ if (tree.exists(manifest))
155
+ manifests.add(manifest);
156
+ for (const target of targets) {
157
+ for (const options of [
158
+ target.options,
159
+ ...Object.values(target.configurations ?? {}),
160
+ ]) {
161
+ if (typeof options?.tsConfig === 'string' &&
162
+ tree.exists(options.tsConfig))
163
+ project.configs.add(node_path_1.posix.resolve('/', options.tsConfig));
164
+ }
165
+ }
166
+ };
167
+ if (tree.exists('/angular.json') || tree.exists('/.angular.json')) {
168
+ const workspace = await (0, workspace_1.getWorkspace)(tree, tree.exists('/angular.json') ? '/angular.json' : '/.angular.json');
169
+ for (const project of workspace.projects.values())
170
+ addProject(project.root, project.sourceRoot, project.targets.values());
171
+ }
172
+ if (tree.exists('/nx.json')) {
173
+ for (const path of filesUnder(tree, '/')) {
174
+ if (node_path_1.posix.basename(path) === 'project.json') {
175
+ const project = tree.readJson(path);
176
+ addProject(project.root ?? node_path_1.posix.dirname(path), project.sourceRoot, Object.values(project.targets ?? {}));
177
+ }
178
+ else if (node_path_1.posix.basename(path) === 'package.json') {
179
+ const pkg = tree.readJson(path);
180
+ if (pkg.nx)
181
+ addProject(node_path_1.posix.dirname(path), pkg.nx.sourceRoot, Object.values(pkg.nx.targets ?? {}));
182
+ }
183
+ }
184
+ }
185
+ if (!projects.size)
186
+ return { files: sourcesUnder(tree, '/'), manifests: [...manifests] };
187
+ const files = new Set();
188
+ for (const [root, project] of projects) {
189
+ const sources = project.configs.size
190
+ ? [...project.configs].flatMap((path) => configuredSources(tree, path))
191
+ : sourcesUnder(tree, node_path_1.posix.resolve('/', project.sourceRoot ?? root));
192
+ for (const path of sources)
193
+ files.add(path);
194
+ }
195
+ return { files: [...files], manifests: [...manifests] };
196
+ }
197
+ /** Associate each source with its closest declared workspace package. */
198
+ function sourceManifest(path, manifests) {
199
+ return [...manifests]
200
+ .sort((a, b) => b.length - a.length)
201
+ .find((manifest) => path.startsWith(`${node_path_1.posix.dirname(manifest).replace(/\/$/, '')}/`));
202
+ }
@@ -16,7 +16,7 @@ const typescript_1 = __importDefault(require("typescript"));
16
16
  // The published schematic contains literal values and does not read package.json.
17
17
  const PACKAGE_NAME = '@tanstack/angular-query';
18
18
  const DEVTOOLS_PACKAGE_NAME = '@tanstack/angular-query-devtools';
19
- const DEVTOOLS_PACKAGE_VERSION = '5.0.0-rc.2';
19
+ const DEVTOOLS_PACKAGE_VERSION = '5.0.0-rc.3';
20
20
  function hasPackageDependency(tree, name) {
21
21
  const packageJsonPath = tree.exists('/package.json')
22
22
  ? '/package.json'