graphile-scoped-introspection 0.2.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.
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export type { PgScopedIntrospectionConfig, PgScopedIntrospectionServiceConfig, SchemaScopedIntrospectionOptions, ScopedCatalogTypes, } from './plugin';
2
+ export { ConstructivePgIntrospectionPlugin, ScopedIntrospectionPreset, scopedIntrospectionUpstreamContract, } from './plugin';
3
+ export type { SchemaScopedIntrospectionPlan, SchemaScopedIntrospectionQuery, SchemaScopedIntrospectionScope, } from './scoped-introspection-query';
4
+ export { makeSchemaScopedIntrospectionPlan, makeSchemaScopedIntrospectionQuery, validateSchemaScopedIntrospection, } from './scoped-introspection-query';
package/index.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateSchemaScopedIntrospection = exports.makeSchemaScopedIntrospectionQuery = exports.makeSchemaScopedIntrospectionPlan = exports.scopedIntrospectionUpstreamContract = exports.ScopedIntrospectionPreset = exports.ConstructivePgIntrospectionPlugin = void 0;
4
+ var plugin_1 = require("./plugin");
5
+ Object.defineProperty(exports, "ConstructivePgIntrospectionPlugin", { enumerable: true, get: function () { return plugin_1.ConstructivePgIntrospectionPlugin; } });
6
+ Object.defineProperty(exports, "ScopedIntrospectionPreset", { enumerable: true, get: function () { return plugin_1.ScopedIntrospectionPreset; } });
7
+ Object.defineProperty(exports, "scopedIntrospectionUpstreamContract", { enumerable: true, get: function () { return plugin_1.scopedIntrospectionUpstreamContract; } });
8
+ var scoped_introspection_query_1 = require("./scoped-introspection-query");
9
+ Object.defineProperty(exports, "makeSchemaScopedIntrospectionPlan", { enumerable: true, get: function () { return scoped_introspection_query_1.makeSchemaScopedIntrospectionPlan; } });
10
+ Object.defineProperty(exports, "makeSchemaScopedIntrospectionQuery", { enumerable: true, get: function () { return scoped_introspection_query_1.makeSchemaScopedIntrospectionQuery; } });
11
+ Object.defineProperty(exports, "validateSchemaScopedIntrospection", { enumerable: true, get: function () { return scoped_introspection_query_1.validateSchemaScopedIntrospection; } });
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "graphile-scoped-introspection",
3
+ "version": "0.2.0",
4
+ "description": "Opt-in schema-scoped PostgreSQL introspection for Graphile",
5
+ "author": "Constructive <developers@constructive.io>",
6
+ "homepage": "https://github.com/constructive-io/constructive",
7
+ "license": "MIT",
8
+ "main": "index.js",
9
+ "module": "esm/index.js",
10
+ "types": "index.d.ts",
11
+ "scripts": {
12
+ "clean": "makage clean",
13
+ "prepack": "npm run build",
14
+ "build": "makage build",
15
+ "build:dev": "makage build --dev",
16
+ "lint": "eslint . --fix",
17
+ "test": "jest",
18
+ "test:watch": "jest --watch"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "directory": "dist"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "https://github.com/constructive-io/constructive"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/constructive-io/constructive/issues"
30
+ },
31
+ "dependencies": {
32
+ "@constructive-io/graphql-types": "^3.32.0"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^22.19.11",
36
+ "graphql": "16.13.0",
37
+ "makage": "^0.8.0",
38
+ "pgsql-test": "^5.14.0",
39
+ "postgraphile": "5.1.4"
40
+ },
41
+ "peerDependencies": {
42
+ "@dataplan/pg": "^1.1.1",
43
+ "graphile-build": "^5.1.1",
44
+ "graphile-build-pg": "5.1.3",
45
+ "graphile-config": "^1.1.0",
46
+ "pg-introspection": "^1.0.1"
47
+ },
48
+ "keywords": [
49
+ "postgraphile",
50
+ "graphile",
51
+ "constructive",
52
+ "plugin",
53
+ "postgres",
54
+ "introspection"
55
+ ],
56
+ "gitHead": "399437801c27b070312125f3f0ee821ce16e183e"
57
+ }
package/plugin.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import 'graphile-build';
2
+ import type { GraphileConfig } from 'graphile-config';
3
+ export type { PgScopedIntrospectionConfig, PgScopedIntrospectionServiceConfig, SchemaScopedIntrospectionOptions, ScopedCatalogTypes, } from '@constructive-io/graphql-types';
4
+ /**
5
+ * CNC-owned atomic replacement for graphile-build-pg's introspection plugin.
6
+ * Stock-only configurations delegate to the upstream helper unchanged.
7
+ */
8
+ export declare const ConstructivePgIntrospectionPlugin: GraphileConfig.Plugin;
9
+ /** Disable upstream atomically before installing the CNC replacement. */
10
+ export declare const ScopedIntrospectionPreset: GraphileConfig.Preset;
11
+ export declare const scopedIntrospectionUpstreamContract: Readonly<{
12
+ package: "graphile-build-pg";
13
+ version: "5.1.3";
14
+ pluginName: keyof GraphileConfig.Plugins;
15
+ namespace: keyof GraphileConfig.GatherHelpers;
16
+ hasInitialCache: boolean;
17
+ hasInitialState: boolean;
18
+ hasWatch: boolean;
19
+ helperNames: string[];
20
+ hookNames: string[];
21
+ }>;
package/plugin.js ADDED
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scopedIntrospectionUpstreamContract = exports.ScopedIntrospectionPreset = exports.ConstructivePgIntrospectionPlugin = void 0;
4
+ require("graphile-build");
5
+ const pg_1 = require("@dataplan/pg");
6
+ const graphile_build_pg_1 = require("graphile-build-pg");
7
+ const pg_introspection_1 = require("pg-introspection");
8
+ const scoped_introspection_query_1 = require("./scoped-introspection-query");
9
+ const upstreamGather = graphile_build_pg_1.PgIntrospectionPlugin.gather;
10
+ const upstreamHelpers = upstreamGather?.helpers;
11
+ const upstreamGetIntrospection = upstreamHelpers?.getIntrospection;
12
+ const SUPPORTED_GRAPHILE_BUILD_PG_VERSION = '5.1.3';
13
+ if (graphile_build_pg_1.version !== SUPPORTED_GRAPHILE_BUILD_PG_VERSION) {
14
+ throw new Error(`Unsupported graphile-build-pg introspection contract: expected ${SUPPORTED_GRAPHILE_BUILD_PG_VERSION}, received ${graphile_build_pg_1.version}`);
15
+ }
16
+ if (!upstreamGather || !upstreamHelpers || !upstreamGetIntrospection) {
17
+ throw new Error('graphile-build-pg PgIntrospectionPlugin no longer exposes the expected gather contract');
18
+ }
19
+ function getIntrospectionQuery(pgService, config) {
20
+ if (config === undefined || config === false) {
21
+ return {
22
+ query: { text: (0, pg_introspection_1.makeIntrospectionQuery)() },
23
+ scopedPlan: null,
24
+ };
25
+ }
26
+ const options = config === true ? {} : config;
27
+ const scopedPlan = (0, scoped_introspection_query_1.makeSchemaScopedIntrospectionPlan)(pgService.schemas ?? [], options);
28
+ return {
29
+ query: scopedPlan.query,
30
+ scopedPlan,
31
+ };
32
+ }
33
+ function assertScopedIntrospectionServices(pgServices, options) {
34
+ if (options === undefined)
35
+ return;
36
+ if (options === null ||
37
+ typeof options !== 'object' ||
38
+ Array.isArray(options)) {
39
+ throw new Error('pgScopedIntrospection must be an object keyed by PostgreSQL service name');
40
+ }
41
+ const serviceNames = new Set((pgServices ?? []).map((pgService) => pgService.name));
42
+ const unknownServiceNames = Object.keys(options).filter((serviceName) => !serviceNames.has(serviceName));
43
+ if (unknownServiceNames.length > 0) {
44
+ throw new Error(`Schema-scoped introspection configured for unknown PostgreSQL service(s): ${unknownServiceNames.join(', ')}`);
45
+ }
46
+ for (const [serviceName, config] of Object.entries(options)) {
47
+ if (config !== true &&
48
+ config !== false &&
49
+ (config === null ||
50
+ typeof config !== 'object' ||
51
+ Array.isArray(config))) {
52
+ throw new Error(`Schema-scoped introspection configuration for service '${serviceName}' must be true, false, or an options object`);
53
+ }
54
+ }
55
+ }
56
+ // Adapted from graphile-build-pg@5.1.3
57
+ // dist/plugins/PgIntrospectionPlugin.js. The upstream function is private, so
58
+ // mixed/scoped services must retain this service validation/query seam locally.
59
+ async function introspectPgServices(pgServices, scopedIntrospection) {
60
+ assertScopedIntrospectionServices(pgServices, scopedIntrospection);
61
+ if (!pgServices)
62
+ return [];
63
+ const seenNames = new Map();
64
+ const seenPgSettingsKeys = new Map();
65
+ const seenWithPgClientKeys = new Map();
66
+ return Promise.all(pgServices.map(async (pgService, i) => {
67
+ const { name, pgSettingsKey, withPgClientKey } = pgService;
68
+ if (!name)
69
+ throw new Error(`pgServices[${i}] has no name`);
70
+ if (!withPgClientKey) {
71
+ throw new Error(`pgServices[${i}] has no withPgClientKey`);
72
+ }
73
+ const duplicateName = seenNames.get(name);
74
+ if (duplicateName !== undefined) {
75
+ throw new Error(`pgServices[${i}] has the same name as pgServices[${duplicateName}] (${JSON.stringify(name)})`);
76
+ }
77
+ seenNames.set(name, i);
78
+ const duplicateClientKey = seenWithPgClientKeys.get(withPgClientKey);
79
+ if (duplicateClientKey !== undefined) {
80
+ throw new Error(`pgServices[${i}] has the same withPgClientKey as pgServices[${duplicateClientKey}] (${JSON.stringify(withPgClientKey)})`);
81
+ }
82
+ seenWithPgClientKeys.set(withPgClientKey, i);
83
+ if (pgSettingsKey) {
84
+ const duplicateSettingsKey = seenPgSettingsKeys.get(pgSettingsKey);
85
+ if (duplicateSettingsKey !== undefined) {
86
+ throw new Error(`pgServices[${i}] has the same pgSettingsKey as pgServices[${duplicateSettingsKey}] (${JSON.stringify(pgSettingsKey)})`);
87
+ }
88
+ seenPgSettingsKeys.set(pgSettingsKey, i);
89
+ }
90
+ const { query, scopedPlan } = getIntrospectionQuery(pgService, scopedIntrospection?.[name]);
91
+ const result = await (0, pg_1.withPgClientFromPgService)(pgService, pgService.pgSettingsForIntrospection ?? null, (client) => client.query(query));
92
+ const [row] = result.rows;
93
+ if (!row)
94
+ throw new Error('Introspection failed');
95
+ return {
96
+ pgService,
97
+ introspectionText: row.introspection,
98
+ scopedPlan,
99
+ };
100
+ }));
101
+ }
102
+ async function announceIntrospection(info, introspections) {
103
+ await Promise.all(introspections.map(async ({ introspection, pgService }) => {
104
+ const announce = async (eventName, entities) => {
105
+ await Promise.all(entities.map((entity) => info.process(eventName, { entity, serviceName: pgService.name })));
106
+ };
107
+ await info.process('pgIntrospection_introspection', {
108
+ introspection,
109
+ serviceName: pgService.name,
110
+ });
111
+ await announce('pgIntrospection_namespace', introspection.namespaces);
112
+ await announce('pgIntrospection_class', introspection.classes);
113
+ await announce('pgIntrospection_attribute', introspection.attributes);
114
+ await announce('pgIntrospection_constraint', introspection.constraints);
115
+ await announce('pgIntrospection_proc', introspection.procs);
116
+ await announce('pgIntrospection_role', introspection.roles);
117
+ await announce('pgIntrospection_auth_member', introspection.auth_members);
118
+ await announce('pgIntrospection_type', introspection.types);
119
+ await announce('pgIntrospection_enum', introspection.enums);
120
+ await announce('pgIntrospection_extension', introspection.extensions);
121
+ await announce('pgIntrospection_index', introspection.indexes);
122
+ await announce('pgIntrospection_language', introspection.languages);
123
+ await announce('pgIntrospection_range', introspection.ranges);
124
+ await announce('pgIntrospection_depend', introspection.depends);
125
+ await announce('pgIntrospection_description', introspection.descriptions);
126
+ }));
127
+ }
128
+ // Adapted from graphile-build-pg@5.1.3
129
+ // dist/plugins/PgIntrospectionPlugin.js. Upstream does not expose its
130
+ // cache/parse/announcement flow independently from the stock query.
131
+ function getConstructiveIntrospection(info) {
132
+ const pgServices = info.resolvedPreset.pgServices ?? [];
133
+ const scopedIntrospection = info.options.pgScopedIntrospection;
134
+ assertScopedIntrospectionServices(pgServices, scopedIntrospection);
135
+ const hasScopedService = Object.values(scopedIntrospection ?? {}).some((config) => config === true || (config !== false && config !== undefined));
136
+ if (!hasScopedService) {
137
+ return upstreamGetIntrospection(info);
138
+ }
139
+ return (info.state.getIntrospectionPromise ??
140
+ (info.state.getIntrospectionPromise = (async () => {
141
+ if (info.cache.dirty) {
142
+ info.cache.introspectionResultsPromise = null;
143
+ info.cache.dirty = false;
144
+ }
145
+ const introspectionPromise = info.cache.introspectionResultsPromise ??
146
+ (info.cache.introspectionResultsPromise =
147
+ introspectPgServices(pgServices, scopedIntrospection));
148
+ introspectionPromise.then(null, () => {
149
+ info.cache.introspectionResultsPromise = null;
150
+ });
151
+ const rawIntrospections = await introspectionPromise;
152
+ // Keep the raw result promise for clean gathers. Parsed introspection is
153
+ // intentionally rebuilt because gather plugins may mutate their copy.
154
+ const introspections = rawIntrospections.map(({ pgService, introspectionText, scopedPlan }) => {
155
+ const introspection = (0, pg_introspection_1.parseIntrospectionResults)(introspectionText);
156
+ if (scopedPlan) {
157
+ try {
158
+ (0, scoped_introspection_query_1.validateSchemaScopedIntrospection)(introspection, scopedPlan);
159
+ }
160
+ catch (error) {
161
+ const message = error instanceof Error ? error.message : String(error);
162
+ throw new Error(`Schema-scoped introspection validation failed for PostgreSQL service '${pgService.name}': ${message}`, { cause: error });
163
+ }
164
+ }
165
+ return { pgService, introspection };
166
+ });
167
+ // Announcements may call back into getIntrospection, so expose the
168
+ // resolved gather-local value before broadcasting entities.
169
+ info.state.getIntrospectionPromise = introspections;
170
+ await announceIntrospection(info, introspections);
171
+ return introspections;
172
+ })()));
173
+ }
174
+ async function getRangeByType(info, serviceName, typeId) {
175
+ const introspections = await info.helpers.pgIntrospection.getIntrospection();
176
+ const relevant = introspections.find((result) => result.pgService.name === serviceName);
177
+ if (!relevant)
178
+ throw new Error(`Could not find database '${serviceName}'`);
179
+ return relevant.introspection.ranges.find((range) => range.rngtypid === typeId || range.rngmultitypid === typeId);
180
+ }
181
+ /**
182
+ * CNC-owned atomic replacement for graphile-build-pg's introspection plugin.
183
+ * Stock-only configurations delegate to the upstream helper unchanged.
184
+ */
185
+ exports.ConstructivePgIntrospectionPlugin = {
186
+ name: 'ConstructivePgIntrospectionPlugin',
187
+ description: 'Adds opt-in schema-scoped PostgreSQL introspection for Constructive',
188
+ version: graphile_build_pg_1.PgIntrospectionPlugin.version,
189
+ provides: ['PgIntrospectionPlugin'],
190
+ before: ['PgRegistryPlugin'],
191
+ gather: {
192
+ ...upstreamGather,
193
+ helpers: {
194
+ ...upstreamHelpers,
195
+ getIntrospection: getConstructiveIntrospection,
196
+ getRangeByType,
197
+ },
198
+ },
199
+ };
200
+ /** Disable upstream atomically before installing the CNC replacement. */
201
+ exports.ScopedIntrospectionPreset = {
202
+ disablePlugins: ['PgIntrospectionPlugin'],
203
+ plugins: [exports.ConstructivePgIntrospectionPlugin],
204
+ };
205
+ exports.scopedIntrospectionUpstreamContract = Object.freeze({
206
+ package: 'graphile-build-pg',
207
+ version: SUPPORTED_GRAPHILE_BUILD_PG_VERSION,
208
+ pluginName: graphile_build_pg_1.PgIntrospectionPlugin.name,
209
+ namespace: upstreamGather.namespace,
210
+ hasInitialCache: typeof upstreamGather.initialCache === 'function',
211
+ hasInitialState: typeof upstreamGather.initialState === 'function',
212
+ hasWatch: typeof upstreamGather.watch === 'function',
213
+ helperNames: Object.keys(upstreamHelpers).sort(),
214
+ hookNames: Object.keys(upstreamGather.hooks ?? {}).sort(),
215
+ });
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Scoped catalog SQL adapted from Graphile Crystal's
3
+ * utils/pg-introspection/src/scopedIntrospection.ts at commit
4
+ * 441cef73b0a12ed24343b7f38241af28b6454280, which is MIT licensed
5
+ * (Copyright © 2023 Benjie Gillam). This is a static, CNC-owned query
6
+ * generator: it does not inspect or rewrite the upstream query at runtime.
7
+ */
8
+ import type { SchemaScopedIntrospectionOptions, ScopedCatalogTypes } from '@constructive-io/graphql-types';
9
+ import type { Introspection } from 'pg-introspection';
10
+ export type { SchemaScopedIntrospectionOptions, ScopedCatalogTypes, } from '@constructive-io/graphql-types';
11
+ export interface SchemaScopedIntrospectionQuery {
12
+ text: string;
13
+ values: [string[], string[]];
14
+ }
15
+ export interface SchemaScopedIntrospectionScope {
16
+ schemas: readonly string[];
17
+ catalogTypes: ScopedCatalogTypes;
18
+ capabilityExtensions: readonly string[];
19
+ }
20
+ export interface SchemaScopedIntrospectionPlan {
21
+ query: SchemaScopedIntrospectionQuery;
22
+ scope: SchemaScopedIntrospectionScope;
23
+ }
24
+ /**
25
+ * Builds a parameterized introspection plan scoped to the requested schemas
26
+ * and the transitive object dependencies required by their objects.
27
+ */
28
+ export declare const makeSchemaScopedIntrospectionPlan: (schemas: readonly string[], options?: SchemaScopedIntrospectionOptions) => SchemaScopedIntrospectionPlan;
29
+ /**
30
+ * Builds only the query portion of a schema-scoped introspection plan.
31
+ *
32
+ * Prefer `makeSchemaScopedIntrospectionPlan()` when the results will be
33
+ * parsed and validated by this package.
34
+ */
35
+ export declare const makeSchemaScopedIntrospectionQuery: (schemas: readonly string[], options?: SchemaScopedIntrospectionOptions) => SchemaScopedIntrospectionQuery;
36
+ /** Validates that an introspection result satisfies its scoped query plan. */
37
+ export declare function validateSchemaScopedIntrospection(introspection: Introspection, plan: SchemaScopedIntrospectionPlan): void;