@demokit-ai/core 0.3.0 → 0.4.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/dist/index.d.cts CHANGED
@@ -81,6 +81,43 @@ interface SessionState {
81
81
  */
82
82
  declare function createSessionState(): SessionState;
83
83
 
84
+ /**
85
+ * Configuration for automatic demo mode detection based on URL
86
+ */
87
+ interface DetectionConfig {
88
+ /**
89
+ * Hostnames that should auto-enable demo mode
90
+ * @example ['demo.myapp.com', 'demo.localhost']
91
+ */
92
+ subdomains?: string[];
93
+ /**
94
+ * Query parameters that trigger demo mode when present
95
+ * @default ['demo']
96
+ * @example With ['demo'], visiting ?demo=true enables demo mode
97
+ */
98
+ queryParams?: string[];
99
+ }
100
+ /**
101
+ * Context passed to the onMutationIntercepted callback
102
+ */
103
+ interface MutationInterceptedContext {
104
+ /**
105
+ * The full URL of the intercepted request
106
+ */
107
+ url: string;
108
+ /**
109
+ * HTTP method (POST, PUT, PATCH, DELETE)
110
+ */
111
+ method: string;
112
+ /**
113
+ * URL parameters extracted from the pattern
114
+ */
115
+ params: Record<string, string>;
116
+ /**
117
+ * The fixture pattern that matched
118
+ */
119
+ pattern: string;
120
+ }
84
121
  /**
85
122
  * Configuration for creating a demo interceptor
86
123
  */
@@ -120,6 +157,29 @@ interface DemoKitConfig {
120
157
  * @default 'http://localhost'
121
158
  */
122
159
  baseUrl?: string;
160
+ /**
161
+ * Auto-detection configuration for enabling demo mode based on URL
162
+ * When configured, demo mode is automatically enabled on matching subdomains
163
+ * or when specific query parameters are present
164
+ */
165
+ detection?: DetectionConfig;
166
+ /**
167
+ * Guard callback that controls whether demo mode can be disabled.
168
+ * Return `true` to allow disabling, `false` to prevent it,
169
+ * or a string to prevent it and provide a reason message.
170
+ *
171
+ * @example
172
+ * canDisable: () => {
173
+ * if (isPublicDemo) return 'Sign up to access your own data'
174
+ * return true
175
+ * }
176
+ */
177
+ canDisable?: () => boolean | string;
178
+ /**
179
+ * Callback fired when a non-GET request is intercepted by a fixture.
180
+ * Useful for showing "simulated in demo mode" toast notifications.
181
+ */
182
+ onMutationIntercepted?: (context: MutationInterceptedContext) => void;
123
183
  }
124
184
  /**
125
185
  * Map of URL patterns to fixture handlers
@@ -194,13 +254,19 @@ interface DemoInterceptor {
194
254
  */
195
255
  enable(): void;
196
256
  /**
197
- * Disable demo mode - fetches will pass through to the real API
257
+ * Disable demo mode - fetches will pass through to the real API.
258
+ * Returns `true` if disabled successfully, `false` or a string reason
259
+ * if prevented by the `canDisable` guard.
198
260
  */
199
- disable(): void;
261
+ disable(): boolean | string;
200
262
  /**
201
263
  * Check if demo mode is currently enabled
202
264
  */
203
265
  isEnabled(): boolean;
266
+ /**
267
+ * Check if this is a public demo (auto-detected via subdomain)
268
+ */
269
+ isPublicDemo(): boolean;
204
270
  /**
205
271
  * Toggle demo mode state and return the new state
206
272
  */
@@ -273,8 +339,14 @@ interface RemoteConfig {
273
339
  */
274
340
  apiKey: string;
275
341
  /**
276
- * DemoKit Cloud API URL
277
- * @default 'https://api.demokit.cloud'
342
+ * DemoKit Cloud API URL (base URL)
343
+ * The SDK will append `/fixtures` to this URL.
344
+ * @example 'https://demokit-cloud.kasava.dev/api'
345
+ * @default 'https://api.demokit.cloud/api'
346
+ */
347
+ apiUrl?: string;
348
+ /**
349
+ * @deprecated Use apiUrl instead. This is kept for backwards compatibility.
278
350
  */
279
351
  cloudUrl?: string;
280
352
  /**
@@ -711,7 +783,11 @@ declare function clearDemoState(key?: string): void;
711
783
  /**
712
784
  * Default DemoKit Cloud API URL
713
785
  */
714
- declare const DEFAULT_CLOUD_URL = "https://api.demokit.cloud";
786
+ declare const DEFAULT_API_URL = "https://api.demokit.cloud/api";
787
+ /**
788
+ * @deprecated Use DEFAULT_API_URL instead
789
+ */
790
+ declare const DEFAULT_CLOUD_URL = "https://api.demokit.cloud/api";
715
791
  /**
716
792
  * Default request timeout in milliseconds
717
793
  */
@@ -2875,4 +2951,4 @@ declare namespace checks {
2875
2951
  export { checks_equals as equals, checks_getTypeName as getTypeName, checks_hasArrayMaxLength as hasArrayMaxLength, checks_hasArrayMinLength as hasArrayMinLength, checks_hasMaxLength as hasMaxLength, checks_hasMaximum as hasMaximum, checks_hasMinLength as hasMinLength, checks_hasMinimum as hasMinimum, checks_isAfterOrEqual as isAfterOrEqual, checks_isArray as isArray, checks_isArrayNotEmpty as isArrayNotEmpty, checks_isBeforeOrEqual as isBeforeOrEqual, checks_isBoolean as isBoolean, checks_isDate as isDate, checks_isDateTime as isDateTime, checks_isEmail as isEmail, checks_isEmptyString as isEmptyString, checks_isISO8601 as isISO8601, checks_isInEnum as isInEnum, checks_isInteger as isInteger, checks_isNull as isNull, checks_isNullish as isNullish, checks_isNumber as isNumber, checks_isObject as isObject, checks_isString as isString, checks_isURL as isURL, checks_isUUID as isUUID, checks_isUndefined as isUndefined, checks_matchesPattern as matchesPattern };
2876
2952
  }
2877
2953
 
2878
- export { type AppContext, type BooleanFieldRule, type Character, type CloudFixtureResponse, type CodebaseFile, DEFAULT_CLOUD_URL, DEFAULT_MAX_RETRIES, DEFAULT_STORAGE_KEY, DEFAULT_TIMEOUT, type DataModel, type Dataset, type DatasetFieldRule, type DemoData, type DemoInterceptor, type DemoKitConfig, type DemoKitRemoteConfig, type DemoNarrative, type DemoState, type DemoStateStore, type DemoStateStoreOptions, type DemokitSchema, type Endpoint, type EndpointMapping, type EntityContext, type EnumFieldRule, FORMAT_PATTERNS, FORMAT_PRIORITY, type FieldRule, FileParseError, type FixtureHandler, type FixtureMap, FormatDetectionError, type FormatDetectionPatterns, type FormatDetectionResult, type GenerationLevel, type GenerationMetadata, type GenerationOptions, type GenerationResult, type GenerationRulesConfig, type HttpMethod, type IntegerFieldRule, type MatchResult, type MergeConflict, type MergeOptions, type MergeResult, type MetricTarget, type ModelData, type ModelSourceMap, type ModelType, type NumberFieldRule, type OutputOptions, type ParameterDef, type ParseCSVResult, type ParseOptions, type ParseResult, type ParseSchemaOptions, type ParseWarning, type ParsedPattern, type PropertyDef, type PropertyDiff, type PropertyType, type QueryKey, type QueryKeyElement, type QueryKeyMatchResult, type Relationship, type RelationshipDetectionMethod, type RelationshipSide, type RelationshipTarget, type RelationshipType, type RemoteConfig, RemoteFetchError, type RemoteLoadingState, type RequestBody, type RequestContext, type ResponseDef, type RuleGeneratorConfig, type SafeResult, type SchemaDiff, type SchemaDiffItem, type SchemaFormat, type SchemaInfo, SchemaMergeError, SchemaParseError, type SchemaRef, type SchemaSource, SchemaValidationError, type SessionState, type StringFieldRule, type TimelineEvent, type ValidationCheck, type ValidationError, type ValidationErrorType, type ValidationResult, type ValidationRule, type ValidationStats, type ValidationWarning, type ValidationWarningType, type ValidatorOptions, aggregateWarnings, buildFixtureMap, checks, clearDemoState, clearPatternCache, createAppContext, createDemoInterceptor, createDemoState, createDemoStateStore, createHandlerForMapping, createRemoteFixtures, createSessionState, describeRule, detectFormat, detectFormatFromFiles, detectRelationshipFromExtension, detectRelationshipFromNaming, detectRelationshipFromRef, detectRelationships, diffSchemas, errorToWarning, extractRefName, fetchCloudFixtures, findMatchingPattern, findMatchingQueryKeyPattern, formatAsCSV, formatAsJSON, formatAsSQL, formatAsTypeScript, generateCuid, generateDatasetId, generateDemoData, generateId, generateIdForModel, generatePrefixedId, generateRulesFromSchema, generateSeededUUID, generateUUID, generateUlid, generateValue, getModelDependencyOrder, getRelationshipRules, getRelationshipsForModel, getRequiredFieldRules, groupFilesByFormat, groupRulesByModel, inferAppContext, isModelReferenced, isRecoverableError, isSchemaRef, isValidApiKey, loadDemoState, matchQueryKey, matchUrl, mergeAppContext, mergeFixtures, mergeSchemas, parseCSV, parseDrizzle, parseGraphQL, parseNextJS, parseOpenAPIFromObject, parseOpenAPIFromPath, parseOpenAPIFromString, parsePrisma, parseSchema, parseSchemaMultiFormat, parseSupabase, parseTRPC, parseTypeScript, parseUrlPattern, parseZod, safeExecute, safeProcessMany, saveDemoState, validateData, validateDatasetName, validateTimestampOrder };
2954
+ export { type AppContext, type BooleanFieldRule, type Character, type CloudFixtureResponse, type CodebaseFile, DEFAULT_API_URL, DEFAULT_CLOUD_URL, DEFAULT_MAX_RETRIES, DEFAULT_STORAGE_KEY, DEFAULT_TIMEOUT, type DataModel, type Dataset, type DatasetFieldRule, type DemoData, type DemoInterceptor, type DemoKitConfig, type DemoKitRemoteConfig, type DemoNarrative, type DemoState, type DemoStateStore, type DemoStateStoreOptions, type DemokitSchema, type DetectionConfig, type Endpoint, type EndpointMapping, type EntityContext, type EnumFieldRule, FORMAT_PATTERNS, FORMAT_PRIORITY, type FieldRule, FileParseError, type FixtureHandler, type FixtureMap, FormatDetectionError, type FormatDetectionPatterns, type FormatDetectionResult, type GenerationLevel, type GenerationMetadata, type GenerationOptions, type GenerationResult, type GenerationRulesConfig, type HttpMethod, type IntegerFieldRule, type MatchResult, type MergeConflict, type MergeOptions, type MergeResult, type MetricTarget, type ModelData, type ModelSourceMap, type ModelType, type MutationInterceptedContext, type NumberFieldRule, type OutputOptions, type ParameterDef, type ParseCSVResult, type ParseOptions, type ParseResult, type ParseSchemaOptions, type ParseWarning, type ParsedPattern, type PropertyDef, type PropertyDiff, type PropertyType, type QueryKey, type QueryKeyElement, type QueryKeyMatchResult, type Relationship, type RelationshipDetectionMethod, type RelationshipSide, type RelationshipTarget, type RelationshipType, type RemoteConfig, RemoteFetchError, type RemoteLoadingState, type RequestBody, type RequestContext, type ResponseDef, type RuleGeneratorConfig, type SafeResult, type SchemaDiff, type SchemaDiffItem, type SchemaFormat, type SchemaInfo, SchemaMergeError, SchemaParseError, type SchemaRef, type SchemaSource, SchemaValidationError, type SessionState, type StringFieldRule, type TimelineEvent, type ValidationCheck, type ValidationError, type ValidationErrorType, type ValidationResult, type ValidationRule, type ValidationStats, type ValidationWarning, type ValidationWarningType, type ValidatorOptions, aggregateWarnings, buildFixtureMap, checks, clearDemoState, clearPatternCache, createAppContext, createDemoInterceptor, createDemoState, createDemoStateStore, createHandlerForMapping, createRemoteFixtures, createSessionState, describeRule, detectFormat, detectFormatFromFiles, detectRelationshipFromExtension, detectRelationshipFromNaming, detectRelationshipFromRef, detectRelationships, diffSchemas, errorToWarning, extractRefName, fetchCloudFixtures, findMatchingPattern, findMatchingQueryKeyPattern, formatAsCSV, formatAsJSON, formatAsSQL, formatAsTypeScript, generateCuid, generateDatasetId, generateDemoData, generateId, generateIdForModel, generatePrefixedId, generateRulesFromSchema, generateSeededUUID, generateUUID, generateUlid, generateValue, getModelDependencyOrder, getRelationshipRules, getRelationshipsForModel, getRequiredFieldRules, groupFilesByFormat, groupRulesByModel, inferAppContext, isModelReferenced, isRecoverableError, isSchemaRef, isValidApiKey, loadDemoState, matchQueryKey, matchUrl, mergeAppContext, mergeFixtures, mergeSchemas, parseCSV, parseDrizzle, parseGraphQL, parseNextJS, parseOpenAPIFromObject, parseOpenAPIFromPath, parseOpenAPIFromString, parsePrisma, parseSchema, parseSchemaMultiFormat, parseSupabase, parseTRPC, parseTypeScript, parseUrlPattern, parseZod, safeExecute, safeProcessMany, saveDemoState, validateData, validateDatasetName, validateTimestampOrder };
package/dist/index.d.ts CHANGED
@@ -81,6 +81,43 @@ interface SessionState {
81
81
  */
82
82
  declare function createSessionState(): SessionState;
83
83
 
84
+ /**
85
+ * Configuration for automatic demo mode detection based on URL
86
+ */
87
+ interface DetectionConfig {
88
+ /**
89
+ * Hostnames that should auto-enable demo mode
90
+ * @example ['demo.myapp.com', 'demo.localhost']
91
+ */
92
+ subdomains?: string[];
93
+ /**
94
+ * Query parameters that trigger demo mode when present
95
+ * @default ['demo']
96
+ * @example With ['demo'], visiting ?demo=true enables demo mode
97
+ */
98
+ queryParams?: string[];
99
+ }
100
+ /**
101
+ * Context passed to the onMutationIntercepted callback
102
+ */
103
+ interface MutationInterceptedContext {
104
+ /**
105
+ * The full URL of the intercepted request
106
+ */
107
+ url: string;
108
+ /**
109
+ * HTTP method (POST, PUT, PATCH, DELETE)
110
+ */
111
+ method: string;
112
+ /**
113
+ * URL parameters extracted from the pattern
114
+ */
115
+ params: Record<string, string>;
116
+ /**
117
+ * The fixture pattern that matched
118
+ */
119
+ pattern: string;
120
+ }
84
121
  /**
85
122
  * Configuration for creating a demo interceptor
86
123
  */
@@ -120,6 +157,29 @@ interface DemoKitConfig {
120
157
  * @default 'http://localhost'
121
158
  */
122
159
  baseUrl?: string;
160
+ /**
161
+ * Auto-detection configuration for enabling demo mode based on URL
162
+ * When configured, demo mode is automatically enabled on matching subdomains
163
+ * or when specific query parameters are present
164
+ */
165
+ detection?: DetectionConfig;
166
+ /**
167
+ * Guard callback that controls whether demo mode can be disabled.
168
+ * Return `true` to allow disabling, `false` to prevent it,
169
+ * or a string to prevent it and provide a reason message.
170
+ *
171
+ * @example
172
+ * canDisable: () => {
173
+ * if (isPublicDemo) return 'Sign up to access your own data'
174
+ * return true
175
+ * }
176
+ */
177
+ canDisable?: () => boolean | string;
178
+ /**
179
+ * Callback fired when a non-GET request is intercepted by a fixture.
180
+ * Useful for showing "simulated in demo mode" toast notifications.
181
+ */
182
+ onMutationIntercepted?: (context: MutationInterceptedContext) => void;
123
183
  }
124
184
  /**
125
185
  * Map of URL patterns to fixture handlers
@@ -194,13 +254,19 @@ interface DemoInterceptor {
194
254
  */
195
255
  enable(): void;
196
256
  /**
197
- * Disable demo mode - fetches will pass through to the real API
257
+ * Disable demo mode - fetches will pass through to the real API.
258
+ * Returns `true` if disabled successfully, `false` or a string reason
259
+ * if prevented by the `canDisable` guard.
198
260
  */
199
- disable(): void;
261
+ disable(): boolean | string;
200
262
  /**
201
263
  * Check if demo mode is currently enabled
202
264
  */
203
265
  isEnabled(): boolean;
266
+ /**
267
+ * Check if this is a public demo (auto-detected via subdomain)
268
+ */
269
+ isPublicDemo(): boolean;
204
270
  /**
205
271
  * Toggle demo mode state and return the new state
206
272
  */
@@ -273,8 +339,14 @@ interface RemoteConfig {
273
339
  */
274
340
  apiKey: string;
275
341
  /**
276
- * DemoKit Cloud API URL
277
- * @default 'https://api.demokit.cloud'
342
+ * DemoKit Cloud API URL (base URL)
343
+ * The SDK will append `/fixtures` to this URL.
344
+ * @example 'https://demokit-cloud.kasava.dev/api'
345
+ * @default 'https://api.demokit.cloud/api'
346
+ */
347
+ apiUrl?: string;
348
+ /**
349
+ * @deprecated Use apiUrl instead. This is kept for backwards compatibility.
278
350
  */
279
351
  cloudUrl?: string;
280
352
  /**
@@ -711,7 +783,11 @@ declare function clearDemoState(key?: string): void;
711
783
  /**
712
784
  * Default DemoKit Cloud API URL
713
785
  */
714
- declare const DEFAULT_CLOUD_URL = "https://api.demokit.cloud";
786
+ declare const DEFAULT_API_URL = "https://api.demokit.cloud/api";
787
+ /**
788
+ * @deprecated Use DEFAULT_API_URL instead
789
+ */
790
+ declare const DEFAULT_CLOUD_URL = "https://api.demokit.cloud/api";
715
791
  /**
716
792
  * Default request timeout in milliseconds
717
793
  */
@@ -2875,4 +2951,4 @@ declare namespace checks {
2875
2951
  export { checks_equals as equals, checks_getTypeName as getTypeName, checks_hasArrayMaxLength as hasArrayMaxLength, checks_hasArrayMinLength as hasArrayMinLength, checks_hasMaxLength as hasMaxLength, checks_hasMaximum as hasMaximum, checks_hasMinLength as hasMinLength, checks_hasMinimum as hasMinimum, checks_isAfterOrEqual as isAfterOrEqual, checks_isArray as isArray, checks_isArrayNotEmpty as isArrayNotEmpty, checks_isBeforeOrEqual as isBeforeOrEqual, checks_isBoolean as isBoolean, checks_isDate as isDate, checks_isDateTime as isDateTime, checks_isEmail as isEmail, checks_isEmptyString as isEmptyString, checks_isISO8601 as isISO8601, checks_isInEnum as isInEnum, checks_isInteger as isInteger, checks_isNull as isNull, checks_isNullish as isNullish, checks_isNumber as isNumber, checks_isObject as isObject, checks_isString as isString, checks_isURL as isURL, checks_isUUID as isUUID, checks_isUndefined as isUndefined, checks_matchesPattern as matchesPattern };
2876
2952
  }
2877
2953
 
2878
- export { type AppContext, type BooleanFieldRule, type Character, type CloudFixtureResponse, type CodebaseFile, DEFAULT_CLOUD_URL, DEFAULT_MAX_RETRIES, DEFAULT_STORAGE_KEY, DEFAULT_TIMEOUT, type DataModel, type Dataset, type DatasetFieldRule, type DemoData, type DemoInterceptor, type DemoKitConfig, type DemoKitRemoteConfig, type DemoNarrative, type DemoState, type DemoStateStore, type DemoStateStoreOptions, type DemokitSchema, type Endpoint, type EndpointMapping, type EntityContext, type EnumFieldRule, FORMAT_PATTERNS, FORMAT_PRIORITY, type FieldRule, FileParseError, type FixtureHandler, type FixtureMap, FormatDetectionError, type FormatDetectionPatterns, type FormatDetectionResult, type GenerationLevel, type GenerationMetadata, type GenerationOptions, type GenerationResult, type GenerationRulesConfig, type HttpMethod, type IntegerFieldRule, type MatchResult, type MergeConflict, type MergeOptions, type MergeResult, type MetricTarget, type ModelData, type ModelSourceMap, type ModelType, type NumberFieldRule, type OutputOptions, type ParameterDef, type ParseCSVResult, type ParseOptions, type ParseResult, type ParseSchemaOptions, type ParseWarning, type ParsedPattern, type PropertyDef, type PropertyDiff, type PropertyType, type QueryKey, type QueryKeyElement, type QueryKeyMatchResult, type Relationship, type RelationshipDetectionMethod, type RelationshipSide, type RelationshipTarget, type RelationshipType, type RemoteConfig, RemoteFetchError, type RemoteLoadingState, type RequestBody, type RequestContext, type ResponseDef, type RuleGeneratorConfig, type SafeResult, type SchemaDiff, type SchemaDiffItem, type SchemaFormat, type SchemaInfo, SchemaMergeError, SchemaParseError, type SchemaRef, type SchemaSource, SchemaValidationError, type SessionState, type StringFieldRule, type TimelineEvent, type ValidationCheck, type ValidationError, type ValidationErrorType, type ValidationResult, type ValidationRule, type ValidationStats, type ValidationWarning, type ValidationWarningType, type ValidatorOptions, aggregateWarnings, buildFixtureMap, checks, clearDemoState, clearPatternCache, createAppContext, createDemoInterceptor, createDemoState, createDemoStateStore, createHandlerForMapping, createRemoteFixtures, createSessionState, describeRule, detectFormat, detectFormatFromFiles, detectRelationshipFromExtension, detectRelationshipFromNaming, detectRelationshipFromRef, detectRelationships, diffSchemas, errorToWarning, extractRefName, fetchCloudFixtures, findMatchingPattern, findMatchingQueryKeyPattern, formatAsCSV, formatAsJSON, formatAsSQL, formatAsTypeScript, generateCuid, generateDatasetId, generateDemoData, generateId, generateIdForModel, generatePrefixedId, generateRulesFromSchema, generateSeededUUID, generateUUID, generateUlid, generateValue, getModelDependencyOrder, getRelationshipRules, getRelationshipsForModel, getRequiredFieldRules, groupFilesByFormat, groupRulesByModel, inferAppContext, isModelReferenced, isRecoverableError, isSchemaRef, isValidApiKey, loadDemoState, matchQueryKey, matchUrl, mergeAppContext, mergeFixtures, mergeSchemas, parseCSV, parseDrizzle, parseGraphQL, parseNextJS, parseOpenAPIFromObject, parseOpenAPIFromPath, parseOpenAPIFromString, parsePrisma, parseSchema, parseSchemaMultiFormat, parseSupabase, parseTRPC, parseTypeScript, parseUrlPattern, parseZod, safeExecute, safeProcessMany, saveDemoState, validateData, validateDatasetName, validateTimestampOrder };
2954
+ export { type AppContext, type BooleanFieldRule, type Character, type CloudFixtureResponse, type CodebaseFile, DEFAULT_API_URL, DEFAULT_CLOUD_URL, DEFAULT_MAX_RETRIES, DEFAULT_STORAGE_KEY, DEFAULT_TIMEOUT, type DataModel, type Dataset, type DatasetFieldRule, type DemoData, type DemoInterceptor, type DemoKitConfig, type DemoKitRemoteConfig, type DemoNarrative, type DemoState, type DemoStateStore, type DemoStateStoreOptions, type DemokitSchema, type DetectionConfig, type Endpoint, type EndpointMapping, type EntityContext, type EnumFieldRule, FORMAT_PATTERNS, FORMAT_PRIORITY, type FieldRule, FileParseError, type FixtureHandler, type FixtureMap, FormatDetectionError, type FormatDetectionPatterns, type FormatDetectionResult, type GenerationLevel, type GenerationMetadata, type GenerationOptions, type GenerationResult, type GenerationRulesConfig, type HttpMethod, type IntegerFieldRule, type MatchResult, type MergeConflict, type MergeOptions, type MergeResult, type MetricTarget, type ModelData, type ModelSourceMap, type ModelType, type MutationInterceptedContext, type NumberFieldRule, type OutputOptions, type ParameterDef, type ParseCSVResult, type ParseOptions, type ParseResult, type ParseSchemaOptions, type ParseWarning, type ParsedPattern, type PropertyDef, type PropertyDiff, type PropertyType, type QueryKey, type QueryKeyElement, type QueryKeyMatchResult, type Relationship, type RelationshipDetectionMethod, type RelationshipSide, type RelationshipTarget, type RelationshipType, type RemoteConfig, RemoteFetchError, type RemoteLoadingState, type RequestBody, type RequestContext, type ResponseDef, type RuleGeneratorConfig, type SafeResult, type SchemaDiff, type SchemaDiffItem, type SchemaFormat, type SchemaInfo, SchemaMergeError, SchemaParseError, type SchemaRef, type SchemaSource, SchemaValidationError, type SessionState, type StringFieldRule, type TimelineEvent, type ValidationCheck, type ValidationError, type ValidationErrorType, type ValidationResult, type ValidationRule, type ValidationStats, type ValidationWarning, type ValidationWarningType, type ValidatorOptions, aggregateWarnings, buildFixtureMap, checks, clearDemoState, clearPatternCache, createAppContext, createDemoInterceptor, createDemoState, createDemoStateStore, createHandlerForMapping, createRemoteFixtures, createSessionState, describeRule, detectFormat, detectFormatFromFiles, detectRelationshipFromExtension, detectRelationshipFromNaming, detectRelationshipFromRef, detectRelationships, diffSchemas, errorToWarning, extractRefName, fetchCloudFixtures, findMatchingPattern, findMatchingQueryKeyPattern, formatAsCSV, formatAsJSON, formatAsSQL, formatAsTypeScript, generateCuid, generateDatasetId, generateDemoData, generateId, generateIdForModel, generatePrefixedId, generateRulesFromSchema, generateSeededUUID, generateUUID, generateUlid, generateValue, getModelDependencyOrder, getRelationshipRules, getRelationshipsForModel, getRequiredFieldRules, groupFilesByFormat, groupRulesByModel, inferAppContext, isModelReferenced, isRecoverableError, isSchemaRef, isValidApiKey, loadDemoState, matchQueryKey, matchUrl, mergeAppContext, mergeFixtures, mergeSchemas, parseCSV, parseDrizzle, parseGraphQL, parseNextJS, parseOpenAPIFromObject, parseOpenAPIFromPath, parseOpenAPIFromString, parsePrisma, parseSchema, parseSchemaMultiFormat, parseSupabase, parseTRPC, parseTypeScript, parseUrlPattern, parseZod, safeExecute, safeProcessMany, saveDemoState, validateData, validateDatasetName, validateTimestampOrder };
package/dist/index.js CHANGED
@@ -330,6 +330,26 @@ function extractUrl(input, baseUrl) {
330
330
  }
331
331
  return baseUrl;
332
332
  }
333
+ function detectDemoMode(detection) {
334
+ if (!detection || typeof window === "undefined") {
335
+ return { detected: false, isPublicDemo: false };
336
+ }
337
+ if (detection.subdomains?.length) {
338
+ const hostname = window.location.hostname;
339
+ if (detection.subdomains.some((sub) => hostname === sub)) {
340
+ return { detected: true, isPublicDemo: true };
341
+ }
342
+ }
343
+ const queryParams = detection.queryParams ?? ["demo"];
344
+ const searchParams = new URLSearchParams(window.location.search);
345
+ for (const param of queryParams) {
346
+ const value = searchParams.get(param);
347
+ if (value !== null && value !== "false") {
348
+ return { detected: true, isPublicDemo: false };
349
+ }
350
+ }
351
+ return { detected: false, isPublicDemo: false };
352
+ }
333
353
  function createDemoInterceptor(config) {
334
354
  const {
335
355
  fixtures: initialFixtures,
@@ -337,9 +357,13 @@ function createDemoInterceptor(config) {
337
357
  onEnable,
338
358
  onDisable,
339
359
  initialEnabled,
340
- baseUrl = "http://localhost"
360
+ baseUrl = "http://localhost",
361
+ detection,
362
+ canDisable,
363
+ onMutationIntercepted
341
364
  } = config;
342
- let enabled = initialEnabled ?? loadDemoState(storageKey);
365
+ const detectionResult = detectDemoMode(detection);
366
+ let enabled = detectionResult.detected || (initialEnabled ?? loadDemoState(storageKey));
343
367
  let currentFixtures = { ...initialFixtures };
344
368
  let sessionState = createSessionState();
345
369
  let originalFetch = null;
@@ -351,14 +375,19 @@ function createDemoInterceptor(config) {
351
375
  originalFetch = globalThis.fetch;
352
376
  globalThis.fetch = async function interceptedFetch(input, init) {
353
377
  if (!enabled) {
378
+ console.log("[DemoKit] Demo mode disabled, passing through");
354
379
  return originalFetch(input, init);
355
380
  }
356
381
  const method = init?.method?.toUpperCase() || "GET";
357
382
  const pathname = extractPathname(input, baseUrl);
383
+ console.log("[DemoKit] Intercepting request:", { method, pathname, enabled });
384
+ console.log("[DemoKit] Available fixtures:", Object.keys(currentFixtures));
358
385
  const match = findMatchingPattern(currentFixtures, method, pathname);
359
386
  if (!match) {
387
+ console.log("[DemoKit] No matching fixture for:", `${method} ${pathname}`);
360
388
  return originalFetch(input, init);
361
389
  }
390
+ console.log("[DemoKit] Found matching fixture:", match[0]);
362
391
  const [pattern, matchResult] = match;
363
392
  const handler = currentFixtures[pattern];
364
393
  const url = extractUrl(input, baseUrl);
@@ -379,6 +408,14 @@ function createDemoInterceptor(config) {
379
408
  headers,
380
409
  session: sessionState
381
410
  };
411
+ if (method !== "GET" && onMutationIntercepted) {
412
+ onMutationIntercepted({
413
+ url,
414
+ method,
415
+ params: matchResult.params,
416
+ pattern
417
+ });
418
+ }
382
419
  let result;
383
420
  try {
384
421
  if (typeof handler === "function") {
@@ -414,14 +451,24 @@ function createDemoInterceptor(config) {
414
451
  onEnable?.();
415
452
  },
416
453
  disable() {
417
- if (!enabled) return;
454
+ if (!enabled) return true;
455
+ if (canDisable) {
456
+ const result = canDisable();
457
+ if (result !== true) {
458
+ return result;
459
+ }
460
+ }
418
461
  enabled = false;
419
462
  saveDemoState(storageKey, false);
420
463
  onDisable?.();
464
+ return true;
421
465
  },
422
466
  isEnabled() {
423
467
  return enabled;
424
468
  },
469
+ isPublicDemo() {
470
+ return detectionResult.isPublicDemo;
471
+ },
425
472
  toggle() {
426
473
  if (enabled) {
427
474
  this.disable();
@@ -524,7 +571,8 @@ function createDemoStateStore(options = {}) {
524
571
  }
525
572
 
526
573
  // src/remote.ts
527
- var DEFAULT_CLOUD_URL = "https://api.demokit.cloud";
574
+ var DEFAULT_API_URL = "https://api.demokit.cloud/api";
575
+ var DEFAULT_CLOUD_URL = DEFAULT_API_URL;
528
576
  var DEFAULT_TIMEOUT = 1e4;
529
577
  var DEFAULT_MAX_RETRIES = 3;
530
578
  function isValidApiKey(apiKey) {
@@ -547,13 +595,16 @@ function getBackoffDelay(attempt, baseDelay = 1e3) {
547
595
  async function fetchCloudFixtures(config) {
548
596
  const {
549
597
  apiKey,
550
- cloudUrl = DEFAULT_CLOUD_URL,
598
+ apiUrl,
599
+ cloudUrl,
600
+ // deprecated, for backwards compatibility
551
601
  onError,
552
602
  onLoad,
553
603
  timeout = DEFAULT_TIMEOUT,
554
604
  retry = true,
555
605
  maxRetries = DEFAULT_MAX_RETRIES
556
606
  } = config;
607
+ const baseUrl = apiUrl || cloudUrl || DEFAULT_API_URL;
557
608
  if (!isValidApiKey(apiKey)) {
558
609
  const error = new RemoteFetchError(
559
610
  "Invalid API key format. Expected format: dk_live_xxx",
@@ -563,7 +614,7 @@ async function fetchCloudFixtures(config) {
563
614
  onError?.(error);
564
615
  throw error;
565
616
  }
566
- const url = `${cloudUrl.replace(/\/$/, "")}/api/v1/fixtures`;
617
+ const url = `${baseUrl.replace(/\/$/, "")}/fixtures`;
567
618
  let lastError = null;
568
619
  const maxAttempts = retry ? maxRetries : 1;
569
620
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
@@ -6847,6 +6898,6 @@ function getRequiredFieldRules(rules) {
6847
6898
  return rules.filter((rule) => rule.required);
6848
6899
  }
6849
6900
 
6850
- export { DEFAULT_CLOUD_URL, DEFAULT_MAX_RETRIES, DEFAULT_STORAGE_KEY, DEFAULT_TIMEOUT, FORMAT_PATTERNS, FORMAT_PRIORITY, FileParseError, FormatDetectionError, RemoteFetchError, SchemaMergeError, SchemaParseError, SchemaValidationError, aggregateWarnings, buildFixtureMap, checks_exports as checks, clearDemoState, clearPatternCache, createAppContext, createDemoInterceptor, createDemoState, createDemoStateStore, createHandlerForMapping, createRemoteFixtures, createSessionState, describeRule, detectFormat, detectFormatFromFiles, detectRelationshipFromExtension, detectRelationshipFromNaming, detectRelationshipFromRef, detectRelationships, diffSchemas, errorToWarning, extractRefName, fetchCloudFixtures, findMatchingPattern, findMatchingQueryKeyPattern, formatAsCSV, formatAsJSON, formatAsSQL, formatAsTypeScript, generateCuid, generateDatasetId, generateDemoData, generateId, generateIdForModel, generatePrefixedId, generateRulesFromSchema, generateSeededUUID, generateUUID, generateUlid, generateValue, getModelDependencyOrder, getRelationshipRules, getRelationshipsForModel, getRequiredFieldRules, groupFilesByFormat, groupRulesByModel, inferAppContext, isModelReferenced, isRecoverableError, isSchemaRef, isValidApiKey, loadDemoState, matchQueryKey, matchUrl, mergeAppContext, mergeFixtures, mergeSchemas, parseCSV, parseDrizzle, parseGraphQL, parseNextJS, parseOpenAPIFromObject, parseOpenAPIFromPath, parseOpenAPIFromString, parsePrisma, parseSchema, parseSchemaMultiFormat, parseSupabase, parseTRPC, parseTypeScript, parseUrlPattern, parseZod, safeExecute, safeProcessMany, saveDemoState, validateData, validateDatasetName, validateTimestampOrder };
6901
+ export { DEFAULT_API_URL, DEFAULT_CLOUD_URL, DEFAULT_MAX_RETRIES, DEFAULT_STORAGE_KEY, DEFAULT_TIMEOUT, FORMAT_PATTERNS, FORMAT_PRIORITY, FileParseError, FormatDetectionError, RemoteFetchError, SchemaMergeError, SchemaParseError, SchemaValidationError, aggregateWarnings, buildFixtureMap, checks_exports as checks, clearDemoState, clearPatternCache, createAppContext, createDemoInterceptor, createDemoState, createDemoStateStore, createHandlerForMapping, createRemoteFixtures, createSessionState, describeRule, detectFormat, detectFormatFromFiles, detectRelationshipFromExtension, detectRelationshipFromNaming, detectRelationshipFromRef, detectRelationships, diffSchemas, errorToWarning, extractRefName, fetchCloudFixtures, findMatchingPattern, findMatchingQueryKeyPattern, formatAsCSV, formatAsJSON, formatAsSQL, formatAsTypeScript, generateCuid, generateDatasetId, generateDemoData, generateId, generateIdForModel, generatePrefixedId, generateRulesFromSchema, generateSeededUUID, generateUUID, generateUlid, generateValue, getModelDependencyOrder, getRelationshipRules, getRelationshipsForModel, getRequiredFieldRules, groupFilesByFormat, groupRulesByModel, inferAppContext, isModelReferenced, isRecoverableError, isSchemaRef, isValidApiKey, loadDemoState, matchQueryKey, matchUrl, mergeAppContext, mergeFixtures, mergeSchemas, parseCSV, parseDrizzle, parseGraphQL, parseNextJS, parseOpenAPIFromObject, parseOpenAPIFromPath, parseOpenAPIFromString, parsePrisma, parseSchema, parseSchemaMultiFormat, parseSupabase, parseTRPC, parseTypeScript, parseUrlPattern, parseZod, safeExecute, safeProcessMany, saveDemoState, validateData, validateDatasetName, validateTimestampOrder };
6851
6902
  //# sourceMappingURL=index.js.map
6852
6903
  //# sourceMappingURL=index.js.map