@stackframe/stack-shared 2.8.48 → 2.8.49
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/CHANGELOG.md +6 -0
- package/dist/config/schema.d.mts +8 -52
- package/dist/config/schema.d.ts +8 -52
- package/dist/config/schema.js +10 -0
- package/dist/config/schema.js.map +1 -1
- package/dist/esm/config/schema.js +10 -0
- package/dist/esm/config/schema.js.map +1 -1
- package/dist/esm/interface/admin-interface.js +10 -0
- package/dist/esm/interface/admin-interface.js.map +1 -1
- package/dist/esm/interface/client-interface.js +11 -7
- package/dist/esm/interface/client-interface.js.map +1 -1
- package/dist/esm/interface/crud/projects.js +2 -1
- package/dist/esm/interface/crud/projects.js.map +1 -1
- package/dist/esm/utils/caches.js +17 -9
- package/dist/esm/utils/caches.js.map +1 -1
- package/dist/esm/utils/ips.js.map +1 -1
- package/dist/esm/utils/urls.js.map +1 -1
- package/dist/interface/admin-interface.d.mts +6 -0
- package/dist/interface/admin-interface.d.ts +6 -0
- package/dist/interface/admin-interface.js +10 -0
- package/dist/interface/admin-interface.js.map +1 -1
- package/dist/interface/client-interface.d.mts +2 -1
- package/dist/interface/client-interface.d.ts +2 -1
- package/dist/interface/client-interface.js +11 -7
- package/dist/interface/client-interface.js.map +1 -1
- package/dist/interface/crud/projects.d.mts +10 -0
- package/dist/interface/crud/projects.d.ts +10 -0
- package/dist/interface/crud/projects.js +2 -1
- package/dist/interface/crud/projects.js.map +1 -1
- package/dist/utils/caches.d.mts +7 -7
- package/dist/utils/caches.d.ts +7 -7
- package/dist/utils/caches.js +17 -9
- package/dist/utils/caches.js.map +1 -1
- package/dist/utils/ips.d.mts +1 -1
- package/dist/utils/ips.d.ts +1 -1
- package/dist/utils/ips.js.map +1 -1
- package/dist/utils/urls.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/interface/crud/projects.ts"],"sourcesContent":["import { CrudTypeOf, createCrud } from \"../../crud\";\nimport * as schemaFields from \"../../schema-fields\";\nimport { yupArray, yupObject, yupString } from \"../../schema-fields\";\n\nconst teamPermissionSchema = yupObject({\n id: yupString().defined(),\n}).defined();\n\nconst oauthProviderReadSchema = yupObject({\n provider_config_id: schemaFields.yupString().defined(),\n id: schemaFields.oauthIdSchema.defined(),\n type: schemaFields.oauthTypeSchema.defined(),\n client_id: schemaFields.yupDefinedAndNonEmptyWhen(\n schemaFields.oauthClientIdSchema,\n { type: 'standard' },\n ),\n client_secret: schemaFields.yupDefinedAndNonEmptyWhen(\n schemaFields.oauthClientSecretSchema,\n { type: 'standard' },\n ),\n\n // extra params\n facebook_config_id: schemaFields.oauthFacebookConfigIdSchema.optional(),\n microsoft_tenant_id: schemaFields.oauthMicrosoftTenantIdSchema.optional(),\n});\n\nconst oauthProviderWriteSchema = oauthProviderReadSchema.omit(['provider_config_id']);\n\nconst enabledOAuthProviderSchema = yupObject({\n id: schemaFields.oauthIdSchema.defined(),\n});\n\nexport const emailConfigSchema = yupObject({\n type: schemaFields.emailTypeSchema.defined(),\n host: schemaFields.yupDefinedAndNonEmptyWhen(schemaFields.emailHostSchema, {\n type: 'standard',\n }),\n port: schemaFields.yupDefinedWhen(schemaFields.emailPortSchema, {\n type: 'standard',\n }),\n username: schemaFields.yupDefinedAndNonEmptyWhen(schemaFields.emailUsernameSchema, {\n type: 'standard',\n }),\n password: schemaFields.yupDefinedAndNonEmptyWhen(schemaFields.emailPasswordSchema, {\n type: 'standard',\n }),\n sender_name: schemaFields.yupDefinedAndNonEmptyWhen(schemaFields.emailSenderNameSchema, {\n type: 'standard',\n }),\n sender_email: schemaFields.yupDefinedAndNonEmptyWhen(schemaFields.emailSenderEmailSchema, {\n type: 'standard',\n }),\n});\n\nexport const emailConfigWithoutPasswordSchema = emailConfigSchema.pick(['type', 'host', 'port', 'username', 'sender_name', 'sender_email']);\n\nconst domainSchema = yupObject({\n domain: schemaFields.urlSchema.defined()\n .matches(/^https?:\\/\\//, 'URL must start with http:// or https://')\n .meta({ openapiField: { description: 'URL. Must start with http:// or https://', exampleValue: 'https://example.com' } }),\n handler_path: schemaFields.handlerPathSchema.defined(),\n});\n\nexport const projectsCrudAdminReadSchema = yupObject({\n id: schemaFields.projectIdSchema.defined(),\n display_name: schemaFields.projectDisplayNameSchema.defined(),\n description: schemaFields.projectDescriptionSchema.nonNullable().defined(),\n logo_url: schemaFields.projectLogoUrlSchema.nullable().optional(),\n full_logo_url: schemaFields.projectFullLogoUrlSchema.nullable().optional(),\n created_at_millis: schemaFields.projectCreatedAtMillisSchema.defined(),\n is_production_mode: schemaFields.projectIsProductionModeSchema.defined(),\n owner_team_id: schemaFields.yupString().nullable().defined(),\n /** @deprecated */\n config: yupObject({\n allow_localhost: schemaFields.projectAllowLocalhostSchema.defined(),\n sign_up_enabled: schemaFields.projectSignUpEnabledSchema.defined(),\n credential_enabled: schemaFields.projectCredentialEnabledSchema.defined(),\n magic_link_enabled: schemaFields.projectMagicLinkEnabledSchema.defined(),\n passkey_enabled: schemaFields.projectPasskeyEnabledSchema.defined(),\n // TODO: remove this\n client_team_creation_enabled: schemaFields.projectClientTeamCreationEnabledSchema.defined(),\n client_user_deletion_enabled: schemaFields.projectClientUserDeletionEnabledSchema.defined(),\n allow_user_api_keys: schemaFields.yupBoolean().defined(),\n allow_team_api_keys: schemaFields.yupBoolean().defined(),\n oauth_providers: yupArray(oauthProviderReadSchema.defined()).defined(),\n enabled_oauth_providers: yupArray(enabledOAuthProviderSchema.defined()).defined().meta({ openapiField: { hidden: true } }),\n domains: yupArray(domainSchema.defined()).defined(),\n email_config: emailConfigSchema.defined(),\n email_theme: schemaFields.emailThemeSchema.defined(),\n create_team_on_sign_up: schemaFields.projectCreateTeamOnSignUpSchema.defined(),\n team_creator_default_permissions: yupArray(teamPermissionSchema.defined()).defined(),\n team_member_default_permissions: yupArray(teamPermissionSchema.defined()).defined(),\n user_default_permissions: yupArray(teamPermissionSchema.defined()).defined(),\n oauth_account_merge_strategy: schemaFields.oauthAccountMergeStrategySchema.defined(),\n }).defined().meta({ openapiField: { hidden: true } }),\n}).defined();\n\nexport const projectsCrudClientReadSchema = yupObject({\n id: schemaFields.projectIdSchema.defined(),\n display_name: schemaFields.projectDisplayNameSchema.defined(),\n config: yupObject({\n sign_up_enabled: schemaFields.projectSignUpEnabledSchema.defined(),\n credential_enabled: schemaFields.projectCredentialEnabledSchema.defined(),\n magic_link_enabled: schemaFields.projectMagicLinkEnabledSchema.defined(),\n passkey_enabled: schemaFields.projectPasskeyEnabledSchema.defined(),\n client_team_creation_enabled: schemaFields.projectClientTeamCreationEnabledSchema.defined(),\n client_user_deletion_enabled: schemaFields.projectClientUserDeletionEnabledSchema.defined(),\n allow_user_api_keys: schemaFields.yupBoolean().defined(),\n allow_team_api_keys: schemaFields.yupBoolean().defined(),\n enabled_oauth_providers: yupArray(enabledOAuthProviderSchema.defined()).defined().meta({ openapiField: { hidden: true } }),\n }).defined().meta({ openapiField: { hidden: true } }),\n}).defined();\n\n\nexport const projectsCrudAdminUpdateSchema = yupObject({\n display_name: schemaFields.projectDisplayNameSchema.optional(),\n description: schemaFields.projectDescriptionSchema.optional(),\n logo_url: schemaFields.projectLogoUrlSchema.nullable().optional(),\n full_logo_url: schemaFields.projectFullLogoUrlSchema.nullable().optional(),\n is_production_mode: schemaFields.projectIsProductionModeSchema.optional(),\n config: yupObject({\n sign_up_enabled: schemaFields.projectSignUpEnabledSchema.optional(),\n credential_enabled: schemaFields.projectCredentialEnabledSchema.optional(),\n magic_link_enabled: schemaFields.projectMagicLinkEnabledSchema.optional(),\n passkey_enabled: schemaFields.projectPasskeyEnabledSchema.optional(),\n client_team_creation_enabled: schemaFields.projectClientTeamCreationEnabledSchema.optional(),\n client_user_deletion_enabled: schemaFields.projectClientUserDeletionEnabledSchema.optional(),\n allow_localhost: schemaFields.projectAllowLocalhostSchema.optional(),\n allow_user_api_keys: schemaFields.yupBoolean().optional(),\n allow_team_api_keys: schemaFields.yupBoolean().optional(),\n email_config: emailConfigSchema.optional().default(undefined),\n email_theme: schemaFields.emailThemeSchema.optional(),\n domains: yupArray(domainSchema.defined()).optional().default(undefined),\n oauth_providers: yupArray(oauthProviderWriteSchema.defined()).optional().default(undefined),\n create_team_on_sign_up: schemaFields.projectCreateTeamOnSignUpSchema.optional(),\n team_creator_default_permissions: yupArray(teamPermissionSchema.defined()).optional(),\n team_member_default_permissions: yupArray(teamPermissionSchema.defined()).optional(),\n user_default_permissions: yupArray(teamPermissionSchema.defined()).optional(),\n oauth_account_merge_strategy: schemaFields.oauthAccountMergeStrategySchema.optional(),\n }).optional().default(undefined),\n}).defined();\n\nexport const projectsCrudAdminCreateSchema = projectsCrudAdminUpdateSchema.concat(yupObject({\n display_name: schemaFields.projectDisplayNameSchema.defined(),\n owner_team_id: schemaFields.yupString().uuid().defined(),\n}).defined());\n\nexport const projectsCrudAdminDeleteSchema = schemaFields.yupMixed();\n\nexport const clientProjectsCrud = createCrud({\n clientReadSchema: projectsCrudClientReadSchema,\n docs: {\n clientRead: {\n summary: 'Get the current project',\n description: 'Get the current project information including display name, OAuth providers and authentication methods. Useful for displaying the available login options to the user.',\n tags: ['Projects'],\n },\n },\n});\nexport type ClientProjectsCrud = CrudTypeOf<typeof clientProjectsCrud>;\n\nexport const projectsCrud = createCrud({\n adminReadSchema: projectsCrudAdminReadSchema,\n adminUpdateSchema: projectsCrudAdminUpdateSchema,\n adminDeleteSchema: projectsCrudAdminDeleteSchema,\n docs: {\n adminRead: {\n summary: 'Get the current project',\n description: 'Get the current project information and configuration including display name, OAuth providers, email configuration, etc.',\n tags: ['Projects'],\n },\n adminUpdate: {\n summary: 'Update the current project',\n description: 'Update the current project information and configuration including display name, OAuth providers, email configuration, etc.',\n tags: ['Projects'],\n },\n adminDelete: {\n summary: 'Delete the current project',\n description: 'Delete the current project and all associated data (including users, teams, API keys, project configs, etc.). Be careful, this action is irreversible.',\n tags: ['Projects'],\n },\n },\n});\nexport type ProjectsCrud = CrudTypeOf<typeof projectsCrud>;\n\nexport const adminUserProjectsCrud = createCrud({\n clientReadSchema: projectsCrudAdminReadSchema,\n clientCreateSchema: projectsCrudAdminCreateSchema,\n docs: {\n clientList: {\n hidden: true,\n },\n clientCreate: {\n hidden: true,\n },\n },\n});\nexport type AdminUserProjectsCrud = CrudTypeOf<typeof adminUserProjectsCrud>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAuC;AACvC,mBAA8B;AAC9B,2BAA+C;AAE/C,IAAM,2BAAuB,gCAAU;AAAA,EACrC,QAAI,gCAAU,EAAE,QAAQ;AAC1B,CAAC,EAAE,QAAQ;AAEX,IAAM,8BAA0B,gCAAU;AAAA,EACxC,oBAAiC,uBAAU,EAAE,QAAQ;AAAA,EACrD,IAAiB,2BAAc,QAAQ;AAAA,EACvC,MAAmB,6BAAgB,QAAQ;AAAA,EAC3C,WAAwB;AAAA,IACT;AAAA,IACb,EAAE,MAAM,WAAW;AAAA,EACrB;AAAA,EACA,eAA4B;AAAA,IACb;AAAA,IACb,EAAE,MAAM,WAAW;AAAA,EACrB;AAAA;AAAA,EAGA,oBAAiC,yCAA4B,SAAS;AAAA,EACtE,qBAAkC,0CAA6B,SAAS;AAC1E,CAAC;AAED,IAAM,2BAA2B,wBAAwB,KAAK,CAAC,oBAAoB,CAAC;AAEpF,IAAM,iCAA6B,gCAAU;AAAA,EAC3C,IAAiB,2BAAc,QAAQ;AACzC,CAAC;AAEM,IAAM,wBAAoB,gCAAU;AAAA,EACzC,MAAmB,6BAAgB,QAAQ;AAAA,EAC3C,MAAmB,uCAAuC,8BAAiB;AAAA,IACzE,MAAM;AAAA,EACR,CAAC;AAAA,EACD,MAAmB,4BAA4B,8BAAiB;AAAA,IAC9D,MAAM;AAAA,EACR,CAAC;AAAA,EACD,UAAuB,uCAAuC,kCAAqB;AAAA,IAC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AS;AAAA,EACtF,CAAC,EAAE,SAAS,EAAE,QAAQ,MAAS;AACjC,CAAC,EAAE,QAAQ;AAEJ,IAAM,gCAAgC,8BAA8B,WAAO,gCAAU;AAAA,EAC1F,cAA2B,sCAAyB,QAAQ;AAAA,EAC5D,eAA4B,uBAAU,EAAE,KAAK,EAAE,QAAQ;AACzD,CAAC,EAAE,QAAQ,CAAC;AAEL,IAAM,gCAA6C,sBAAS;AAE5D,IAAM,yBAAqB,wBAAW;AAAA,EAC3C,kBAAkB;AAAA,EAClB,MAAM;AAAA,IACJ,YAAY;AAAA,MACV,SAAS;AAAA,MACT,aAAa;AAAA,MACb,MAAM,CAAC,UAAU;AAAA,IACnB;AAAA,EACF;AACF,CAAC;AAGM,IAAM,mBAAe,wBAAW;AAAA,EACrC,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,MAAM;AAAA,IACJ,WAAW;AAAA,MACT,SAAS;AAAA,MACT,aAAa;AAAA,MACb,MAAM,CAAC,UAAU;AAAA,IACnB;AAAA,IACA,aAAa;AAAA,MACX,SAAS;AAAA,MACT,aAAa;AAAA,MACb,MAAM,CAAC,UAAU;AAAA,IACnB;AAAA,IACA,aAAa;AAAA,MACX,SAAS;AAAA,MACT,aAAa;AAAA,MACb,MAAM,CAAC,UAAU;AAAA,IACnB;AAAA,EACF;AACF,CAAC;AAGM,IAAM,4BAAwB,wBAAW;AAAA,EAC9C,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,MAAM;AAAA,IACJ,YAAY;AAAA,MACV,QAAQ;AAAA,IACV;AAAA,IACA,cAAc;AAAA,MACZ,QAAQ;AAAA,IACV;AAAA,EACF;AACF,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/interface/crud/projects.ts"],"sourcesContent":["import { CrudTypeOf, createCrud } from \"../../crud\";\nimport * as schemaFields from \"../../schema-fields\";\nimport { yupArray, yupObject, yupString } from \"../../schema-fields\";\n\nconst teamPermissionSchema = yupObject({\n id: yupString().defined(),\n}).defined();\n\nconst oauthProviderReadSchema = yupObject({\n provider_config_id: schemaFields.yupString().defined(),\n id: schemaFields.oauthIdSchema.defined(),\n type: schemaFields.oauthTypeSchema.defined(),\n client_id: schemaFields.yupDefinedAndNonEmptyWhen(\n schemaFields.oauthClientIdSchema,\n { type: 'standard' },\n ),\n client_secret: schemaFields.yupDefinedAndNonEmptyWhen(\n schemaFields.oauthClientSecretSchema,\n { type: 'standard' },\n ),\n\n // extra params\n facebook_config_id: schemaFields.oauthFacebookConfigIdSchema.optional(),\n microsoft_tenant_id: schemaFields.oauthMicrosoftTenantIdSchema.optional(),\n});\n\nconst oauthProviderWriteSchema = oauthProviderReadSchema.omit(['provider_config_id']);\n\nconst enabledOAuthProviderSchema = yupObject({\n id: schemaFields.oauthIdSchema.defined(),\n});\n\nexport const emailConfigSchema = yupObject({\n type: schemaFields.emailTypeSchema.defined(),\n host: schemaFields.yupDefinedAndNonEmptyWhen(schemaFields.emailHostSchema, {\n type: 'standard',\n }),\n port: schemaFields.yupDefinedWhen(schemaFields.emailPortSchema, {\n type: 'standard',\n }),\n username: schemaFields.yupDefinedAndNonEmptyWhen(schemaFields.emailUsernameSchema, {\n type: 'standard',\n }),\n password: schemaFields.yupDefinedAndNonEmptyWhen(schemaFields.emailPasswordSchema, {\n type: 'standard',\n }),\n sender_name: schemaFields.yupDefinedAndNonEmptyWhen(schemaFields.emailSenderNameSchema, {\n type: 'standard',\n }),\n sender_email: schemaFields.yupDefinedAndNonEmptyWhen(schemaFields.emailSenderEmailSchema, {\n type: 'standard',\n }),\n});\n\nexport const emailConfigWithoutPasswordSchema = emailConfigSchema.pick(['type', 'host', 'port', 'username', 'sender_name', 'sender_email']);\n\nconst domainSchema = yupObject({\n domain: schemaFields.urlSchema.defined()\n .matches(/^https?:\\/\\//, 'URL must start with http:// or https://')\n .meta({ openapiField: { description: 'URL. Must start with http:// or https://', exampleValue: 'https://example.com' } }),\n handler_path: schemaFields.handlerPathSchema.defined(),\n});\n\nexport const projectsCrudAdminReadSchema = yupObject({\n id: schemaFields.projectIdSchema.defined(),\n display_name: schemaFields.projectDisplayNameSchema.defined(),\n description: schemaFields.projectDescriptionSchema.nonNullable().defined(),\n logo_url: schemaFields.projectLogoUrlSchema.nullable().optional(),\n full_logo_url: schemaFields.projectFullLogoUrlSchema.nullable().optional(),\n created_at_millis: schemaFields.projectCreatedAtMillisSchema.defined(),\n is_production_mode: schemaFields.projectIsProductionModeSchema.defined(),\n owner_team_id: schemaFields.yupString().nullable().defined(),\n /** @deprecated */\n config: yupObject({\n allow_localhost: schemaFields.projectAllowLocalhostSchema.defined(),\n sign_up_enabled: schemaFields.projectSignUpEnabledSchema.defined(),\n credential_enabled: schemaFields.projectCredentialEnabledSchema.defined(),\n magic_link_enabled: schemaFields.projectMagicLinkEnabledSchema.defined(),\n passkey_enabled: schemaFields.projectPasskeyEnabledSchema.defined(),\n // TODO: remove this\n client_team_creation_enabled: schemaFields.projectClientTeamCreationEnabledSchema.defined(),\n client_user_deletion_enabled: schemaFields.projectClientUserDeletionEnabledSchema.defined(),\n allow_user_api_keys: schemaFields.yupBoolean().defined(),\n allow_team_api_keys: schemaFields.yupBoolean().defined(),\n oauth_providers: yupArray(oauthProviderReadSchema.defined()).defined(),\n enabled_oauth_providers: yupArray(enabledOAuthProviderSchema.defined()).defined().meta({ openapiField: { hidden: true } }),\n domains: yupArray(domainSchema.defined()).defined(),\n email_config: emailConfigSchema.defined(),\n email_theme: schemaFields.emailThemeSchema.defined(),\n create_team_on_sign_up: schemaFields.projectCreateTeamOnSignUpSchema.defined(),\n team_creator_default_permissions: yupArray(teamPermissionSchema.defined()).defined(),\n team_member_default_permissions: yupArray(teamPermissionSchema.defined()).defined(),\n user_default_permissions: yupArray(teamPermissionSchema.defined()).defined(),\n oauth_account_merge_strategy: schemaFields.oauthAccountMergeStrategySchema.defined(),\n }).defined().meta({ openapiField: { hidden: true } }),\n}).defined();\n\nexport const projectsCrudClientReadSchema = yupObject({\n id: schemaFields.projectIdSchema.defined(),\n display_name: schemaFields.projectDisplayNameSchema.defined(),\n config: yupObject({\n sign_up_enabled: schemaFields.projectSignUpEnabledSchema.defined(),\n credential_enabled: schemaFields.projectCredentialEnabledSchema.defined(),\n magic_link_enabled: schemaFields.projectMagicLinkEnabledSchema.defined(),\n passkey_enabled: schemaFields.projectPasskeyEnabledSchema.defined(),\n client_team_creation_enabled: schemaFields.projectClientTeamCreationEnabledSchema.defined(),\n client_user_deletion_enabled: schemaFields.projectClientUserDeletionEnabledSchema.defined(),\n allow_user_api_keys: schemaFields.yupBoolean().defined(),\n allow_team_api_keys: schemaFields.yupBoolean().defined(),\n enabled_oauth_providers: yupArray(enabledOAuthProviderSchema.defined()).defined().meta({ openapiField: { hidden: true } }),\n domains: yupArray(domainSchema.defined()).defined(),\n }).defined().meta({ openapiField: { hidden: true } }),\n}).defined();\n\n\nexport const projectsCrudAdminUpdateSchema = yupObject({\n display_name: schemaFields.projectDisplayNameSchema.optional(),\n description: schemaFields.projectDescriptionSchema.optional(),\n logo_url: schemaFields.projectLogoUrlSchema.nullable().optional(),\n full_logo_url: schemaFields.projectFullLogoUrlSchema.nullable().optional(),\n is_production_mode: schemaFields.projectIsProductionModeSchema.optional(),\n config: yupObject({\n sign_up_enabled: schemaFields.projectSignUpEnabledSchema.optional(),\n credential_enabled: schemaFields.projectCredentialEnabledSchema.optional(),\n magic_link_enabled: schemaFields.projectMagicLinkEnabledSchema.optional(),\n passkey_enabled: schemaFields.projectPasskeyEnabledSchema.optional(),\n client_team_creation_enabled: schemaFields.projectClientTeamCreationEnabledSchema.optional(),\n client_user_deletion_enabled: schemaFields.projectClientUserDeletionEnabledSchema.optional(),\n allow_localhost: schemaFields.projectAllowLocalhostSchema.optional(),\n allow_user_api_keys: schemaFields.yupBoolean().optional(),\n allow_team_api_keys: schemaFields.yupBoolean().optional(),\n email_config: emailConfigSchema.optional().default(undefined),\n email_theme: schemaFields.emailThemeSchema.optional(),\n domains: yupArray(domainSchema.defined()).optional().default(undefined),\n oauth_providers: yupArray(oauthProviderWriteSchema.defined()).optional().default(undefined),\n create_team_on_sign_up: schemaFields.projectCreateTeamOnSignUpSchema.optional(),\n team_creator_default_permissions: yupArray(teamPermissionSchema.defined()).optional(),\n team_member_default_permissions: yupArray(teamPermissionSchema.defined()).optional(),\n user_default_permissions: yupArray(teamPermissionSchema.defined()).optional(),\n oauth_account_merge_strategy: schemaFields.oauthAccountMergeStrategySchema.optional(),\n }).optional().default(undefined),\n}).defined();\n\nexport const projectsCrudAdminCreateSchema = projectsCrudAdminUpdateSchema.concat(yupObject({\n display_name: schemaFields.projectDisplayNameSchema.defined(),\n owner_team_id: schemaFields.yupString().uuid().defined(),\n}).defined());\n\nexport const projectsCrudAdminDeleteSchema = schemaFields.yupMixed();\n\nexport const clientProjectsCrud = createCrud({\n clientReadSchema: projectsCrudClientReadSchema,\n docs: {\n clientRead: {\n summary: 'Get the current project',\n description: 'Get the current project information including display name, OAuth providers and authentication methods. Useful for displaying the available login options to the user.',\n tags: ['Projects'],\n },\n },\n});\nexport type ClientProjectsCrud = CrudTypeOf<typeof clientProjectsCrud>;\n\nexport const projectsCrud = createCrud({\n adminReadSchema: projectsCrudAdminReadSchema,\n adminUpdateSchema: projectsCrudAdminUpdateSchema,\n adminDeleteSchema: projectsCrudAdminDeleteSchema,\n docs: {\n adminRead: {\n summary: 'Get the current project',\n description: 'Get the current project information and configuration including display name, OAuth providers, email configuration, etc.',\n tags: ['Projects'],\n },\n adminUpdate: {\n summary: 'Update the current project',\n description: 'Update the current project information and configuration including display name, OAuth providers, email configuration, etc.',\n tags: ['Projects'],\n },\n adminDelete: {\n summary: 'Delete the current project',\n description: 'Delete the current project and all associated data (including users, teams, API keys, project configs, etc.). Be careful, this action is irreversible.',\n tags: ['Projects'],\n },\n },\n});\nexport type ProjectsCrud = CrudTypeOf<typeof projectsCrud>;\n\nexport const adminUserProjectsCrud = createCrud({\n clientReadSchema: projectsCrudAdminReadSchema,\n clientCreateSchema: projectsCrudAdminCreateSchema,\n docs: {\n clientList: {\n hidden: true,\n },\n clientCreate: {\n hidden: true,\n },\n },\n});\nexport type AdminUserProjectsCrud = CrudTypeOf<typeof adminUserProjectsCrud>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAuC;AACvC,mBAA8B;AAC9B,2BAA+C;AAE/C,IAAM,2BAAuB,gCAAU;AAAA,EACrC,QAAI,gCAAU,EAAE,QAAQ;AAC1B,CAAC,EAAE,QAAQ;AAEX,IAAM,8BAA0B,gCAAU;AAAA,EACxC,oBAAiC,uBAAU,EAAE,QAAQ;AAAA,EACrD,IAAiB,2BAAc,QAAQ;AAAA,EACvC,MAAmB,6BAAgB,QAAQ;AAAA,EAC3C,WAAwB;AAAA,IACT;AAAA,IACb,EAAE,MAAM,WAAW;AAAA,EACrB;AAAA,EACA,eAA4B;AAAA,IACb;AAAA,IACb,EAAE,MAAM,WAAW;AAAA,EACrB;AAAA;AAAA,EAGA,oBAAiC,yCAA4B,SAAS;AAAA,EACtE,qBAAkC,0CAA6B,SAAS;AAC1E,CAAC;AAED,IAAM,2BAA2B,wBAAwB,KAAK,CAAC,oBAAoB,CAAC;AAEpF,IAAM,iCAA6B,gCAAU;AAAA,EAC3C,IAAiB,2BAAc,QAAQ;AACzC,CAAC;AAEM,IAAM,wBAAoB,gCAAU;AAAA,EACzC,MAAmB,6BAAgB,QAAQ;AAAA,EAC3C,MAAmB,uCAAuC,8BAAiB;AAAA,IACzE,MAAM;AAAA,EACR,CAAC;AAAA,EACD,MAAmB,4BAA4B,8BAAiB;AAAA,IAC9D,MAAM;AAAA,EACR,CAAC;AAAA,EACD,UAAuB,uCAAuC,kCAAqB;AAAA,IACjF,MAAM;AAAA,EACR,CAAC;AAAA,EACD,UAAuB,uCAAuC,kCAAqB;AAAA,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ACtF,CAAC,EAAE,SAAS,EAAE,QAAQ,MAAS;AACjC,CAAC,EAAE,QAAQ;AAEJ,IAAM,gCAAgC,8BAA8B,WAAO,gCAAU;AAAA,EAC1F,cAA2B,sCAAyB,QAAQ;AAAA,EAC5D,eAA4B,uBAAU,EAAE,KAAK,EAAE,QAAQ;AACzD,CAAC,EAAE,QAAQ,CAAC;AAEL,IAAM,gCAA6C,sBAAS;AAE5D,IAAM,yBAAqB,wBAAW;AAAA,EAC3C,kBAAkB;AAAA,EAClB,MAAM;AAAA,IACJ,YAAY;AAAA,MACV,SAAS;AAAA,MACT,aAAa;AAAA,MACb,MAAM,CAAC,UAAU;AAAA,IACnB;AAAA,EACF;AACF,CAAC;AAGM,IAAM,mBAAe,wBAAW;AAAA,EACrC,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,MAAM;AAAA,IACJ,WAAW;AAAA,MACT,SAAS;AAAA,MACT,aAAa;AAAA,MACb,MAAM,CAAC,UAAU;AAAA,IACnB;AAAA,IACA,aAAa;AAAA,MACX,SAAS;AAAA,MACT,aAAa;AAAA,MACb,MAAM,CAAC,UAAU;AAAA,IACnB;AAAA,IACA,aAAa;AAAA,MACX,SAAS;AAAA,MACT,aAAa;AAAA,MACb,MAAM,CAAC,UAAU;AAAA,IACnB;AAAA,EACF;AACF,CAAC;AAGM,IAAM,4BAAwB,wBAAW;AAAA,EAC9C,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,MAAM;AAAA,IACJ,YAAY;AAAA,MACV,QAAQ;AAAA,IACV;AAAA,IACA,cAAc;AAAA,MACZ,QAAQ;AAAA,IACV;AAAA,EACF;AACF,CAAC;","names":[]}
|
package/dist/utils/caches.d.mts
CHANGED
|
@@ -17,6 +17,7 @@ declare class AsyncCache<D extends any[], T> {
|
|
|
17
17
|
private _createKeyed;
|
|
18
18
|
getValueCache(dependencies: D): AsyncValueCache<T>;
|
|
19
19
|
refreshWhere(predicate: (dependencies: D) => boolean): Promise<void>;
|
|
20
|
+
invalidateWhere(predicate: (dependencies: D) => boolean): Promise<void>;
|
|
20
21
|
readonly isCacheAvailable: (key: D) => boolean;
|
|
21
22
|
readonly getIfCached: (key: D) => ({
|
|
22
23
|
status: "error";
|
|
@@ -38,8 +39,8 @@ declare class AsyncCache<D extends any[], T> {
|
|
|
38
39
|
readonly getOrWait: (key: D, cacheStrategy: CacheStrategy) => ReactPromise<T>;
|
|
39
40
|
readonly forceSetCachedValue: (key: D, value: T) => void;
|
|
40
41
|
readonly forceSetCachedValueAsync: (key: D, value: Promise<T>) => ReactPromise<boolean>;
|
|
41
|
-
readonly refresh: (key: D) => Promise<
|
|
42
|
-
readonly invalidate: (key: D) => void
|
|
42
|
+
readonly refresh: (key: D) => Promise<void>;
|
|
43
|
+
readonly invalidate: (key: D) => Promise<void>;
|
|
43
44
|
readonly onStateChange: (key: D, callback: (value: T, oldValue: T | undefined) => void) => {
|
|
44
45
|
unsubscribe: () => void;
|
|
45
46
|
};
|
|
@@ -83,14 +84,13 @@ declare class AsyncValueCache<T> {
|
|
|
83
84
|
forceSetCachedValue(value: T): void;
|
|
84
85
|
forceSetCachedValueAsync(value: Promise<T>): ReactPromise<boolean>;
|
|
85
86
|
/**
|
|
86
|
-
*
|
|
87
|
+
* If anyone is listening to the cache, refreshes the value, and sets it without invalidating the cache.
|
|
87
88
|
*/
|
|
88
|
-
refresh(): Promise<
|
|
89
|
+
refresh(): Promise<void>;
|
|
89
90
|
/**
|
|
90
|
-
* Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read).
|
|
91
|
-
* it will refresh immediately.
|
|
91
|
+
* Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read). It will refresh immediately.
|
|
92
92
|
*/
|
|
93
|
-
invalidate(): void
|
|
93
|
+
invalidate(): Promise<void>;
|
|
94
94
|
isDirty(): boolean;
|
|
95
95
|
onStateChange(callback: (value: T, oldValue: T | undefined) => void): {
|
|
96
96
|
unsubscribe: () => void;
|
package/dist/utils/caches.d.ts
CHANGED
|
@@ -17,6 +17,7 @@ declare class AsyncCache<D extends any[], T> {
|
|
|
17
17
|
private _createKeyed;
|
|
18
18
|
getValueCache(dependencies: D): AsyncValueCache<T>;
|
|
19
19
|
refreshWhere(predicate: (dependencies: D) => boolean): Promise<void>;
|
|
20
|
+
invalidateWhere(predicate: (dependencies: D) => boolean): Promise<void>;
|
|
20
21
|
readonly isCacheAvailable: (key: D) => boolean;
|
|
21
22
|
readonly getIfCached: (key: D) => ({
|
|
22
23
|
status: "error";
|
|
@@ -38,8 +39,8 @@ declare class AsyncCache<D extends any[], T> {
|
|
|
38
39
|
readonly getOrWait: (key: D, cacheStrategy: CacheStrategy) => ReactPromise<T>;
|
|
39
40
|
readonly forceSetCachedValue: (key: D, value: T) => void;
|
|
40
41
|
readonly forceSetCachedValueAsync: (key: D, value: Promise<T>) => ReactPromise<boolean>;
|
|
41
|
-
readonly refresh: (key: D) => Promise<
|
|
42
|
-
readonly invalidate: (key: D) => void
|
|
42
|
+
readonly refresh: (key: D) => Promise<void>;
|
|
43
|
+
readonly invalidate: (key: D) => Promise<void>;
|
|
43
44
|
readonly onStateChange: (key: D, callback: (value: T, oldValue: T | undefined) => void) => {
|
|
44
45
|
unsubscribe: () => void;
|
|
45
46
|
};
|
|
@@ -83,14 +84,13 @@ declare class AsyncValueCache<T> {
|
|
|
83
84
|
forceSetCachedValue(value: T): void;
|
|
84
85
|
forceSetCachedValueAsync(value: Promise<T>): ReactPromise<boolean>;
|
|
85
86
|
/**
|
|
86
|
-
*
|
|
87
|
+
* If anyone is listening to the cache, refreshes the value, and sets it without invalidating the cache.
|
|
87
88
|
*/
|
|
88
|
-
refresh(): Promise<
|
|
89
|
+
refresh(): Promise<void>;
|
|
89
90
|
/**
|
|
90
|
-
* Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read).
|
|
91
|
-
* it will refresh immediately.
|
|
91
|
+
* Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read). It will refresh immediately.
|
|
92
92
|
*/
|
|
93
|
-
invalidate(): void
|
|
93
|
+
invalidate(): Promise<void>;
|
|
94
94
|
isDirty(): boolean;
|
|
95
95
|
onStateChange(callback: (value: T, oldValue: T | undefined) => void): {
|
|
96
96
|
unsubscribe: () => void;
|
package/dist/utils/caches.js
CHANGED
|
@@ -83,6 +83,15 @@ var AsyncCache = class {
|
|
|
83
83
|
}
|
|
84
84
|
await Promise.all(promises);
|
|
85
85
|
}
|
|
86
|
+
async invalidateWhere(predicate) {
|
|
87
|
+
const promises = [];
|
|
88
|
+
for (const [dependencies, cache] of this._map) {
|
|
89
|
+
if (predicate(dependencies)) {
|
|
90
|
+
promises.push(cache.invalidate().catch(() => void 0));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
await Promise.all(promises);
|
|
94
|
+
}
|
|
86
95
|
};
|
|
87
96
|
var AsyncValueCache = class {
|
|
88
97
|
constructor(fetcher, _options = {}) {
|
|
@@ -139,21 +148,20 @@ var AsyncValueCache = class {
|
|
|
139
148
|
return this._setAsync(value);
|
|
140
149
|
}
|
|
141
150
|
/**
|
|
142
|
-
*
|
|
151
|
+
* If anyone is listening to the cache, refreshes the value, and sets it without invalidating the cache.
|
|
143
152
|
*/
|
|
144
153
|
async refresh() {
|
|
145
|
-
|
|
154
|
+
if (this._subscriptionsCount > 0) {
|
|
155
|
+
await this.getOrWait("write-only");
|
|
156
|
+
}
|
|
146
157
|
}
|
|
147
158
|
/**
|
|
148
|
-
* Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read).
|
|
149
|
-
* it will refresh immediately.
|
|
159
|
+
* Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read). It will refresh immediately.
|
|
150
160
|
*/
|
|
151
|
-
invalidate() {
|
|
161
|
+
async invalidate() {
|
|
152
162
|
this._store.setUnavailable();
|
|
153
163
|
this._pendingPromise = void 0;
|
|
154
|
-
|
|
155
|
-
(0, import_promises.runAsynchronously)(this.refresh());
|
|
156
|
-
}
|
|
164
|
+
await this.refresh();
|
|
157
165
|
}
|
|
158
166
|
isDirty() {
|
|
159
167
|
return this._pendingPromise === void 0;
|
|
@@ -178,7 +186,7 @@ var AsyncValueCache = class {
|
|
|
178
186
|
(0, import_promises.runAsynchronously)(async () => {
|
|
179
187
|
await (0, import_promises.wait)(5e3);
|
|
180
188
|
if (this._subscriptionsCount === 0 && currentRefreshPromiseIndex === this._mostRecentRefreshPromiseIndex) {
|
|
181
|
-
this.invalidate();
|
|
189
|
+
await this.invalidate();
|
|
182
190
|
}
|
|
183
191
|
});
|
|
184
192
|
for (const unsubscribe of this._unsubscribers) {
|
package/dist/utils/caches.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/caches.tsx"],"sourcesContent":["import { DependenciesMap } from \"./maps\";\nimport { filterUndefined } from \"./objects\";\nimport { RateLimitOptions, ReactPromise, pending, rateLimited, resolved, runAsynchronously, wait } from \"./promises\";\nimport { AsyncStore } from \"./stores\";\n\n/**\n * Can be used to cache the result of a function call, for example for the `use` hook in React.\n */\nexport function cacheFunction<F extends Function>(f: F): F {\n const dependenciesMap = new DependenciesMap<any, any>();\n\n return ((...args: any) => {\n if (dependenciesMap.has(args)) {\n return dependenciesMap.get(args);\n }\n\n const value = f(...args);\n dependenciesMap.set(args, value);\n return value;\n }) as any as F;\n}\nundefined?.test(\"cacheFunction\", ({ expect }) => {\n // Test with a simple function\n let callCount = 0;\n const add = (a: number, b: number) => {\n callCount++;\n return a + b;\n };\n\n const cachedAdd = cacheFunction(add);\n\n // First call should execute the function\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Second call with same args should use cached result\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Call with different args should execute the function again\n expect(cachedAdd(2, 3)).toBe(5);\n expect(callCount).toBe(2);\n\n // Test with a function that returns objects\n let objectCallCount = 0;\n const createObject = (id: number) => {\n objectCallCount++;\n return { id };\n };\n\n const cachedCreateObject = cacheFunction(createObject);\n\n // First call should execute the function\n const obj1 = cachedCreateObject(1);\n expect(obj1).toEqual({ id: 1 });\n expect(objectCallCount).toBe(1);\n\n // Second call with same args should use cached result\n const obj2 = cachedCreateObject(1);\n expect(obj2).toBe(obj1); // Same reference\n expect(objectCallCount).toBe(1);\n});\n\n\ntype CacheStrategy = \"write-only\" | \"read-write\" | \"never\";\n\nexport class AsyncCache<D extends any[], T> {\n private readonly _map = new DependenciesMap<D, AsyncValueCache<T>>();\n\n constructor(\n private readonly _fetcher: (dependencies: D) => Promise<T>,\n private readonly _options: {\n onSubscribe?: (key: D, refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n // nothing here yet\n }\n\n private _createKeyed<FunctionName extends keyof AsyncValueCache<T>>(\n functionName: FunctionName,\n ): (key: D, ...args: Parameters<AsyncValueCache<T>[FunctionName]>) => ReturnType<AsyncValueCache<T>[FunctionName]> {\n return (key: D, ...args) => {\n const valueCache = this.getValueCache(key);\n return (valueCache[functionName] as any).apply(valueCache, args);\n };\n }\n\n getValueCache(dependencies: D): AsyncValueCache<T> {\n let cache = this._map.get(dependencies);\n if (!cache) {\n cache = new AsyncValueCache(\n async () => await this._fetcher(dependencies),\n {\n ...this._options,\n onSubscribe: this._options.onSubscribe ? (cb) => this._options.onSubscribe!(dependencies, cb) : undefined,\n },\n );\n this._map.set(dependencies, cache);\n }\n return cache;\n }\n\n async refreshWhere(predicate: (dependencies: D) => boolean) {\n const promises: Promise<T>[] = [];\n for (const [dependencies, cache] of this._map) {\n if (predicate(dependencies)) {\n promises.push(cache.refresh());\n }\n }\n await Promise.all(promises);\n }\n\n readonly isCacheAvailable = this._createKeyed(\"isCacheAvailable\");\n readonly getIfCached = this._createKeyed(\"getIfCached\");\n readonly getOrWait = this._createKeyed(\"getOrWait\");\n readonly forceSetCachedValue = this._createKeyed(\"forceSetCachedValue\");\n readonly forceSetCachedValueAsync = this._createKeyed(\"forceSetCachedValueAsync\");\n readonly refresh = this._createKeyed(\"refresh\");\n readonly invalidate = this._createKeyed(\"invalidate\");\n readonly onStateChange = this._createKeyed(\"onStateChange\");\n readonly isDirty = this._createKeyed(\"isDirty\");\n}\n\nclass AsyncValueCache<T> {\n private _store: AsyncStore<T>;\n private _pendingPromise: ReactPromise<T> | undefined;\n private _fetcher: () => Promise<T>;\n private readonly _rateLimitOptions: Omit<RateLimitOptions, \"batchCalls\">;\n private _subscriptionsCount = 0;\n private _unsubscribers: (() => void)[] = [];\n private _mostRecentRefreshPromiseIndex = 0;\n\n constructor(\n fetcher: () => Promise<T>,\n private readonly _options: {\n onSubscribe?: (refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n this._store = new AsyncStore();\n this._rateLimitOptions = {\n concurrency: 1,\n throttleMs: 300,\n ...filterUndefined(_options.rateLimiter ?? {}),\n };\n\n\n this._fetcher = rateLimited(fetcher, {\n ...this._rateLimitOptions,\n batchCalls: true,\n });\n }\n\n isCacheAvailable(): boolean {\n return this._store.isAvailable();\n }\n\n getIfCached() {\n return this._store.get();\n }\n\n getOrWait(cacheStrategy: CacheStrategy): ReactPromise<T> {\n const cached = this.getIfCached();\n if (cacheStrategy === \"read-write\" && cached.status === \"ok\") {\n return resolved(cached.data);\n }\n\n return this._refetch(cacheStrategy);\n }\n\n private _set(value: T): void {\n this._store.set(value);\n }\n\n private _setAsync(value: Promise<T>): ReactPromise<boolean> {\n const promise = pending(value);\n this._pendingPromise = promise;\n return pending(this._store.setAsync(promise));\n }\n\n private _refetch(cacheStrategy: CacheStrategy): ReactPromise<T> {\n if (cacheStrategy === \"read-write\" && this._pendingPromise) {\n return this._pendingPromise;\n }\n const promise = pending(this._fetcher());\n if (cacheStrategy === \"never\") {\n return promise;\n }\n return pending(this._setAsync(promise).then(() => promise));\n }\n\n forceSetCachedValue(value: T): void {\n this._set(value);\n }\n\n forceSetCachedValueAsync(value: Promise<T>): ReactPromise<boolean> {\n return this._setAsync(value);\n }\n\n /**\n * Refetches the value from the fetcher, and updates the cache with it.\n */\n async refresh(): Promise<T> {\n return await this.getOrWait(\"write-only\");\n }\n\n /**\n * Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read). If anyone was listening to it,\n * it will refresh immediately.\n */\n invalidate(): void {\n this._store.setUnavailable();\n this._pendingPromise = undefined;\n if (this._subscriptionsCount > 0) {\n runAsynchronously(this.refresh());\n }\n }\n\n isDirty(): boolean {\n return this._pendingPromise === undefined;\n }\n\n onStateChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {\n const storeObj = this._store.onChange(callback);\n\n runAsynchronously(this.getOrWait(\"read-write\"));\n\n if (this._subscriptionsCount++ === 0 && this._options.onSubscribe) {\n const unsubscribe = this._options.onSubscribe(() => {\n runAsynchronously(this.refresh());\n });\n this._unsubscribers.push(unsubscribe);\n }\n\n let hasUnsubscribed = false;\n return {\n unsubscribe: () => {\n if (hasUnsubscribed) return;\n hasUnsubscribed = true;\n storeObj.unsubscribe();\n if (--this._subscriptionsCount === 0) {\n const currentRefreshPromiseIndex = ++this._mostRecentRefreshPromiseIndex;\n runAsynchronously(async () => {\n // wait a few seconds; if anything changes during that time, we don't want to refresh\n // else we do unnecessary requests if we unsubscribe and then subscribe again immediately\n await wait(5000);\n if (this._subscriptionsCount === 0 && currentRefreshPromiseIndex === this._mostRecentRefreshPromiseIndex) {\n this.invalidate();\n }\n });\n\n for (const unsubscribe of this._unsubscribers) {\n unsubscribe();\n }\n }\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAgC;AAChC,qBAAgC;AAChC,sBAAwG;AACxG,oBAA2B;AAKpB,SAAS,cAAkC,GAAS;AACzD,QAAM,kBAAkB,IAAI,4BAA0B;AAEtD,SAAQ,IAAI,SAAc;AACxB,QAAI,gBAAgB,IAAI,IAAI,GAAG;AAC7B,aAAO,g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,KAAK,gBAAgB;AAC7C,wBAAY;AAAA,UACd;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/caches.tsx"],"sourcesContent":["import { DependenciesMap } from \"./maps\";\nimport { filterUndefined } from \"./objects\";\nimport { RateLimitOptions, ReactPromise, pending, rateLimited, resolved, runAsynchronously, wait } from \"./promises\";\nimport { AsyncStore } from \"./stores\";\n\n/**\n * Can be used to cache the result of a function call, for example for the `use` hook in React.\n */\nexport function cacheFunction<F extends Function>(f: F): F {\n const dependenciesMap = new DependenciesMap<any, any>();\n\n return ((...args: any) => {\n if (dependenciesMap.has(args)) {\n return dependenciesMap.get(args);\n }\n\n const value = f(...args);\n dependenciesMap.set(args, value);\n return value;\n }) as any as F;\n}\nundefined?.test(\"cacheFunction\", ({ expect }) => {\n // Test with a simple function\n let callCount = 0;\n const add = (a: number, b: number) => {\n callCount++;\n return a + b;\n };\n\n const cachedAdd = cacheFunction(add);\n\n // First call should execute the function\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Second call with same args should use cached result\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Call with different args should execute the function again\n expect(cachedAdd(2, 3)).toBe(5);\n expect(callCount).toBe(2);\n\n // Test with a function that returns objects\n let objectCallCount = 0;\n const createObject = (id: number) => {\n objectCallCount++;\n return { id };\n };\n\n const cachedCreateObject = cacheFunction(createObject);\n\n // First call should execute the function\n const obj1 = cachedCreateObject(1);\n expect(obj1).toEqual({ id: 1 });\n expect(objectCallCount).toBe(1);\n\n // Second call with same args should use cached result\n const obj2 = cachedCreateObject(1);\n expect(obj2).toBe(obj1); // Same reference\n expect(objectCallCount).toBe(1);\n});\n\n\ntype CacheStrategy = \"write-only\" | \"read-write\" | \"never\";\n\nexport class AsyncCache<D extends any[], T> {\n private readonly _map = new DependenciesMap<D, AsyncValueCache<T>>();\n\n constructor(\n private readonly _fetcher: (dependencies: D) => Promise<T>,\n private readonly _options: {\n onSubscribe?: (key: D, refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n // nothing here yet\n }\n\n private _createKeyed<FunctionName extends keyof AsyncValueCache<T>>(\n functionName: FunctionName,\n ): (key: D, ...args: Parameters<AsyncValueCache<T>[FunctionName]>) => ReturnType<AsyncValueCache<T>[FunctionName]> {\n return (key: D, ...args) => {\n const valueCache = this.getValueCache(key);\n return (valueCache[functionName] as any).apply(valueCache, args);\n };\n }\n\n getValueCache(dependencies: D): AsyncValueCache<T> {\n let cache = this._map.get(dependencies);\n if (!cache) {\n cache = new AsyncValueCache(\n async () => await this._fetcher(dependencies),\n {\n ...this._options,\n onSubscribe: this._options.onSubscribe ? (cb) => this._options.onSubscribe!(dependencies, cb) : undefined,\n },\n );\n this._map.set(dependencies, cache);\n }\n return cache;\n }\n\n async refreshWhere(predicate: (dependencies: D) => boolean) {\n const promises: Promise<void>[] = [];\n for (const [dependencies, cache] of this._map) {\n if (predicate(dependencies)) {\n promises.push(cache.refresh());\n }\n }\n await Promise.all(promises);\n }\n\n async invalidateWhere(predicate: (dependencies: D) => boolean) {\n const promises: Promise<void>[] = [];\n for (const [dependencies, cache] of this._map) {\n if (predicate(dependencies)) {\n promises.push(cache.invalidate().catch(() => undefined));\n }\n }\n await Promise.all(promises);\n }\n\n readonly isCacheAvailable = this._createKeyed(\"isCacheAvailable\");\n readonly getIfCached = this._createKeyed(\"getIfCached\");\n readonly getOrWait = this._createKeyed(\"getOrWait\");\n readonly forceSetCachedValue = this._createKeyed(\"forceSetCachedValue\");\n readonly forceSetCachedValueAsync = this._createKeyed(\"forceSetCachedValueAsync\");\n readonly refresh = this._createKeyed(\"refresh\");\n readonly invalidate = this._createKeyed(\"invalidate\");\n readonly onStateChange = this._createKeyed(\"onStateChange\");\n readonly isDirty = this._createKeyed(\"isDirty\");\n}\n\nclass AsyncValueCache<T> {\n private _store: AsyncStore<T>;\n private _pendingPromise: ReactPromise<T> | undefined;\n private _fetcher: () => Promise<T>;\n private readonly _rateLimitOptions: Omit<RateLimitOptions, \"batchCalls\">;\n private _subscriptionsCount = 0;\n private _unsubscribers: (() => void)[] = [];\n private _mostRecentRefreshPromiseIndex = 0;\n\n constructor(\n fetcher: () => Promise<T>,\n private readonly _options: {\n onSubscribe?: (refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n this._store = new AsyncStore();\n this._rateLimitOptions = {\n concurrency: 1,\n throttleMs: 300,\n ...filterUndefined(_options.rateLimiter ?? {}),\n };\n\n\n this._fetcher = rateLimited(fetcher, {\n ...this._rateLimitOptions,\n batchCalls: true,\n });\n }\n\n isCacheAvailable(): boolean {\n return this._store.isAvailable();\n }\n\n getIfCached() {\n return this._store.get();\n }\n\n getOrWait(cacheStrategy: CacheStrategy): ReactPromise<T> {\n const cached = this.getIfCached();\n if (cacheStrategy === \"read-write\" && cached.status === \"ok\") {\n return resolved(cached.data);\n }\n\n return this._refetch(cacheStrategy);\n }\n\n private _set(value: T): void {\n this._store.set(value);\n }\n\n private _setAsync(value: Promise<T>): ReactPromise<boolean> {\n const promise = pending(value);\n this._pendingPromise = promise;\n return pending(this._store.setAsync(promise));\n }\n\n private _refetch(cacheStrategy: CacheStrategy): ReactPromise<T> {\n if (cacheStrategy === \"read-write\" && this._pendingPromise) {\n return this._pendingPromise;\n }\n const promise = pending(this._fetcher());\n if (cacheStrategy === \"never\") {\n return promise;\n }\n return pending(this._setAsync(promise).then(() => promise));\n }\n\n forceSetCachedValue(value: T): void {\n this._set(value);\n }\n\n forceSetCachedValueAsync(value: Promise<T>): ReactPromise<boolean> {\n return this._setAsync(value);\n }\n\n /**\n * If anyone is listening to the cache, refreshes the value, and sets it without invalidating the cache.\n */\n async refresh(): Promise<void> {\n if (this._subscriptionsCount > 0) {\n await this.getOrWait(\"write-only\");\n }\n }\n\n /**\n * Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read). It will refresh immediately.\n */\n async invalidate(): Promise<void> {\n this._store.setUnavailable();\n this._pendingPromise = undefined;\n await this.refresh();\n }\n\n isDirty(): boolean {\n return this._pendingPromise === undefined;\n }\n\n onStateChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {\n const storeObj = this._store.onChange(callback);\n\n runAsynchronously(this.getOrWait(\"read-write\"));\n\n if (this._subscriptionsCount++ === 0 && this._options.onSubscribe) {\n const unsubscribe = this._options.onSubscribe(() => {\n runAsynchronously(this.refresh());\n });\n this._unsubscribers.push(unsubscribe);\n }\n\n let hasUnsubscribed = false;\n return {\n unsubscribe: () => {\n if (hasUnsubscribed) return;\n hasUnsubscribed = true;\n storeObj.unsubscribe();\n if (--this._subscriptionsCount === 0) {\n const currentRefreshPromiseIndex = ++this._mostRecentRefreshPromiseIndex;\n runAsynchronously(async () => {\n // wait a few seconds; we want to keep the cache up during this time\n // else we do unnecessary requests if we unsubscribe and then subscribe again immediately\n await wait(5000);\n if (this._subscriptionsCount === 0 && currentRefreshPromiseIndex === this._mostRecentRefreshPromiseIndex) {\n await this.invalidate();\n }\n });\n\n for (const unsubscribe of this._unsubscribers) {\n unsubscribe();\n }\n }\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAgC;AAChC,qBAAgC;AAChC,sBAAwG;AACxG,oBAA2B;AAKpB,SAAS,cAAkC,GAAS;AACzD,QAAM,kBAAkB,IAAI,4BAA0B;AAEtD,SAAQ,IAAI,SAAc;AACxB,QAAI,gBAAgB,IAAI,IAAI,GAAG;AAC7B,aAAO,gBAAgB,IAAI,IAAI;AAAA,IACjC;AAEA,UAAM,QAAQ,EAAE,GAAG,IAAI;AACvB,oBAAgB,IAAI,MAAM,KAAK;AAC/B,WAAO;AAAA,EACT;AACF;AA8CO,IAAM,aAAN,MAAqC;AAAA,EAG1C,YACmB,UACA,WA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AAgC;AACxG,oBAAM,KAAK,WAAW;AAAA,YACxB;AAAA,UACF,CAAC;AAED,qBAAW,eAAe,KAAK,gBAAgB;AAC7C,wBAAY;AAAA,UACd;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/utils/ips.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
type Ipv4Address = `${number}.${number}.${number}.${number}`;
|
|
2
2
|
type Ipv6Address = string;
|
|
3
|
-
declare function isIpAddress(ip: string):
|
|
3
|
+
declare function isIpAddress(ip: string): boolean;
|
|
4
4
|
declare function assertIpAddress(ip: string): asserts ip is Ipv4Address | Ipv6Address;
|
|
5
5
|
|
|
6
6
|
export { type Ipv4Address, type Ipv6Address, assertIpAddress, isIpAddress };
|
package/dist/utils/ips.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
type Ipv4Address = `${number}.${number}.${number}.${number}`;
|
|
2
2
|
type Ipv6Address = string;
|
|
3
|
-
declare function isIpAddress(ip: string):
|
|
3
|
+
declare function isIpAddress(ip: string): boolean;
|
|
4
4
|
declare function assertIpAddress(ip: string): asserts ip is Ipv4Address | Ipv6Address;
|
|
5
5
|
|
|
6
6
|
export { type Ipv4Address, type Ipv6Address, assertIpAddress, isIpAddress };
|
package/dist/utils/ips.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/ips.tsx"],"sourcesContent":["import ipRegex from \"ip-regex\";\n\nexport type Ipv4Address = `${number}.${number}.${number}.${number}`;\nexport type Ipv6Address = string;\n\nexport function isIpAddress(ip: string)
|
|
1
|
+
{"version":3,"sources":["../../src/utils/ips.tsx"],"sourcesContent":["import ipRegex from \"ip-regex\";\n\nexport type Ipv4Address = `${number}.${number}.${number}.${number}`;\nexport type Ipv6Address = string;\n\nexport function isIpAddress(ip: string) {\n return ipRegex({ exact: true }).test(ip);\n}\nundefined?.test(\"isIpAddress\", ({ expect }) => {\n // Test valid IPv4 addresses\n expect(isIpAddress(\"192.168.1.1\")).toBe(true);\n expect(isIpAddress(\"127.0.0.1\")).toBe(true);\n expect(isIpAddress(\"0.0.0.0\")).toBe(true);\n expect(isIpAddress(\"255.255.255.255\")).toBe(true);\n\n // Test valid IPv6 addresses\n expect(isIpAddress(\"::1\")).toBe(true);\n expect(isIpAddress(\"2001:db8::\")).toBe(true);\n expect(isIpAddress(\"2001:db8:85a3:8d3:1319:8a2e:370:7348\")).toBe(true);\n\n // Test invalid IP addresses\n expect(isIpAddress(\"\")).toBe(false);\n expect(isIpAddress(\"not an ip\")).toBe(false);\n expect(isIpAddress(\"256.256.256.256\")).toBe(false);\n expect(isIpAddress(\"192.168.1\")).toBe(false);\n expect(isIpAddress(\"192.168.1.1.1\")).toBe(false);\n expect(isIpAddress(\"2001:db8::xyz\")).toBe(false);\n});\n\nexport function assertIpAddress(ip: string): asserts ip is Ipv4Address | Ipv6Address {\n if (!isIpAddress(ip)) {\n throw new Error(`Invalid IP address: ${ip}`);\n }\n}\nundefined?.test(\"assertIpAddress\", ({ expect }) => {\n // Test with valid IPv4 address\n expect(() => assertIpAddress(\"192.168.1.1\")).not.toThrow();\n\n // Test with valid IPv6 address\n expect(() => assertIpAddress(\"::1\")).not.toThrow();\n\n // Test with invalid IP addresses\n expect(() => assertIpAddress(\"\")).toThrow(\"Invalid IP address: \");\n expect(() => assertIpAddress(\"not an ip\")).toThrow(\"Invalid IP address: not an ip\");\n expect(() => assertIpAddress(\"256.256.256.256\")).toThrow(\"Invalid IP address: 256.256.256.256\");\n expect(() => assertIpAddress(\"192.168.1\")).toThrow(\"Invalid IP address: 192.168.1\");\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAoB;AAKb,SAAS,YAAY,IAAY;AACtC,aAAO,gBAAAA,SAAQ,EAAE,OAAO,KAAK,CAAC,EAAE,KAAK,EAAE;AACzC;AAsBO,SAAS,gBAAgB,IAAqD;AACnF,MAAI,CAAC,YAAY,EAAE,GAAG;AACpB,UAAM,IAAI,MAAM,uBAAuB,EAAE,EAAE;AAAA,EAC7C;AACF;","names":["ipRegex"]}
|
package/dist/utils/urls.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/urls.tsx"],"sourcesContent":["import { generateSecureRandomString } from \"./crypto\";\nimport { templateIdentity } from \"./strings\";\n\nexport function createUrlIfValid(...args: ConstructorParameters<typeof URL>) {\n try {\n return new URL(...args);\n } catch (e) {\n return null;\n }\n}\nundefined?.test(\"createUrlIfValid\", ({ expect }) => {\n // Test with valid URLs\n expect(createUrlIfValid(\"https://example.com\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"https://example.com/path?query=value#hash\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"/path\", \"https://example.com\")).toBeInstanceOf(URL);\n\n // Test with invalid URLs\n expect(createUrlIfValid(\"\")).toBeNull();\n expect(createUrlIfValid(\"not a url\")).toBeNull();\n expect(createUrlIfValid(\"http://\")).toBeNull();\n});\n\nexport function isValidUrl(url: string) {\n return !!createUrlIfValid(url);\n}\nundefined?.test(\"isValidUrl\", ({ expect }) => {\n // Test with valid URLs\n expect(isValidUrl(\"https://example.com\")).toBe(true);\n expect(isValidUrl(\"http://localhost:3000\")).toBe(true);\n expect(isValidUrl(\"ftp://example.com\")).toBe(true);\n\n // Test with invalid URLs\n expect(isValidUrl(\"\")).toBe(false);\n expect(isValidUrl(\"not a url\")).toBe(false);\n expect(isValidUrl(\"http://\")).toBe(false);\n});\n\nexport function isValidHostname(hostname: string) {\n // Basic validation\n if (!hostname || hostname.startsWith('.') || hostname.endsWith('.') || hostname.includes('..')) {\n return false;\n }\n\n const url = createUrlIfValid(`https://${hostname}`);\n if (!url) return false;\n return url.hostname === hostname;\n}\nundefined?.test(\"isValidHostname\", ({ expect }) => {\n // Test with valid hostnames\n expect(isValidHostname(\"example.com\")).toBe(true);\n expect(isValidHostname(\"localhost\")).toBe(true);\n expect(isValidHostname(\"sub.domain.example.com\")).toBe(true);\n expect(isValidHostname(\"127.0.0.1\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostname(\"\")).toBe(false);\n expect(isValidHostname(\"example.com/path\")).toBe(false);\n expect(isValidHostname(\"https://example.com\")).toBe(false);\n expect(isValidHostname(\"example com\")).toBe(false);\n});\n\nexport function isValidHostnameWithWildcards(hostname: string) {\n // Empty hostnames are invalid\n if (!hostname) return false;\n\n // Check if it contains wildcards\n const hasWildcard = hostname.includes('*');\n\n if (!hasWildcard) {\n // If no wildcards, validate as a normal hostname\n return isValidHostname(hostname);\n }\n\n // Basic validation checks that apply even with wildcards\n // - Hostname cannot start or end with a dot\n if (hostname.startsWith('.') || hostname.endsWith('.')) {\n return false;\n }\n\n // - No consecutive dots\n if (hostname.includes('..')) {\n return false;\n }\n\n // For wildcard validation, check that non-wildcard parts contain valid characters\n // Replace wildcards with a valid placeholder to check the rest\n const testHostname = hostname.replace(/\\*+/g, 'wildcard');\n\n // Check if the resulting string would be a valid hostname\n if (!/^[a-zA-Z0-9.-]+$/.test(testHostname)) {\n return false;\n }\n\n // Additional check: ensure the pattern makes sense\n // Check each segment between wildcards\n const segments = hostname.split(/\\*+/);\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (segment === '') continue; // Empty segments are OK (consecutive wildcards)\n\n // First segment can't start with dot\n if (i === 0 && segment.startsWith('.')) {\n return false;\n }\n\n // Last segment can't end with dot\n if (i === segments.length - 1 && segment.endsWith('.')) {\n return false;\n }\n\n // No segment should have consecutive dots\n if (segment.includes('..')) {\n return false;\n }\n }\n\n return true;\n}\nundefined?.test(\"isValidHostnameWithWildcards\", ({ expect }) => {\n // Test with valid regular hostnames\n expect(isValidHostnameWithWildcards(\"example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"localhost\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.domain.example.com\")).toBe(true);\n\n // Test with valid wildcard hostnames\n expect(isValidHostnameWithWildcards(\"*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"a-*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*.*.org\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"**.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.**.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*-api.*.com\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostnameWithWildcards(\"\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com/path\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"https://example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\".example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com.\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example..com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"*.example..com\")).toBe(false);\n});\n\nexport function matchHostnamePattern(pattern: string, hostname: string): boolean {\n // If no wildcards, it's an exact match\n if (!pattern.includes('*')) {\n return pattern === hostname;\n }\n\n // Convert the pattern to a regex\n // First, escape all regex special characters except *\n let regexPattern = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n // Use a placeholder for ** to handle it separately from single *\n const doubleWildcardPlaceholder = '\\x00DOUBLE_WILDCARD\\x00';\n regexPattern = regexPattern.replace(/\\*\\*/g, doubleWildcardPlaceholder);\n\n // Replace single * with a pattern that matches anything except dots\n regexPattern = regexPattern.replace(/\\*/g, '[^.]*');\n\n // Replace the double wildcard placeholder with a pattern that matches anything including dots\n regexPattern = regexPattern.replace(new RegExp(doubleWildcardPlaceholder, 'g'), '.*');\n\n // Anchor the pattern to match the entire hostname\n regexPattern = '^' + regexPattern + '$';\n\n try {\n const regex = new RegExp(regexPattern);\n return regex.test(hostname);\n } catch {\n return false;\n }\n}\nundefined?.test(\"matchHostnamePattern\", ({ expect }) => {\n // Test exact matches\n expect(matchHostnamePattern(\"example.com\", \"example.com\")).toBe(true);\n expect(matchHostnamePattern(\"example.com\", \"other.com\")).toBe(false);\n\n // Test single wildcard matches\n expect(matchHostnamePattern(\"*.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"www.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.example.com\", \"api.v2.example.com\")).toBe(false);\n\n // Test double wildcard matches\n expect(matchHostnamePattern(\"**.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"api.v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"a.b.c.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"example.com\")).toBe(false);\n\n // Test complex patterns\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v1.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api.example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.*.org\", \"mail.example.org\")).toBe(true);\n expect(matchHostnamePattern(\"*.*.org\", \"example.org\")).toBe(false);\n});\n\nexport function isLocalhost(urlOrString: string | URL) {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n if (url.hostname === \"localhost\" || url.hostname.endsWith(\".localhost\")) return true;\n if (url.hostname.match(/^127\\.\\d+\\.\\d+\\.\\d+$/)) return true;\n return false;\n}\nundefined?.test(\"isLocalhost\", ({ expect }) => {\n // Test with localhost URLs\n expect(isLocalhost(\"http://localhost\")).toBe(true);\n expect(isLocalhost(\"https://localhost:8080\")).toBe(true);\n expect(isLocalhost(\"http://sub.localhost\")).toBe(true);\n expect(isLocalhost(\"http://127.0.0.1\")).toBe(true);\n expect(isLocalhost(\"http://127.1.2.3\")).toBe(true);\n\n // Test with non-localhost URLs\n expect(isLocalhost(\"https://example.com\")).toBe(false);\n expect(isLocalhost(\"http://192.168.1.1\")).toBe(false);\n expect(isLocalhost(\"http://10.0.0.1\")).toBe(false);\n\n // Test with URL objects\n expect(isLocalhost(new URL(\"http://localhost\"))).toBe(true);\n expect(isLocalhost(new URL(\"https://example.com\"))).toBe(false);\n\n // Test with invalid URLs\n expect(isLocalhost(\"not a url\")).toBe(false);\n expect(isLocalhost(\"\")).toBe(false);\n});\n\nexport function isRelative(url: string) {\n const randomDomain = `${generateSecureRandomString()}.stack-auth.example.com`;\n const u = createUrlIfValid(url, `https://${randomDomain}`);\n if (!u) return false;\n if (u.host !== randomDomain) return false;\n if (u.protocol !== \"https:\") return false;\n return true;\n}\nundefined?.test(\"isRelative\", ({ expect }) => {\n // We can't easily mock generateSecureRandomString in this context\n // but we can still test the function's behavior\n\n // Test with relative URLs\n expect(isRelative(\"/\")).toBe(true);\n expect(isRelative(\"/path\")).toBe(true);\n expect(isRelative(\"/path?query=value#hash\")).toBe(true);\n\n // Test with absolute URLs\n expect(isRelative(\"https://example.com\")).toBe(false);\n expect(isRelative(\"http://example.com\")).toBe(false);\n expect(isRelative(\"//example.com\")).toBe(false);\n\n // Note: The implementation treats empty strings and invalid URLs as relative\n // This is because they can be resolved against a base URL\n expect(isRelative(\"\")).toBe(true);\n expect(isRelative(\"not a url\")).toBe(true);\n});\n\nexport function getRelativePart(url: URL) {\n return url.pathname + url.search + url.hash;\n}\nundefined?.test(\"getRelativePart\", ({ expect }) => {\n // Test with various URLs\n expect(getRelativePart(new URL(\"https://example.com\"))).toBe(\"/\");\n expect(getRelativePart(new URL(\"https://example.com/path\"))).toBe(\"/path\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value\"))).toBe(\"/path?query=value\");\n expect(getRelativePart(new URL(\"https://example.com/path#hash\"))).toBe(\"/path#hash\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value#hash\"))).toBe(\"/path?query=value#hash\");\n\n // Test with different domains but same paths\n const url1 = new URL(\"https://example.com/path?query=value#hash\");\n const url2 = new URL(\"https://different.com/path?query=value#hash\");\n expect(getRelativePart(url1)).toBe(getRelativePart(url2));\n});\n\n/**\n * A template literal tag that returns a URL.\n *\n * Any values passed are encoded.\n */\nexport function url(strings: TemplateStringsArray | readonly string[], ...values: (string|number|boolean)[]): URL {\n return new URL(urlString(strings, ...values));\n}\nundefined?.test(\"url\", ({ expect }) => {\n // Test with no interpolation\n expect(url`https://example.com`).toBeInstanceOf(URL);\n expect(url`https://example.com`.href).toBe(\"https://example.com/\");\n\n // Test with string interpolation\n expect(url`https://example.com/${\"path\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}`.pathname).toBe(\"/path\");\n\n // Test with number interpolation\n expect(url`https://example.com/${42}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${42}`.pathname).toBe(\"/42\");\n\n // Test with boolean interpolation\n expect(url`https://example.com/${true}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${true}`.pathname).toBe(\"/true\");\n\n // Test with special characters in interpolation\n expect(url`https://example.com/${\"path with spaces\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path with spaces\"}`.pathname).toBe(\"/path%20with%20spaces\");\n\n // Test with multiple interpolations\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.pathname).toBe(\"/path\");\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.search).toBe(\"?query=value\");\n});\n\n\n/**\n * A template literal tag that returns a URL string.\n *\n * Any values passed are encoded.\n */\nexport function urlString(strings: TemplateStringsArray | readonly string[], ...values: (string|number|boolean)[]): string {\n return templateIdentity(strings, ...values.map(encodeURIComponent));\n}\nundefined?.test(\"urlString\", ({ expect }) => {\n // Test with no interpolation\n expect(urlString`https://example.com`).toBe(\"https://example.com\");\n\n // Test with string interpolation\n expect(urlString`https://example.com/${\"path\"}`).toBe(\"https://example.com/path\");\n\n // Test with number interpolation\n expect(urlString`https://example.com/${42}`).toBe(\"https://example.com/42\");\n\n // Test with boolean interpolation\n expect(urlString`https://example.com/${true}`).toBe(\"https://example.com/true\");\n\n // Test with special characters in interpolation\n expect(urlString`https://example.com/${\"path with spaces\"}`).toBe(\"https://example.com/path%20with%20spaces\");\n expect(urlString`https://example.com/${\"?&=\"}`).toBe(\"https://example.com/%3F%26%3D\");\n\n // Test with multiple interpolations\n expect(urlString`https://example.com/${\"path\"}?query=${\"value\"}`).toBe(\"https://example.com/path?query=value\");\n expect(urlString`https://example.com/${\"path\"}?query=${\"value with spaces\"}`).toBe(\"https://example.com/path?query=value%20with%20spaces\");\n});\n\nexport function isChildUrl(parentUrl: URL, maybeChildUrl: URL) {\n return parentUrl.origin === maybeChildUrl.origin\n && isChildPath(parentUrl.pathname, maybeChildUrl.pathname)\n && [...parentUrl.searchParams].every(([key, value]) => maybeChildUrl.searchParams.get(key) === value)\n && (!parentUrl.hash || parentUrl.hash === maybeChildUrl.hash);\n}\nundefined?.test(\"isChildUrl\", ({ expect }) => {\n // true\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(true);\n\n // false\n expect(isChildUrl(new URL(\"https://abc.com\"), new URL(\"https://example.com\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com?query=value123\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n});\n\nexport function isChildPath(parentPath: string, maybeChildPath: string) {\n parentPath = parentPath.endsWith(\"/\") ? parentPath : parentPath + \"/\";\n maybeChildPath = maybeChildPath.endsWith(\"/\") ? maybeChildPath : maybeChildPath + \"/\";\n return maybeChildPath.startsWith(parentPath);\n}\nundefined?.test(\"isSubPath\", ({ expect }) => {\n expect(isChildPath(\"/\", \"/\")).toBe(true);\n expect(isChildPath(\"/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path-abc/\")).toBe(false);\n expect(isChildPath(\"/path/\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path/\", \"/path-abc/\")).toBe(false);\n});\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2C;AAC3C,qBAAiC;AAE1B,SAAS,oBAAoB,MAAyC;AAC3E,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,IAAI;AAAA,EACxB,SAAS,GAAG;AACV,WAAO;AAAA,EACT;AACF;AAaO,SAAS,WAAWA,MAAa;AACtC,SAAO,CAAC,CAAC,iBAAiBA,IAAG;AAC/B;AAaO,SAAS,gBAAgB,UAAkB;AAEhD,MAAI,CAAC,YA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AQ,UAAU,SAAS,cAAc;AAC5D;AAiBO,SAAS,YAAY,YAAoB,gBAAwB;AACtE,eAAa,WAAW,SAAS,GAAG,IAAI,aAAa,aAAa;AAClE,mBAAiB,eAAe,SAAS,GAAG,IAAI,iBAAiB,iBAAiB;AAClF,SAAO,eAAe,WAAW,UAAU;AAC7C;","names":["url"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/urls.tsx"],"sourcesContent":["import { generateSecureRandomString } from \"./crypto\";\nimport { templateIdentity } from \"./strings\";\n\nexport function createUrlIfValid(...args: ConstructorParameters<typeof URL>) {\n try {\n return new URL(...args);\n } catch (e) {\n return null;\n }\n}\nundefined?.test(\"createUrlIfValid\", ({ expect }) => {\n // Test with valid URLs\n expect(createUrlIfValid(\"https://example.com\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"https://example.com/path?query=value#hash\")).toBeInstanceOf(URL);\n expect(createUrlIfValid(\"/path\", \"https://example.com\")).toBeInstanceOf(URL);\n\n // Test with invalid URLs\n expect(createUrlIfValid(\"\")).toBeNull();\n expect(createUrlIfValid(\"not a url\")).toBeNull();\n expect(createUrlIfValid(\"http://\")).toBeNull();\n});\n\nexport function isValidUrl(url: string) {\n return !!createUrlIfValid(url);\n}\nundefined?.test(\"isValidUrl\", ({ expect }) => {\n // Test with valid URLs\n expect(isValidUrl(\"https://example.com\")).toBe(true);\n expect(isValidUrl(\"http://localhost:3000\")).toBe(true);\n expect(isValidUrl(\"ftp://example.com\")).toBe(true);\n\n // Test with invalid URLs\n expect(isValidUrl(\"\")).toBe(false);\n expect(isValidUrl(\"not a url\")).toBe(false);\n expect(isValidUrl(\"http://\")).toBe(false);\n});\n\nexport function isValidHostname(hostname: string) {\n // Basic validation\n if (!hostname || hostname.startsWith('.') || hostname.endsWith('.') || hostname.includes('..')) {\n return false;\n }\n\n const url = createUrlIfValid(`https://${hostname}`);\n if (!url) return false;\n return url.hostname === hostname;\n}\nundefined?.test(\"isValidHostname\", ({ expect }) => {\n // Test with valid hostnames\n expect(isValidHostname(\"example.com\")).toBe(true);\n expect(isValidHostname(\"localhost\")).toBe(true);\n expect(isValidHostname(\"sub.domain.example.com\")).toBe(true);\n expect(isValidHostname(\"127.0.0.1\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostname(\"\")).toBe(false);\n expect(isValidHostname(\"example.com/path\")).toBe(false);\n expect(isValidHostname(\"https://example.com\")).toBe(false);\n expect(isValidHostname(\"example com\")).toBe(false);\n});\n\nexport function isValidHostnameWithWildcards(hostname: string) {\n // Empty hostnames are invalid\n if (!hostname) return false;\n\n // Check if it contains wildcards\n const hasWildcard = hostname.includes('*');\n\n if (!hasWildcard) {\n // If no wildcards, validate as a normal hostname\n return isValidHostname(hostname);\n }\n\n // Basic validation checks that apply even with wildcards\n // - Hostname cannot start or end with a dot\n if (hostname.startsWith('.') || hostname.endsWith('.')) {\n return false;\n }\n\n // - No consecutive dots\n if (hostname.includes('..')) {\n return false;\n }\n\n // For wildcard validation, check that non-wildcard parts contain valid characters\n // Replace wildcards with a valid placeholder to check the rest\n const testHostname = hostname.replace(/\\*+/g, 'wildcard');\n\n // Check if the resulting string would be a valid hostname\n if (!/^[a-zA-Z0-9.-]+$/.test(testHostname)) {\n return false;\n }\n\n // Additional check: ensure the pattern makes sense\n // Check each segment between wildcards\n const segments = hostname.split(/\\*+/);\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (segment === '') continue; // Empty segments are OK (consecutive wildcards)\n\n // First segment can't start with dot\n if (i === 0 && segment.startsWith('.')) {\n return false;\n }\n\n // Last segment can't end with dot\n if (i === segments.length - 1 && segment.endsWith('.')) {\n return false;\n }\n\n // No segment should have consecutive dots\n if (segment.includes('..')) {\n return false;\n }\n }\n\n return true;\n}\nundefined?.test(\"isValidHostnameWithWildcards\", ({ expect }) => {\n // Test with valid regular hostnames\n expect(isValidHostnameWithWildcards(\"example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"localhost\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.domain.example.com\")).toBe(true);\n\n // Test with valid wildcard hostnames\n expect(isValidHostnameWithWildcards(\"*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"a-*.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*.*.org\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"**.example.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"sub.**.com\")).toBe(true);\n expect(isValidHostnameWithWildcards(\"*-api.*.com\")).toBe(true);\n\n // Test with invalid hostnames\n expect(isValidHostnameWithWildcards(\"\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com/path\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"https://example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\".example.com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example.com.\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"example..com\")).toBe(false);\n expect(isValidHostnameWithWildcards(\"*.example..com\")).toBe(false);\n});\n\nexport function matchHostnamePattern(pattern: string, hostname: string): boolean {\n // If no wildcards, it's an exact match\n if (!pattern.includes('*')) {\n return pattern === hostname;\n }\n\n // Convert the pattern to a regex\n // First, escape all regex special characters except *\n let regexPattern = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n // Use a placeholder for ** to handle it separately from single *\n const doubleWildcardPlaceholder = '\\x00DOUBLE_WILDCARD\\x00';\n regexPattern = regexPattern.replace(/\\*\\*/g, doubleWildcardPlaceholder);\n\n // Replace single * with a pattern that matches anything except dots\n regexPattern = regexPattern.replace(/\\*/g, '[^.]*');\n\n // Replace the double wildcard placeholder with a pattern that matches anything including dots\n regexPattern = regexPattern.replace(new RegExp(doubleWildcardPlaceholder, 'g'), '.*');\n\n // Anchor the pattern to match the entire hostname\n regexPattern = '^' + regexPattern + '$';\n\n try {\n const regex = new RegExp(regexPattern);\n return regex.test(hostname);\n } catch {\n return false;\n }\n}\nundefined?.test(\"matchHostnamePattern\", ({ expect }) => {\n // Test exact matches\n expect(matchHostnamePattern(\"example.com\", \"example.com\")).toBe(true);\n expect(matchHostnamePattern(\"example.com\", \"other.com\")).toBe(false);\n\n // Test single wildcard matches\n expect(matchHostnamePattern(\"*.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"www.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"*.example.com\", \"example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.example.com\", \"api.v2.example.com\")).toBe(false);\n\n // Test double wildcard matches\n expect(matchHostnamePattern(\"**.example.com\", \"api.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"api.v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"a.b.c.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"**.example.com\", \"example.com\")).toBe(false);\n\n // Test complex patterns\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v1.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api-v2.example.com\")).toBe(true);\n expect(matchHostnamePattern(\"api-*.example.com\", \"api.example.com\")).toBe(false);\n expect(matchHostnamePattern(\"*.*.org\", \"mail.example.org\")).toBe(true);\n expect(matchHostnamePattern(\"*.*.org\", \"example.org\")).toBe(false);\n});\n\nexport function isLocalhost(urlOrString: string | URL) {\n const url = createUrlIfValid(urlOrString);\n if (!url) return false;\n if (url.hostname === \"localhost\" || url.hostname.endsWith(\".localhost\")) return true;\n if (url.hostname.match(/^127\\.\\d+\\.\\d+\\.\\d+$/)) return true;\n return false;\n}\nundefined?.test(\"isLocalhost\", ({ expect }) => {\n // Test with localhost URLs\n expect(isLocalhost(\"http://localhost\")).toBe(true);\n expect(isLocalhost(\"https://localhost:8080\")).toBe(true);\n expect(isLocalhost(\"http://sub.localhost\")).toBe(true);\n expect(isLocalhost(\"http://127.0.0.1\")).toBe(true);\n expect(isLocalhost(\"http://127.1.2.3\")).toBe(true);\n\n // Test with non-localhost URLs\n expect(isLocalhost(\"https://example.com\")).toBe(false);\n expect(isLocalhost(\"http://192.168.1.1\")).toBe(false);\n expect(isLocalhost(\"http://10.0.0.1\")).toBe(false);\n\n // Test with URL objects\n expect(isLocalhost(new URL(\"http://localhost\"))).toBe(true);\n expect(isLocalhost(new URL(\"https://example.com\"))).toBe(false);\n\n // Test with invalid URLs\n expect(isLocalhost(\"not a url\")).toBe(false);\n expect(isLocalhost(\"\")).toBe(false);\n});\n\nexport function isRelative(url: string) {\n const randomDomain = `${generateSecureRandomString()}.stack-auth.example.com`;\n const u = createUrlIfValid(url, `https://${randomDomain}`);\n if (!u) return false;\n if (u.host !== randomDomain) return false;\n if (u.protocol !== \"https:\") return false;\n return true;\n}\nundefined?.test(\"isRelative\", ({ expect }) => {\n // We can't easily mock generateSecureRandomString in this context\n // but we can still test the function's behavior\n\n // Test with relative URLs\n expect(isRelative(\"/\")).toBe(true);\n expect(isRelative(\"/path\")).toBe(true);\n expect(isRelative(\"/path?query=value#hash\")).toBe(true);\n\n // Test with absolute URLs\n expect(isRelative(\"https://example.com\")).toBe(false);\n expect(isRelative(\"http://example.com\")).toBe(false);\n expect(isRelative(\"//example.com\")).toBe(false);\n\n // Note: The implementation treats empty strings and invalid URLs as relative\n // This is because they can be resolved against a base URL\n expect(isRelative(\"\")).toBe(true);\n expect(isRelative(\"not a url\")).toBe(true);\n});\n\nexport function getRelativePart(url: URL) {\n return url.pathname + url.search + url.hash;\n}\nundefined?.test(\"getRelativePart\", ({ expect }) => {\n // Test with various URLs\n expect(getRelativePart(new URL(\"https://example.com\"))).toBe(\"/\");\n expect(getRelativePart(new URL(\"https://example.com/path\"))).toBe(\"/path\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value\"))).toBe(\"/path?query=value\");\n expect(getRelativePart(new URL(\"https://example.com/path#hash\"))).toBe(\"/path#hash\");\n expect(getRelativePart(new URL(\"https://example.com/path?query=value#hash\"))).toBe(\"/path?query=value#hash\");\n\n // Test with different domains but same paths\n const url1 = new URL(\"https://example.com/path?query=value#hash\");\n const url2 = new URL(\"https://different.com/path?query=value#hash\");\n expect(getRelativePart(url1)).toBe(getRelativePart(url2));\n});\n\n/**\n * A template literal tag that returns a URL.\n *\n * Any values passed are encoded.\n */\nexport function url(strings: TemplateStringsArray | readonly string[], ...values: (string | number | boolean)[]): URL {\n return new URL(urlString(strings, ...values));\n}\nundefined?.test(\"url\", ({ expect }) => {\n // Test with no interpolation\n expect(url`https://example.com`).toBeInstanceOf(URL);\n expect(url`https://example.com`.href).toBe(\"https://example.com/\");\n\n // Test with string interpolation\n expect(url`https://example.com/${\"path\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}`.pathname).toBe(\"/path\");\n\n // Test with number interpolation\n expect(url`https://example.com/${42}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${42}`.pathname).toBe(\"/42\");\n\n // Test with boolean interpolation\n expect(url`https://example.com/${true}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${true}`.pathname).toBe(\"/true\");\n\n // Test with special characters in interpolation\n expect(url`https://example.com/${\"path with spaces\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path with spaces\"}`.pathname).toBe(\"/path%20with%20spaces\");\n\n // Test with multiple interpolations\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`).toBeInstanceOf(URL);\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.pathname).toBe(\"/path\");\n expect(url`https://example.com/${\"path\"}?query=${\"value\"}`.search).toBe(\"?query=value\");\n});\n\n\n/**\n * A template literal tag that returns a URL string.\n *\n * Any values passed are encoded.\n */\nexport function urlString(strings: TemplateStringsArray | readonly string[], ...values: (string | number | boolean)[]): string {\n return templateIdentity(strings, ...values.map(encodeURIComponent));\n}\nundefined?.test(\"urlString\", ({ expect }) => {\n // Test with no interpolation\n expect(urlString`https://example.com`).toBe(\"https://example.com\");\n\n // Test with string interpolation\n expect(urlString`https://example.com/${\"path\"}`).toBe(\"https://example.com/path\");\n\n // Test with number interpolation\n expect(urlString`https://example.com/${42}`).toBe(\"https://example.com/42\");\n\n // Test with boolean interpolation\n expect(urlString`https://example.com/${true}`).toBe(\"https://example.com/true\");\n\n // Test with special characters in interpolation\n expect(urlString`https://example.com/${\"path with spaces\"}`).toBe(\"https://example.com/path%20with%20spaces\");\n expect(urlString`https://example.com/${\"?&=\"}`).toBe(\"https://example.com/%3F%26%3D\");\n\n // Test with multiple interpolations\n expect(urlString`https://example.com/${\"path\"}?query=${\"value\"}`).toBe(\"https://example.com/path?query=value\");\n expect(urlString`https://example.com/${\"path\"}?query=${\"value with spaces\"}`).toBe(\"https://example.com/path?query=value%20with%20spaces\");\n});\n\nexport function isChildUrl(parentUrl: URL, maybeChildUrl: URL) {\n return parentUrl.origin === maybeChildUrl.origin\n && isChildPath(parentUrl.pathname, maybeChildUrl.pathname)\n && [...parentUrl.searchParams].every(([key, value]) => maybeChildUrl.searchParams.get(key) === value)\n && (!parentUrl.hash || parentUrl.hash === maybeChildUrl.hash);\n}\nundefined?.test(\"isChildUrl\", ({ expect }) => {\n // true\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value\"))).toBe(true);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(true);\n\n // false\n expect(isChildUrl(new URL(\"https://abc.com\"), new URL(\"https://example.com\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://abc.com/\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com\"), new URL(\"https://abc.com/path?query=value#hash\"))).toBe(false);\n expect(isChildUrl(new URL(\"https://example.com?query=value123\"), new URL(\"https://example.com/path?query=value#hash\"))).toBe(false);\n});\n\nexport function isChildPath(parentPath: string, maybeChildPath: string) {\n parentPath = parentPath.endsWith(\"/\") ? parentPath : parentPath + \"/\";\n maybeChildPath = maybeChildPath.endsWith(\"/\") ? maybeChildPath : maybeChildPath + \"/\";\n return maybeChildPath.startsWith(parentPath);\n}\nundefined?.test(\"isSubPath\", ({ expect }) => {\n expect(isChildPath(\"/\", \"/\")).toBe(true);\n expect(isChildPath(\"/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path/\", \"/path/abc\")).toBe(true);\n expect(isChildPath(\"/path\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path\", \"/path-abc/\")).toBe(false);\n expect(isChildPath(\"/path/\", \"/path-abc\")).toBe(false);\n expect(isChildPath(\"/path/\", \"/path-abc/\")).toBe(false);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2C;AAC3C,qBAAiC;AAE1B,SAAS,oBAAoB,MAAyC;AAC3E,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,IAAI;AAAA,EACxB,SAAS,GAAG;AACV,WAAO;AAAA,EACT;AACF;AAaO,SAAS,WAAWA,MAAa;AACtC,SAAO,CAAC,CAAC,iBAAiBA,IAAG;AAC/B;AAaO,SAAS,gBAAgB,U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